From 6051c37302ffc041c2dd89f1ea6eb0acaeb7f445 Mon Sep 17 00:00:00 2001 From: Nikolay Novikov Date: Sat, 7 Sep 2019 12:32:31 +0300 Subject: [PATCH] code style --- src/Console/Commands/ModelMakeCommand.php | 4 +- src/Exceptions/ValidationException.php | 14 +- src/ModelTrait.php | 168 +++++++++--------- .../EloquentValidationServiceProvider.php | 20 +-- src/resources/lang/en/validation.php | 2 +- src/resources/lang/ru/validation.php | 2 +- src/resources/model.stub | 68 +++---- 7 files changed, 139 insertions(+), 139 deletions(-) diff --git a/src/Console/Commands/ModelMakeCommand.php b/src/Console/Commands/ModelMakeCommand.php index afef1f1..7bb3195 100644 --- a/src/Console/Commands/ModelMakeCommand.php +++ b/src/Console/Commands/ModelMakeCommand.php @@ -10,14 +10,14 @@ class ModelMakeCommand extends \Illuminate\Foundation\Console\ModelMakeCommand * @var string */ protected $name = 'make:model-validation'; - + /** * The console command description. * * @var string */ protected $description = 'Create a new Eloquent model class [eloquent-validation]'; - + /** * {@inheritDoc} * @see \Illuminate\Foundation\Console\ModelMakeCommand::getStub() diff --git a/src/Exceptions/ValidationException.php b/src/Exceptions/ValidationException.php index 0d2b282..562dca6 100644 --- a/src/Exceptions/ValidationException.php +++ b/src/Exceptions/ValidationException.php @@ -10,7 +10,7 @@ class ValidationException extends \Illuminate\Validation\ValidationException * @var int */ public $status = 400; - + /** * @param mixed $errors * @param mixed $response @@ -20,7 +20,7 @@ class ValidationException extends \Illuminate\Validation\ValidationException public function __construct($errors, $response = null, $errorBag = 'default', $prefix = null) { $prefix = $this->canonizePrefix($prefix); - + if ($errors instanceof \Illuminate\Validation\Validator) { if (is_null($prefix)) { $validator = $errors; @@ -36,7 +36,7 @@ public function __construct($errors, $response = null, $errorBag = 'default', $p if (is_scalar($errors)) { $errors = ['error' => $errors]; } - + $validator = \Validator::make([], []); foreach ($errors as $key => $items) { foreach ((array)$items as $item) { @@ -44,7 +44,7 @@ public function __construct($errors, $response = null, $errorBag = 'default', $p } } } - + parent::__construct($validator, $response, $errorBag); } @@ -57,19 +57,19 @@ protected function canonizePrefix($prefix) if (! is_iterable($prefix)) { return $prefix; } - + foreach ($prefix as $key => $item) { if (!is_scalar($item) || !mb_strlen($item)) { unset($prefix[$key]); } } - + if ($prefix) { $prefix = implode('.', $prefix) . '.'; } else { $prefix = null; } - + return $prefix; } } diff --git a/src/ModelTrait.php b/src/ModelTrait.php index 8fc2227..a76b1c0 100644 --- a/src/ModelTrait.php +++ b/src/ModelTrait.php @@ -11,46 +11,46 @@ trait ModelTrait * @var array */ private static $fillableDynamic = []; - + /** * Base validation rules for all attributes - * + * * @var mixed */ private $baseRules = 'scalar'; - + /** * Attribute names * * @var array */ private static $attributeNames; - + /** * "Save" after-validation - * + * * @param \Illuminate\Validation\Validator $validator * @return void */ public function saveValidation(\Illuminate\Validation\Validator $validator) { - + } - + /** * "Delete" after-validation - * + * * @param \Illuminate\Validation\Validator $validator * @return void */ public function deleteValidation(\Illuminate\Validation\Validator $validator) { - + } - + /** * @see \Illuminate\Database\Eloquent\Model - * + * * @param string $key * @param string $value */ @@ -59,27 +59,27 @@ public function setAttribute($key, $value) if (isset($this->trim) && in_array($key, $this->trim) && is_scalar($value) && mb_strlen($value)) { $value = trim($value); } - + if (isset($this->nullable) && in_array($key, $this->nullable) && $value === '') { $value = null; } - + if (isset($value) && in_array($key, $this->getDates())) { if (is_scalar($value)) { if (!is_numeric($value)) { $value = strtotime($value); } - + $value = date($this->getDateFormat(), $value); } } - + return parent::setAttribute($key, $value); } - + /** * Save validation - * + * * @param \Illuminate\Database\Eloquent\Builder $query * @param mixed $prefix * @param array $additionalRules @@ -91,66 +91,66 @@ public function scopeValidate(\Illuminate\Database\Eloquent\Builder $query, $pre $validator = \Validator::make($this->attributes, array_fill_keys(array_keys($this->attributes), $this->baseRules)); $validator->setAttributeNames($this->getAttributeNames()); $passes = $validator->passes(); - + // Handles if ($passes) { $validator = \Validator::make([], []); $validator->setAttributeNames($this->getAttributeNames()); - + $validator->after(function ($validator) { if (!empty($this->calculated)) { $this->handleUnchangeable($this->calculated, $validator, 'eloquent-validation::validation.calculated'); } - + if (!empty($this->unchangeable) && $this->exists) { $this->handleUnchangeable($this->unchangeable, $validator); } - + if (!empty($this->unique)) { $this->handleUnique($this->unique, $validator); } }); - + $passes = $validator->passes(); } - + // Additional rules if ($passes && $additionalRules) { $validator = \Validator::make($this->attributes, $additionalRules); $validator->setAttributeNames($this->getAttributeNames()); - + $passes = $validator->passes(); } - + // Rules if ($passes) { $validator = \Validator::make($this->attributes, $this->canonizeRules()); $validator->setAttributeNames($this->getAttributeNames()); - + $passes = $validator->passes(); } - + // After validation if ($passes) { $validator = \Validator::make($this->attributes, []); $validator->setAttributeNames($this->getAttributeNames()); - + $validator->after([$this, 'saveValidation']); - + $passes = $validator->passes(); } - + if (! $passes) { throw new ValidationException($validator, null, 'default', $prefix); } - + return $this; } - + /** * Delete validation - * + * * @param \Illuminate\Database\Eloquent\Builder $query * @param mixed $prefix * @param array $additionalRules @@ -159,55 +159,55 @@ public function scopeValidate(\Illuminate\Database\Eloquent\Builder $query, $pre public function scopeValidateDelete(\Illuminate\Database\Eloquent\Builder $query, $prefix = null, array $additionalRules = []) { $passes = true; - + // Additional rules if ($additionalRules) { $validator = \Validator::make($this->attributes, $additionalRules); $validator->setAttributeNames($this->getAttributeNames()); - + $passes = $validator->passes(); } - + // After validation if ($passes) { $validator = \Validator::make($this->attributes, []); $validator->setAttributeNames($this->getAttributeNames()); - + $validator->after([$this, 'deleteValidation']); - + $passes = $validator->passes(); } - + if (! $passes) { throw new ValidationException($validator, null, 'default', $prefix); } - + return $this; } - + /** * Temporary (for one query) list of "fillables" columns - * + * * @return \Illuminate\Database\Eloquent\Model */ public function scopeFields() { $args = func_get_args(); array_shift($args); - + if (!isset($args[0])) { $args[0] = []; } - + if (is_array($args[0])) { $args = $args[0]; } - + static::$fillableDynamic = &$args; - + return $this; } - + /** * @see \Illuminate\Database\Eloquent\Model::getFillable() * @@ -218,10 +218,10 @@ public function getFillable() if (!static::$fillableDynamic) { return parent::getFillable(); } - + return static::$fillableDynamic; } - + /** * @see \Illuminate\Database\Eloquent\Model::save() * @@ -232,13 +232,13 @@ public function save(array $options = []) { $list = []; static::$fillableDynamic = &$list; - + return parent::save($options); } - + /** * Set the attributes names - * + * * @param array $attributeNames * @return void */ @@ -246,45 +246,45 @@ public static function setAttributeNames(?array $attributeNames) { static::$attributeNames = &$attributeNames; } - + /** * Get the attributes names - * + * * @return array */ public function getAttributeNames() { if (is_null(static::$attributeNames)) { $attributeNames = []; - + if (\App::getLocale()) { $path = explode('\\', get_class($this)); - + $file = Str::snake(array_pop($path)); - + array_shift($path); $path = array_map([Str::class, 'snake'], $path); $dir = implode('/', $path); - + if (!$dir) { $dir = 'models'; } - + $attributeNames = trans($dir.'/'.$file.'.attributes'); if (! is_array($attributeNames)) { $attributeNames = []; } } - + static::$attributeNames = &$attributeNames; } - + return static::$attributeNames; } - + /** * Handle "unchangeable" - * + * * @param array $unchangeable * @param \Illuminate\Validation\Validator $validator * @param string $translate @@ -297,9 +297,9 @@ protected function handleUnchangeable( if ($this->isUnguarded()) { return; } - + $newAttributes = $this->attributes; - + foreach ($unchangeable as $name) { if (array_key_exists($name, $newAttributes) && !$this->originalIsEquivalent($name, $newAttributes[$name])) { $validator->errors()->add( @@ -309,10 +309,10 @@ protected function handleUnchangeable( } } } - + /** * Handle "unique" - * + * * @param array $uniques * @param \Illuminate\Validation\Validator $validator * @param string $translate @@ -324,10 +324,10 @@ protected function handleUnique( ) { $newAttributes = $this->attributes; $attributeNames = $this->getAttributeNames(); - + foreach ($uniques as $unique) { $builder = new $this; - + foreach ($unique as $field) { if (isset($newAttributes[$field])) { $builder = $builder->where($field, '=', $newAttributes[$field]); @@ -335,76 +335,76 @@ protected function handleUnique( $builder = $builder->whereNull($field); } } - + if ($this->primaryKey && isset($newAttributes[$this->primaryKey])) { $builder = $builder->where($this->primaryKey, '!=', $newAttributes[$this->primaryKey]); } - + if (in_array(\Illuminate\Database\Eloquent\SoftDeletes::class, class_uses($builder->getModel()))) { $builder = $builder->withTrashed(); } - + if ($builder->first()) { $params = ['attributes' => []]; foreach ($unique as $field) { $params['attributes'][] = $attributeNames[$field] ?? $field; } $params['attributes'] = implode(', ', $params['attributes']); - + $validator->errors()->add($field, trans($translate, $params)); } } } - + /** * @return array */ private function canonizeRules() { $rules = $this->rules ?? []; - + // "unique" validation $hasPrimary = ($this->primaryKey && isset($this->attributes[$this->primaryKey])); - + foreach ($rules as $field => &$fieldRules) { if (! is_array($fieldRules)) { $fieldRules = explode('|', $fieldRules); } - + foreach ($fieldRules as $key => $rule) { $rule = explode(':', $rule, 2); - + if (mb_strtolower($rule[0]) == 'unique') { if (isset($rule[1])) { $rule[1] = explode(',', $rule[1]); } else { $rule[1] = []; } - + if (count($rule[1]) == 0) { $rule[1][] = $this->getConnectionName() ? $this->getConnectionName().'.'.$this->getTable() : $this->getTable(); } - + if (count($rule[1]) == 1) { $rule[1][] = $field; } - + if (count($rule[1]) == 2 && $hasPrimary) { $rule[1][] = $this->attributes[$this->primaryKey]; $rule[1][] = $this->primaryKey; } - + $rule[1] = implode(',', $rule[1]); $rule = implode(':', $rule); - + $fieldRules[$key] = $rule; } } } unset($fieldRules); - + return $rules; } } diff --git a/src/Providers/EloquentValidationServiceProvider.php b/src/Providers/EloquentValidationServiceProvider.php index 19a9a03..35a5b08 100644 --- a/src/Providers/EloquentValidationServiceProvider.php +++ b/src/Providers/EloquentValidationServiceProvider.php @@ -18,25 +18,25 @@ public function boot() { return ( is_scalar($value) || is_null($value) || (is_object($value) && method_exists($value, '__toString')) ); }); - + \Validator::replacer('scalar', function ($message, $attribute, $rule, $parameters, $validator) { return trans( 'eloquent-validation::validation.scalar', ['attribute' => $validator->getDisplayableAttribute($attribute)] ); }); - - + + // "config" validation \Validator::extend('config', function ($attribute, $value, $parameters, $validator) { if (empty($parameters[0])) { throw new \Exception('Parameter required for "config" rule!'); } - + return isset(config($parameters[0])[$value]); }); - + \Validator::replacer('config', function ($message, $attribute, $rule, $parameters, $validator) { return trans( @@ -44,13 +44,13 @@ public function boot() ['attribute' => $validator->getDisplayableAttribute($attribute)] ); }); - - + + // langs $this->loadTranslationsFrom(__DIR__.'/../resources/lang/', 'eloquent-validation'); $this->publishes([__DIR__.'/../resources/lang/' => resource_path('lang/vendor/eloquent-validation')]); - - + + // commands if ($this->app->runningInConsole()) { $this->commands([ @@ -66,6 +66,6 @@ public function boot() */ public function register() { - + } } diff --git a/src/resources/lang/en/validation.php b/src/resources/lang/en/validation.php index 176b119..12608cb 100644 --- a/src/resources/lang/en/validation.php +++ b/src/resources/lang/en/validation.php @@ -3,7 +3,7 @@ return [ 'scalar' => 'The :attribute must be scalar.', 'config' => 'The :attribute attribute must contain value from directory.', - + 'calculated' => 'Field :attribute calculated automatically.', 'unchangeable' => 'Field :attribute cannot be changed.', 'unique' => 'The combination of fields :attributes must be unique.', diff --git a/src/resources/lang/ru/validation.php b/src/resources/lang/ru/validation.php index e7eadfb..300ef8c 100644 --- a/src/resources/lang/ru/validation.php +++ b/src/resources/lang/ru/validation.php @@ -3,7 +3,7 @@ return [ 'scalar' => 'Поле :attribute должно быть скалярной величиной.', 'config' => 'Поле :attribute должно содержать значение из справочника.', - + 'calculated' => 'Поле :attribute вычисляется автоматически.', 'unchangeable' => 'Поле :attribute не может быть изменено.', 'unique' => 'Сочетание полей :attributes должно быть уникальным.', diff --git a/src/resources/model.stub b/src/resources/model.stub index 442c71e..47efaab 100644 --- a/src/resources/model.stub +++ b/src/resources/model.stub @@ -7,7 +7,7 @@ use Illuminate\Database\Eloquent\Model; class DummyClass extends Model { use \AnourValar\EloquentValidation\ModelTrait; - + /** * The connection name for the model. * @@ -28,75 +28,75 @@ class DummyClass extends Model * @var string */ protected $primaryKey = 'id'; - + /** * Indicates if the IDs are auto-incrementing. * * @var bool */ public $incrementing = true; - + /** * Indicates if the model should be timestamped. * * @var bool */ public $timestamps = true; - + /** * Validation rules - * + * * @var array */ protected $rules = [ - + ]; - + /** * Trim columns - * + * * @var array */ protected $trim = [ - + ]; - + /** * '' => null convertation - * + * * @var array */ protected $nullable = [ - + ]; - + /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = [ - + ]; - + /** * The attributes that should be hidden for serialization. * * @var array */ protected $hidden = [ - + ]; - + /** * The model's attributes. (default) * * @var array */ protected $attributes = [ - + ]; - + /** * The attributes that should be cast to native types. * @@ -104,41 +104,41 @@ class DummyClass extends Model */ protected $casts = [ 'id' => 'integer', - + 'created_at' => 'datetime', 'updated_at' => 'datetime', ]; - + /** * Calculated columns - * + * * @var array */ protected $calculated = [ - + ]; - + /** * Immutable columns - * + * * @var array */ protected $unchangeable = [ - + ]; - + /** * Unique columns sets - * + * * @var array */ protected $unique = [ - + ]; - + /** * "Save" after-validation - * + * * @param \Illuminate\Validation\Validator $validator * @return void */ @@ -147,15 +147,15 @@ class DummyClass extends Model //$data = $validator->getData(); //$validator->errors()->add('id', trans('models/DummyClass.id_not_exists')); } - + /** * "Delete" after-validation - * + * * @param \Illuminate\Validation\Validator $validator * @return void */ public function deleteValidation(\Illuminate\Validation\Validator $validator) { - + } }