├── config └── datos-abiertos.php ├── .styleci.yml ├── src ├── Facades │ ├── Colegios.php │ ├── Divipola.php │ └── OrganismosTransito.php ├── Datasets │ ├── Divipola.php │ ├── OrganismosTransito.php │ ├── Colegios.php │ └── BaseDataset.php └── DatosAbiertosServiceProvider.php ├── LICENSE.md ├── composer.json ├── CONTRIBUTING.md └── README.md /config/datos-abiertos.php: -------------------------------------------------------------------------------- 1 | env('DATOS_ABIERTOS_TOKEN', ''), 5 | ]; 6 | -------------------------------------------------------------------------------- /.styleci.yml: -------------------------------------------------------------------------------- 1 | preset: laravel 2 | 3 | disabled: 4 | - single_class_element_per_statement 5 | - hash_to_slash_comment 6 | - concat_without_spaces 7 | -------------------------------------------------------------------------------- /src/Facades/Colegios.php: -------------------------------------------------------------------------------- 1 | app->runningInConsole()) { 18 | $this->publishes([ 19 | __DIR__ . '/../config/datos-abiertos.php' => config_path('datos-abiertos.php'), 20 | ], 'datos-abiertos'); 21 | } 22 | } 23 | 24 | /** 25 | * Register the application services. 26 | */ 27 | public function register() 28 | { 29 | // Automatically apply the package configuration 30 | $this->mergeConfigFrom(__DIR__ . '/../config/datos-abiertos.php', 'datos-abiertos'); 31 | 32 | // Register the main class to use with the facade 33 | $this->app->singleton('colegios', function () { 34 | return new Colegios; 35 | }); 36 | 37 | $this->app->singleton('divipola', function () { 38 | return new Divipola; 39 | }); 40 | 41 | $this->app->singleton('organismo-transito', function () { 42 | return new OrganismosTransito; 43 | }); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "andreshg112/datos-abiertos", 3 | "description": "Consulta la API de Datos Abiertos del Gobierno de Colombia en la plataforma https://www.datos.gov.co", 4 | "keywords": [ 5 | "andreshg112", 6 | "datos-abiertos", 7 | "divipola" 8 | ], 9 | "homepage": "https://github.com/andreshg112/datos-abiertos", 10 | "license": "MIT", 11 | "type": "library", 12 | "authors": [ 13 | { 14 | "name": "Andrés Herrera García", 15 | "email": "andreshg112@gmail.com", 16 | "role": "Developer" 17 | } 18 | ], 19 | "require": { 20 | "php": "^7.1", 21 | "allejo/php-soda": "^1.0", 22 | "illuminate/support": "^5.5", 23 | "spatie/macroable": "^1.0" 24 | }, 25 | "require-dev": { 26 | "codedungeon/phpunit-result-printer": "^0.26.1", 27 | "orchestra/testbench": "3.8.*", 28 | "phpunit/phpunit": "^7.0" 29 | }, 30 | "autoload": { 31 | "psr-4": { 32 | "Andreshg112\\DatosAbiertos\\": "src" 33 | } 34 | }, 35 | "autoload-dev": { 36 | "psr-4": { 37 | "Andreshg112\\DatosAbiertos\\Tests\\": "tests" 38 | } 39 | }, 40 | "scripts": { 41 | "test": "vendor/bin/phpunit", 42 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage" 43 | }, 44 | "config": { 45 | "sort-packages": true 46 | }, 47 | "extra": { 48 | "laravel": { 49 | "providers": [ 50 | "Andreshg112\\DatosAbiertos\\DatosAbiertosServiceProvider" 51 | ], 52 | "aliases": { 53 | "Colegios": "Andreshg112\\DatosAbiertos\\Facades\\Colegios", 54 | "Divipola": "Andreshg112\\DatosAbiertos\\Facades\\Divipola", 55 | "OrganismosTransito": "Andreshg112\\DatosAbiertos\\Facades\\OrganismosTransito" 56 | } 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /src/Datasets/BaseDataset.php: -------------------------------------------------------------------------------- 1 | sodaClient = new SodaClient(self::SOURCE_DOMAIN, config('datos-abiertos.token')); 27 | 28 | $this->sodaDataset = new SodaDataset($this->sodaClient, $this->getDatasetIdentifier()); 29 | 30 | $this->addMacroMethods(); 31 | } 32 | 33 | #endregion 34 | 35 | #region Funciones abstractas 36 | 37 | /** 38 | * Retorna las columnas del dataset (recurso). 39 | * 40 | * @return string[] 41 | */ 42 | abstract public function getColumns(); 43 | 44 | /** 45 | * Retorna el identificador del dataset (recurso). 46 | * 47 | * @return string 48 | */ 49 | abstract protected function getDatasetIdentifier(); 50 | 51 | /** 52 | * Retorna la columna cuyo valor es único dentro del recurso (dataset). 53 | * 54 | * @return string 55 | */ 56 | abstract protected function getUniqueColumn(); 57 | 58 | #endregion 59 | 60 | #region Funciones 61 | 62 | /** 63 | * Agrega métodos dinámicos para consultar un dataset (recurso) por cada columna que tenga. 64 | * 65 | * @return void 66 | */ 67 | private function addMacroMethods() 68 | { 69 | $columns = $this->getColumns(); 70 | 71 | foreach ($columns as $column) { 72 | static::macro( 73 | 'where' . ucfirst(Str::camel($column)), 74 | function ($value) use ($column) { 75 | return $this->getData([$column => $value]); 76 | } 77 | ); 78 | } 79 | } 80 | 81 | /** 82 | * Undocumented function. 83 | * 84 | * @param int|string $uniqueValue 85 | * @return array 86 | */ 87 | public function find($uniqueValue) 88 | { 89 | $data = $this->where($this->getUniqueColumn(), $uniqueValue); 90 | 91 | return $data[0] ?? null; 92 | } 93 | 94 | /** 95 | * Consulta el listado del recurso de acuerdo a los parámetros. 96 | * Si no se especifican, por defecto trae todos. 97 | * Para saber cómo usar los filtros, consultar en el siguiente enlace: 98 | * https://github.com/allejo/PhpSoda/wiki/Simple-Filters. 99 | * 100 | * @param array|string|\allejo\Socrata\SoqlQuery $filterOrSoqlQuery Los parámetros de la consulta. 101 | * @return array[] 102 | */ 103 | public function getData($filterOrSoqlQuery = '') 104 | { 105 | $data = $this->sodaDataset->getData($filterOrSoqlQuery); 106 | 107 | return $data; 108 | } 109 | 110 | /** 111 | * Consulta registros del recurso por el valor de una columna. 112 | * 113 | * @param string $column 114 | * @param int|string $value 115 | * @return array[] 116 | */ 117 | public function where(string $column, $value) 118 | { 119 | return $this->getData([$column => $value]); 120 | } 121 | 122 | #endregion 123 | } 124 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [Datos Abiertos de Colombia](https://www.datos.gov.co) para Laravel 2 | 3 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/andreshg112/datos-abiertos.svg?style=flat-square)](https://packagist.org/packages/andreshg112/datos-abiertos) 4 | [![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) 5 | [![Build Status](https://travis-ci.com/andreshg112/datos-abiertos.svg?branch=master)](https://travis-ci.com/andreshg112/datos-abiertos) 6 | [![StyleCI](https://styleci.io/repos/177488663/shield)](https://styleci.io/repos/177488663) 7 | [![Quality Score](https://img.shields.io/scrutinizer/g/andreshg112/datos-abiertos.svg?style=flat-square)](https://scrutinizer-ci.com/g/andreshg112/datos-abiertos) 8 | [![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/andreshg112/datos-abiertos/master.svg?style=flat-square)](https://scrutinizer-ci.com/g/andreshg112/datos-abiertos/?branch=master) 9 | [![Total Downloads](https://img.shields.io/packagist/dt/andreshg112/datos-abiertos.svg?style=flat-square)](https://packagist.org/packages/andreshg112/datos-abiertos) 10 | 11 | Este paquete encapsula las consultas a la API de [Datos Abiertos del Gobierno de Colombia](https://www.datos.gov.co). 12 | 13 | ## Recursos implementados 14 | 15 | - [ESTABLECIMIENTOS EDUCATIVOS DE PREESCOLAR, BÁSICA](https://www.datos.gov.co/Educaci-n/ESTABLECIMIENTOS-EDUCATIVOS-DE-PREESCOLAR-B-SICA/ea56-rtcx/data) (`\Andreshg112\DatosAbiertos\Facades\Colegios`). 16 | 17 | - [Códigos de la Divisón Político-Administrativa del país](https://www.datos.gov.co/Mapas-Nacionales/DIVIPOLA-Codigos-municipios/gdxc-w37w) (`\Andreshg112\DatosAbiertos\Facades\Divipola`). 18 | 19 | - [Organismos de Tránsito](https://www.datos.gov.co/Transporte/ORGANISMO-DE-TR-NSITO/88yh-mmbj) (`\Andreshg112\DatosAbiertos\Facades\OrganismosTransito`). 20 | 21 | > Si deseas que desarrolle una consulta a otro recurso de datos.gov.co, puedes realizar la petición en los [Issues](../../issues). 22 | 23 | ## Requisitos 24 | 25 | - Laravel >= 5.5 26 | - PHP >= 7.1.x 27 | 28 | > Si quieres soporte para una versión inferior a las especificadas, por favor deja la petición en los [Issues](../../issues) y veré qué puedo hacer. 29 | 30 | ## Instalación 31 | 32 | Puedes instalar el paquete a través de composer: 33 | 34 | ```bash 35 | composer require andreshg112/datos-abiertos 36 | ``` 37 | 38 | Este paquete usa [Laravel Package Discovery](https://laravel.com/docs/5.5/packages#package-discovery) por lo que, si usas Laravel 5.5 o superior, no debes preocuparte agregar `\Andreshg112\DatosAbiertos\DatosAbiertosServiceProvider` al listado de `providers` en el archivo `config/app.php`. 39 | 40 | ## Uso 41 | 42 | ### Uso básico 43 | 44 | Cada recurso hereda de `\Andreshg112\DatosAbiertos\Datasets\BaseDataset`, el cual tiene el método `getData($filterOrSoqlQuery = '')` que permite consultar todos los registros del recurso o [filtrar](#uso-de-filtros) de acuerdo a los parámetros. 45 | 46 | Por ejemplo: 47 | 48 | ```php 49 | use Andreshg112\DatosAbiertos\Facades\Divipola; 50 | 51 | // Listado total de municipios: 52 | $data = Divipola::getData(); 53 | ``` 54 | 55 | ### Uso de filtros 56 | 57 | > En la [definición de la API de Divipola](https://dev.socrata.com/foundry/www.datos.gov.co/gdxc-w37w) puedes encontrar los detalles del recurso y el uso de filtros. 58 | 59 | > Advertencia: La API de datos.gov.co distingue mayúsculas y minúsculas. Por lo tanto si buscas, por ejemplo, `nom_mpio=valledupar` no aparecerá porque debe tener la `V` mayúscula. 60 | 61 | ```php 62 | use Andreshg112\DatosAbiertos\Facades\Divipola; 63 | 64 | // Para filtrar por código de departamento puedes hacer cualquiera de las siguientes formas: 65 | 66 | $filterOrSoqlQuery = 'cod_depto=20'; // esta 67 | 68 | $filterOrSoqlQuery = ['cod_depto' => '20']; // o esta 69 | 70 | $data = Divipola::getData($filterOrSoqlQuery); 71 | ``` 72 | 73 | > Este paquete usa [allejo/php-soda](https://github.com/allejo/PhpSoda) para realizar las peticiones a los recursos de datos.gov.co usando Socrata Open Data API (SODA), por lo tanto `$filterOrSoqlQuery` puede ser cualquiera de los parámetros aceptados por la función `\allejo\Socrata\SodaDataset::getData(filterOrSoqlQuery)`. Para usar filtros avanzados, dirígete a su [documentación](https://github.com/allejo/PhpSoda/wiki/Simple-Filters) (en inglés). 74 | 75 | ## Extender la funcionalidad 76 | 77 | ### Macroable 78 | 79 | La clase padre `\Andreshg112\DatosAbiertos\Datasets\BaseDataset` de los recursos (datasets) usa el trait `\Spatie\Macroable\Macroable` de [spatie/macroable](https://github.com/spatie/macroable), por lo que puedes extender la funcionalidad de cada recurso de la siguiente manera: 80 | 81 | ```php 82 | // En el archivo app/Providers/AppServiceProvider.php: 83 | 84 | use Andreshg112\DatosAbiertos\Facades\OrganismosTransito; 85 | 86 | class AppServiceProvider extends ServiceProvider 87 | { 88 | /** 89 | * Bootstrap any application services. 90 | * 91 | * @return void 92 | */ 93 | public function boot() 94 | { 95 | OrganismosTransito::macro('whereEstadoLimit', function($estado, $limit){ 96 | $filter = [ 97 | '$where' => "estado = '$estado'", // https://dev.socrata.com/docs/queries 98 | '$limit' => $limit, // 1, 2, 3, etc. 99 | ]; 100 | 101 | return $this->getData($filter); 102 | }); 103 | } 104 | } 105 | 106 | // Y luego, en cualquier otra parte: 107 | $data = OrganismosTransito::whereEstadoLimit('ACTIVO', 3); 108 | ``` 109 | 110 | Para más información, dirígete a su [documentación](https://github.com/spatie/macroable). 111 | 112 | ### Crear tu propio recurso 113 | 114 | Puedes crear tu propio dataset que herede de `\Andreshg112\DatosAbiertos\Datasets\BaseDataset` de la siguiente manera: 115 | 116 | > Este recurso será implementado en el paquete, solo se coloca de ejemplo. 117 | 118 | ```php 119 | La API no acepta tildes, `ñ` o caracteres especiales en los nombres. 161 | 162 | Luego, tendrás que hacer una [fachada](https://laravel.com/docs/5.5/facades) para la clase y está listo para usarse. Puede ser una [fachada en tiempo real](https://laravel.com/docs/5.5/facades#real-time-facades) colocando el namespace `Facades` antes del namespace de la clase, así: 163 | 164 | ```php 165 | use Facades\App\Datasets\Colegios; 166 | ``` 167 | 168 | ## Métodos de los recursos (datasets) 169 | 170 | Todos los recursos permiten el [filtrado avanzado](https://dev.socrata.com/docs/queries) a través del método `getData($filterOrSoqlQuery)`, pero para búsquedas simples, se puede usar el método `where(string $column, $value)` de la siguiente manera: 171 | 172 | ```php 173 | use Facades\App\Datasets\Colegios; // Fachada en tiempo real. 174 | 175 | $data = Colegios::where('modelos_educativos', 'EDUCACIÓN TRADICIONAL'); 176 | ``` 177 | 178 | Las columnas del recurso o dataset (ya sea incluido o personalizado), que se indican en `getColumns()`, permiten acceden dinámicamente a métodos de acuerdo con los nombres transformados en camelCase, y el prefijo `where` con la primera letra mayúscula por ejemplo: 179 | 180 | ```php 181 | use Facades\App\Datasets\Colegios; 182 | use Andreshg112\DatosAbiertos\Facades\Divipola; 183 | use Andreshg112\DatosAbiertos\Facades\OrganismosTransito; 184 | 185 | // nombredepartamento 186 | Colegios::whereNombredepartamento('Cesar'); // d minúscula porque no tiene subguión. 187 | 188 | // nom_mpio 189 | Divipola::whereNomMpio('Valledupar'); // M mayúscula porque tiene subguión. 190 | 191 | // categor_a 192 | OrganismosTransito::whereCategorA('A'); // A mayúscula porque tiene un subguión antes. 193 | ``` 194 | 195 | Todos los métodos retornan un vector de registros (array de arrays). Si se desea consultar un solo registro a través de la columna con valor único, entonces se hace uso de la función `find($uniqueValue)`. Esto hace que el método solo retorne un solo registro (array) en vez de un vector de registros. Por ejemplo: 196 | 197 | ```php 198 | use Andreshg112\DatosAbiertos\Facades\Colegios; // Esta es la implementación incluída. 199 | 200 | $data = Colegios::find(147707000156); 201 | 202 | // Es equivalente a: 203 | $data = Colegios::whereCodigoestablecimiento(147707000156)[0] ?? null; 204 | 205 | // y a: 206 | $data = Colegios::where('codigoestablecimiento', 147707000156)[0] ?? null; 207 | 208 | ``` 209 | 210 | ### Columnas de valor único: 211 | 212 | - Colegios: codigo_establecimiento 213 | - Divipola: cod_mpio 214 | - OrganismosTransito: cod_divipola 215 | 216 | > Los nombres de las columnas están especificados en la definición de la API de cada recurso en la plataforma de [Datos Abiertos](https://www.datos.gov.co). 217 | 218 | ### Pruebas 219 | 220 | ```bash 221 | composer test 222 | ``` 223 | 224 | ### Registro de cambios 225 | 226 | Por favor, mira el listado de [Versiones](../../releases) para obtener más información sobre lo que ha cambiado recientemente. 227 | 228 | ## Contribuir 229 | 230 | Por favor, mira el archivo [CONTRIBUTING](CONTRIBUTING.md) (en inglés) para más detalles. 231 | 232 | ### Seguridad 233 | 234 | Si descubres una vulnerabilidad o fallo relacionado con seguridad, te agradezco que por favor me escribas a andreshg112@gmail.com en vez de hacerlo en el registro de errores. 235 | 236 | ## Créditos 237 | 238 | - [Andrés Herrera García](https://github.com/andreshg112) 239 | - [All Contributors](../../contributors) 240 | 241 | ## Licencia 242 | 243 | Licencia MIT. Por favor, mira el archivo [License File](LICENSE.md) (en inglés) para más información. 244 | 245 | ## Laravel Package Boilerplate 246 | 247 | Este paquete fue generado usando [Laravel Package Boilerplate](https://laravelpackageboilerplate.com). 248 | --------------------------------------------------------------------------------