ImportacionController.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace app\commands;
  3. use v1\models\Estado;
  4. use v1\models\Municipio;
  5. use yii\console\Controller;
  6. use yii\db\Expression;
  7. use yii\helpers\Json;
  8. class ImportacionController extends Controller {
  9. public $truncate = null;
  10. private $_db = null;
  11. private $_actions = [
  12. 'actionProveedores',
  13. ];
  14. public function options($actionID) {
  15. return [
  16. 'truncate',
  17. ];
  18. }
  19. public function actionIndex() {
  20. if ($this->truncate == 1) {
  21. $this->actionTruncate();
  22. }
  23. foreach ($this->_actions as $action) {
  24. $this->{$action}();
  25. }
  26. }
  27. public function actionMunicipios() {
  28. $this->stdout("Guardando Sincronizar estados\n");
  29. $basePath = \Yii::getAlias('@app');
  30. $file = fopen("{$basePath}/csv/municipios.csv", "r");
  31. if ($file !== false) {
  32. while (($data = fgetcsv($file, 1000)) !== false) {
  33. @list($claveEstado, $nombreEstado, $abreviado, $claveMun, $nombreMun) = $data;
  34. $municipio = null;
  35. $estado = null;
  36. $municipio = Municipio::find()
  37. ->andWhere([
  38. 'clave' => intval($claveMun),
  39. 'nombre' => trim($nombreMun)
  40. ])
  41. ->orderBy('clave')
  42. ->one();
  43. if ($municipio === null) {
  44. $this->stdout('No se encontró el Municipio');
  45. continue;
  46. }
  47. $this->stdout($municipio->nombre);
  48. $estado = Estado::find()
  49. ->andWhere([
  50. 'clave' => intval($claveEstado),
  51. 'nombre' => trim($nombreEstado)
  52. ])
  53. ->one();
  54. if ($estado === null) {
  55. $this->stdout('No se encontró el Municipio');
  56. continue;
  57. }
  58. $municipio->idEstado = $estado->id;
  59. $this->stdout("{$estado->nombre}\n");
  60. if (!$municipio->save()) {
  61. $errores = Json::encode($municipio->getFirstErrors());
  62. $this->stderr("{$errores}\n");
  63. }
  64. }
  65. }
  66. fclose($file);
  67. }
  68. }