Commit 13ffaf8e467263cc493487cb02ed8000c54f26e6

Authored by Mihail
1 parent 0cb8c7a5

add error handler in brands and image loading

backend/components/base/BaseActiveRecord.php
@@ -9,12 +9,16 @@ @@ -9,12 +9,16 @@
9 namespace backend\components\base; 9 namespace backend\components\base;
10 10
11 11
12 -use yii\base\ErrorException; 12 +use common\components\exceptions\OrdinaryActiveRecordException;
13 13
14 class BaseActiveRecord extends \yii\db\ActiveRecord { 14 class BaseActiveRecord extends \yii\db\ActiveRecord {
15 15
  16 + /**
  17 + * @param int $row
  18 + * @throws OrdinaryActiveRecordException
  19 + * выбрасывает специальное исключения, наполняя сообщение с массива ошибок модели (после попытки валидации)
  20 + */
16 public function throwStringErrorException($row = 0){ 21 public function throwStringErrorException($row = 0){
17 -  
18 $errors_str = ''; 22 $errors_str = '';
19 if ($row != 0) { 23 if ($row != 0) {
20 $errors_str = "Ошибка в строке {$row} "; 24 $errors_str = "Ошибка в строке {$row} ";
@@ -22,7 +26,9 @@ class BaseActiveRecord extends \yii\db\ActiveRecord { @@ -22,7 +26,9 @@ class BaseActiveRecord extends \yii\db\ActiveRecord {
22 foreach ($this->getErrors() as $error) { 26 foreach ($this->getErrors() as $error) {
23 $errors_str .= implode( array_values($error) ); 27 $errors_str .= implode( array_values($error) );
24 } 28 }
25 - throw new ErrorException( $errors_str ); 29 + $ex = new OrdinaryActiveRecordException( $errors_str );
  30 + $ex->active_record_name = static::formName();
  31 + throw $ex;
26 } 32 }
27 33
28 } 34 }
29 \ No newline at end of file 35 \ No newline at end of file
backend/controllers/BrandsController.php
@@ -9,6 +9,7 @@ use yii\web\Controller; @@ -9,6 +9,7 @@ use yii\web\Controller;
9 use yii\web\NotFoundHttpException; 9 use yii\web\NotFoundHttpException;
10 use yii\filters\VerbFilter; 10 use yii\filters\VerbFilter;
11 use yii\filters\AccessControl; 11 use yii\filters\AccessControl;
  12 +use yii\web\UploadedFile;
12 13
13 /** 14 /**
14 * BrandsController implements the CRUD actions for Brands model. 15 * BrandsController implements the CRUD actions for Brands model.
@@ -82,14 +83,8 @@ class BrandsController extends Controller @@ -82,14 +83,8 @@ class BrandsController extends Controller
82 { 83 {
83 $model = new Brands(); 84 $model = new Brands();
84 85
85 - if ($model->load(Yii::$app->request->post()) && $model->save()) {  
86 - //return $this->redirect(['view', 'id' => $model->BRAND]);  
87 - return $this->redirect(['index']);  
88 - } else {  
89 - return $this->render('create', [  
90 - 'model' => $model,  
91 - ]);  
92 - } 86 + return $this->saveIMG( $model, 'create' );
  87 +
93 } 88 }
94 89
95 /** 90 /**
@@ -102,14 +97,8 @@ class BrandsController extends Controller @@ -102,14 +97,8 @@ class BrandsController extends Controller
102 { 97 {
103 $model = $this->findModel($id); 98 $model = $this->findModel($id);
104 99
105 - if ($model->load(Yii::$app->request->post()) && $model->save()) {  
106 - //return $this->redirect(['view', 'id' => $model->BRAND]);  
107 - return $this->redirect(['index']);  
108 - } else {  
109 - return $this->render('update', [  
110 - 'model' => $model,  
111 - ]);  
112 - } 100 + return $this->saveIMG( $model, 'update' );
  101 +
113 } 102 }
114 103
115 /** 104 /**
@@ -140,4 +129,31 @@ class BrandsController extends Controller @@ -140,4 +129,31 @@ class BrandsController extends Controller
140 throw new NotFoundHttpException('The requested page does not exist.'); 129 throw new NotFoundHttpException('The requested page does not exist.');
141 } 130 }
142 } 131 }
  132 +
  133 + /**
  134 + * @param $model
  135 + * @return string|\yii\web\Response
  136 + * сохраняет картинку и валидирует модель
  137 + * выбрасывает исключение в случае ошибки
  138 + */
  139 + protected function saveIMG( $model, $action ){
  140 + if( $model->load(Yii::$app->request->post()) ) {
  141 + $model->file = UploadedFile::getInstance($model, 'file');
  142 + $model->IMG = $model->file->name;
  143 + // первый проход - валидируем, сохраняем файл,
  144 + if ( $model->validate() ) {
  145 + // сохраним файл
  146 + $model->file->saveAs( Yii::getAlias('@storage') . '/files/brands/' . $model->IMG );
  147 + if ( $model->save() ) {
  148 + return $this->redirect(['index']);
  149 + }
  150 + }
  151 + $model->throwStringErrorException();
  152 + } else {
  153 + return $this->render($action, [
  154 + 'model' => $model,
  155 + ]);
  156 + }
  157 +
  158 + }
143 } 159 }
backend/controllers/ParserController.php
@@ -3,6 +3,7 @@ namespace backend\controllers; @@ -3,6 +3,7 @@ namespace backend\controllers;
3 3
4 use backend\models\Details; 4 use backend\models\Details;
5 use common\components\exceptions\CrossParsingException; 5 use common\components\exceptions\CrossParsingException;
  6 +use common\components\exceptions\OrdinaryActiveRecordException;
6 use common\components\exceptions\PriceParsingException; 7 use common\components\exceptions\PriceParsingException;
7 use common\components\exceptions\RgParsingException; 8 use common\components\exceptions\RgParsingException;
8 use common\components\ModelArrayValidator; 9 use common\components\ModelArrayValidator;
@@ -76,6 +77,10 @@ class ParserController extends BaseController @@ -76,6 +77,10 @@ class ParserController extends BaseController
76 $action_name = ['results']; 77 $action_name = ['results'];
77 }elseif ( $exception instanceof RgParsingException ) { 78 }elseif ( $exception instanceof RgParsingException ) {
78 $action_name = ['rg-grup/results']; 79 $action_name = ['rg-grup/results'];
  80 + }elseif ( $exception instanceof OrdinaryActiveRecordException ) {
  81 + // для обычной модели возвращаемся в index в качестве контроллера используем имя модели
  82 + $action_name = strtolower($exception->active_record_name);
  83 + $action_name = ["$action_name/index"];
79 } 84 }
80 85
81 if ( $exception !== null ) { 86 if ( $exception !== null ) {
backend/views/brands/_form.php
@@ -17,14 +17,22 @@ use yii\widgets\ActiveForm; @@ -17,14 +17,22 @@ use yii\widgets\ActiveForm;
17 echo $form->field($model, 'BRAND')->textInput(['maxlength' => true])->label('Название') 17 echo $form->field($model, 'BRAND')->textInput(['maxlength' => true])->label('Название')
18 ?> 18 ?>
19 19
20 - <?= $form->field($model, 'CONTENT')->textarea(['rows' => 6]) ?> 20 + <?= $form->field($model, 'CONTENT')->widget(\mihaildev\ckeditor\CKEditor::className(),[
  21 + 'editorOptions' => \mihaildev\elfinder\ElFinder::ckeditorOptions('elfinder',[
  22 + 'preset' => 'full', //разработанны стандартные настройки basic, standard, full данную возможность не обязательно использовать
  23 + 'inline' => false, //по умолчанию false]),
  24 + // 'filebrowserUploadUrl'=>Yii::$app->getUrlManager()->createUrl('news/images-upload')
  25 + ]
  26 + )
  27 + ]); ?>
21 <?= $form->field($model, 'if_oem')->checkbox() ?> 28 <?= $form->field($model, 'if_oem')->checkbox() ?>
22 - <?= $form->field($model, 'IMG')->fileInput() ?> 29 + <?= $form->field($model, 'file')->fileInput()->label(false)->hint('имя файла должно иметь только латинские символы и цифры',['tag'=>'span'])?>
23 30
24 31
25 <div class="form-group"> 32 <div class="form-group">
26 <?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Редактировать', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> 33 <?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Редактировать', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
27 </div> 34 </div>
  35 + <?= Html::a('Вернуться', ['index'], ['class' => 'btn btn-primary']) ?>
28 36
29 <?php ActiveForm::end(); ?> 37 <?php ActiveForm::end(); ?>
30 38
common/components/exceptions/OrdinaryActiveRecordException.php 0 → 100644
  1 +<?php
  2 +/**
  3 + * Created by PhpStorm.
  4 + * User: Tsurkanov
  5 + * Date: 30.11.2015
  6 + * Time: 17:36
  7 + */
  8 +
  9 +namespace common\components\exceptions;
  10 +
  11 +
  12 +use yii\base\UserException;
  13 +
  14 +class OrdinaryActiveRecordException extends UserException {
  15 + // для хранения имени AR где произошла ошибка
  16 + // используется для обработки ошибок
  17 + public $active_record_name = '';
  18 +}
0 \ No newline at end of file 19 \ No newline at end of file
common/models/Brands.php
@@ -2,6 +2,7 @@ @@ -2,6 +2,7 @@
2 2
3 namespace common\models; 3 namespace common\models;
4 4
  5 +use backend\components\base\BaseActiveRecord;
5 use Yii; 6 use Yii;
6 7
7 /** 8 /**
@@ -17,8 +18,10 @@ use Yii; @@ -17,8 +18,10 @@ use Yii;
17 * @property string $IMG 18 * @property string $IMG
18 * @property string $timestamp 19 * @property string $timestamp
19 */ 20 */
20 -class Brands extends \yii\db\ActiveRecord 21 +class Brands extends BaseActiveRecord
21 { 22 {
  23 + // для валидации выбранного пользователем файла
  24 + public $file;
22 /** 25 /**
23 * @inheritdoc 26 * @inheritdoc
24 */ 27 */
@@ -39,7 +42,9 @@ class Brands extends \yii\db\ActiveRecord @@ -39,7 +42,9 @@ class Brands extends \yii\db\ActiveRecord
39 [['timestamp'], 'safe'], 42 [['timestamp'], 'safe'],
40 [['BRAND'], 'string', 'max' => 100], 43 [['BRAND'], 'string', 'max' => 100],
41 [['tecdoc_logo'], 'string', 'max' => 50], 44 [['tecdoc_logo'], 'string', 'max' => 50],
42 - [['IMG'], 'string', 'max' => 255] 45 + ['IMG', 'string', 'max' => 255],
  46 + ['IMG', 'match', 'pattern' => '/[a-zA-Z0-9]+\.[a-zA-Z]+/', 'message' => 'имя файла изображения должно иметь только латинские символы и цифры'],
  47 + [['file'], 'image' ]
43 ]; 48 ];
44 } 49 }
45 50
@@ -1891,28 +1891,28 @@ @@ -1891,28 +1891,28 @@
1891 }, 1891 },
1892 { 1892 {
1893 "name": "sebastian/diff", 1893 "name": "sebastian/diff",
1894 - "version": "1.3.0", 1894 + "version": "1.4.1",
1895 "source": { 1895 "source": {
1896 "type": "git", 1896 "type": "git",
1897 "url": "https://github.com/sebastianbergmann/diff.git", 1897 "url": "https://github.com/sebastianbergmann/diff.git",
1898 - "reference": "863df9687835c62aa423a22412d26fa2ebde3fd3" 1898 + "reference": "13edfd8706462032c2f52b4b862974dd46b71c9e"
1899 }, 1899 },
1900 "dist": { 1900 "dist": {
1901 "type": "zip", 1901 "type": "zip",
1902 - "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/863df9687835c62aa423a22412d26fa2ebde3fd3",  
1903 - "reference": "863df9687835c62aa423a22412d26fa2ebde3fd3", 1902 + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/13edfd8706462032c2f52b4b862974dd46b71c9e",
  1903 + "reference": "13edfd8706462032c2f52b4b862974dd46b71c9e",
1904 "shasum": "" 1904 "shasum": ""
1905 }, 1905 },
1906 "require": { 1906 "require": {
1907 "php": ">=5.3.3" 1907 "php": ">=5.3.3"
1908 }, 1908 },
1909 "require-dev": { 1909 "require-dev": {
1910 - "phpunit/phpunit": "~4.2" 1910 + "phpunit/phpunit": "~4.8"
1911 }, 1911 },
1912 "type": "library", 1912 "type": "library",
1913 "extra": { 1913 "extra": {
1914 "branch-alias": { 1914 "branch-alias": {
1915 - "dev-master": "1.3-dev" 1915 + "dev-master": "1.4-dev"
1916 } 1916 }
1917 }, 1917 },
1918 "autoload": { 1918 "autoload": {
@@ -1935,11 +1935,11 @@ @@ -1935,11 +1935,11 @@
1935 } 1935 }
1936 ], 1936 ],
1937 "description": "Diff implementation", 1937 "description": "Diff implementation",
1938 - "homepage": "http://www.github.com/sebastianbergmann/diff", 1938 + "homepage": "https://github.com/sebastianbergmann/diff",
1939 "keywords": [ 1939 "keywords": [
1940 "diff" 1940 "diff"
1941 ], 1941 ],
1942 - "time": "2015-02-22 15:13:53" 1942 + "time": "2015-12-08 07:14:41"
1943 }, 1943 },
1944 { 1944 {
1945 "name": "sebastian/environment", 1945 "name": "sebastian/environment",
@@ -2110,16 +2110,16 @@ @@ -2110,16 +2110,16 @@
2110 }, 2110 },
2111 { 2111 {
2112 "name": "sebastian/recursion-context", 2112 "name": "sebastian/recursion-context",
2113 - "version": "1.0.1", 2113 + "version": "1.0.2",
2114 "source": { 2114 "source": {
2115 "type": "git", 2115 "type": "git",
2116 "url": "https://github.com/sebastianbergmann/recursion-context.git", 2116 "url": "https://github.com/sebastianbergmann/recursion-context.git",
2117 - "reference": "994d4a811bafe801fb06dccbee797863ba2792ba" 2117 + "reference": "913401df809e99e4f47b27cdd781f4a258d58791"
2118 }, 2118 },
2119 "dist": { 2119 "dist": {
2120 "type": "zip", 2120 "type": "zip",
2121 - "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/994d4a811bafe801fb06dccbee797863ba2792ba",  
2122 - "reference": "994d4a811bafe801fb06dccbee797863ba2792ba", 2121 + "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/913401df809e99e4f47b27cdd781f4a258d58791",
  2122 + "reference": "913401df809e99e4f47b27cdd781f4a258d58791",
2123 "shasum": "" 2123 "shasum": ""
2124 }, 2124 },
2125 "require": { 2125 "require": {
@@ -2159,7 +2159,7 @@ @@ -2159,7 +2159,7 @@
2159 ], 2159 ],
2160 "description": "Provides functionality to recursively process PHP variables", 2160 "description": "Provides functionality to recursively process PHP variables",
2161 "homepage": "http://www.github.com/sebastianbergmann/recursion-context", 2161 "homepage": "http://www.github.com/sebastianbergmann/recursion-context",
2162 - "time": "2015-06-21 08:04:50" 2162 + "time": "2015-11-11 19:50:13"
2163 }, 2163 },
2164 { 2164 {
2165 "name": "sebastian/version", 2165 "name": "sebastian/version",