Skip to content
This repository was archived by the owner on Jun 4, 2024. It is now read-only.

Extend generated validation rules #12

Merged
merged 2 commits into from
Aug 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
173 changes: 127 additions & 46 deletions src/lib/ValidationRulesBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,12 @@

namespace cebe\yii2openapi\lib;

use cebe\yii2openapi\lib\items\Attribute;
use cebe\yii2openapi\lib\items\DbModel;
use cebe\yii2openapi\lib\items\ValidationRule;
use function in_array;
use function preg_match;
use function strtolower;

class ValidationRulesBuilder
{
Expand All @@ -19,11 +23,14 @@ class ValidationRulesBuilder

/**
* @var array|ValidationRule[]
**/
*/
private $rules = [];

private $typeScope = [
'safe' => [], 'required' => [], 'int' => [], 'bool' => [], 'float' => [], 'string' => [], 'ref' => []
'required' => [],
'ref' => [],
'trim' => [],
'safe' => [],
];

public function __construct(DbModel $model)
Expand All @@ -34,13 +41,124 @@ public function __construct(DbModel $model)
/**
* @return array|\cebe\yii2openapi\lib\items\ValidationRule[]
*/
public function build(): array
public function build():array
{
$this->prepareTypeScope();
$this->rulesByType();

if (!empty($this->typeScope['trim'])) {
$this->rules[] = new ValidationRule($this->typeScope['trim'], 'trim');
}

if (!empty($this->typeScope['required'])) {
$this->rules[] = new ValidationRule($this->typeScope['required'], 'required');
}
if (!empty($this->typeScope['ref'])) {
$this->addExistRules($this->typeScope['ref']);
}
foreach ($this->model->attributes as $attribute) {
$this->resolveAttributeRules($attribute);
}
if (!empty($this->typeScope['safe'])) {
$this->rules[] = new ValidationRule($this->typeScope['safe'], 'safe');
}
return $this->rules;
}

private function resolveAttributeRules(Attribute $attribute):void
{
if ($attribute->isReadOnly()) {
return;
}
if ($attribute->isUnique()) {
$this->rules[] = new ValidationRule([$attribute->columnName], 'unique');
}
if ($attribute->phpType === 'bool') {
$this->rules[] = new ValidationRule([$attribute->columnName], 'boolean');
return;
}

if (in_array($attribute->dbType, ['date', 'time', 'datetime'], true)) {
$this->rules[] = new ValidationRule([$attribute->columnName], $attribute->dbType, []);
return;
}
if (in_array($attribute->phpType, ['int', 'double', 'float']) && !$attribute->isReference()) {
$this->addNumericRule($attribute);
return;
}
if ($attribute->phpType === 'string' && !$attribute->isReference()) {
$this->addStringRule($attribute);
}
if (!empty($attribute->enumValues)) {
$this->rules[] = new ValidationRule([$attribute->columnName], 'in', ['range' => $attribute->enumValues]);
return;
}
$this->addRulesByAttributeName($attribute);
}

private function addRulesByAttributeName(Attribute $attribute):void
{
//@TODO: probably also patterns for file, image
$patterns = [
'~e?mail~i' => 'email',
'~(url|site|website|href|link)~i' => 'url',
'~(ip|ipaddr)~i' => 'ip',
];
foreach ($patterns as $pattern => $validator) {
if (preg_match($pattern, strtolower($attribute->columnName))) {
$this->rules[] = new ValidationRule([$attribute->columnName], $validator);
return;
}
}
}

/**
* @param array|Attribute[] $relations
*/
private function addExistRules(array $relations):void
{
foreach ($relations as $attribute) {
if ($attribute->phpType === 'int') {
$this->addNumericRule($attribute);
} elseif ($attribute->phpType === 'string') {
$this->addStringRule($attribute);
}
$this->rules[] = new ValidationRule(
[$attribute->columnName],
'exist',
['targetRelation' => $attribute->camelName()]
);
}
}

private function addStringRule(Attribute $attribute):void
{
$params = [];
if ($attribute->maxLength === $attribute->minLength && $attribute->minLength !== null) {
$params['length'] = $attribute->minLength;
} else {
if ($attribute->minLength !== null) {
$params['min'] = $attribute->minLength;
}
if ($attribute->maxLength !== null) {
$params['max'] = $attribute->maxLength;
}
}
$this->rules[] = new ValidationRule([$attribute->columnName], 'string', $params);
}

private function addNumericRule(Attribute $attribute):void
{
$params = [];
if ($attribute->limits['min'] !== null) {
$params['min'] = $attribute->limits['min'];
}
if ($attribute->limits['max'] !== null) {
$params['max'] = $attribute->limits['max'];
}
$validator = $attribute->phpType === 'int' ? 'integer' : 'double';
$this->rules[] = new ValidationRule([$attribute->columnName], $validator, $params);
}

private function prepareTypeScope():void
{
foreach ($this->model->attributes as $attribute) {
Expand All @@ -51,57 +169,20 @@ private function prepareTypeScope():void
$this->typeScope['required'][$attribute->columnName] = $attribute->columnName;
}

if ($attribute->isReference()) {
if (in_array($attribute->phpType, ['int', 'string'])) {
$this->typeScope[$attribute->phpType][$attribute->columnName] = $attribute->columnName;
}
$this->typeScope['ref'][] = ['attr' => $attribute->columnName, 'rel' => $attribute->camelName()];
continue;
if ($attribute->phpType === 'string') {
$this->typeScope['trim'][$attribute->columnName] = $attribute->columnName;
}

if (in_array($attribute->phpType, ['int', 'string', 'bool', 'float'])) {
$this->typeScope[$attribute->phpType][$attribute->columnName] = $attribute->columnName;
if ($attribute->isReference()) {
$this->typeScope['ref'][] = $attribute;
continue;
}

if ($attribute->phpType === 'double') {
$this->typeScope['float'][$attribute->columnName] = $attribute->columnName;
if (in_array($attribute->phpType, ['int', 'string', 'bool', 'float', 'double'])) {
continue;
}

$this->typeScope['safe'][$attribute->columnName] = $attribute->columnName;
}
}

private function rulesByType():void
{
if (!empty($this->typeScope['string'])) {
$this->rules[] = new ValidationRule($this->typeScope['string'], 'trim');
}
if (!empty($this->typeScope['required'])) {
$this->rules[] = new ValidationRule($this->typeScope['required'], 'required');
}

if (!empty($this->typeScope['int'])) {
$this->rules[] = new ValidationRule($this->typeScope['int'], 'integer');
}

foreach ($this->typeScope['ref'] as $relation) {
$this->rules[] = new ValidationRule([$relation['attr']], 'exist', ['targetRelation'=>$relation['rel']]);
}

if (!empty($this->typeScope['string'])) {
$this->rules[] = new ValidationRule($this->typeScope['string'], 'string');
}

if (!empty($this->typeScope['float'])) {
$this->rules[] = new ValidationRule($this->typeScope['float'], 'double');
}
if (!empty($this->typeScope['bool'])) {
$this->rules[] = new ValidationRule($this->typeScope['bool'], 'boolean');
}
if (!empty($this->typeScope['safe'])) {
$this->rules[] = new ValidationRule($this->typeScope['safe'], 'safe');
}
}
}
14 changes: 13 additions & 1 deletion src/lib/items/Attribute.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
* @property-write mixed $default
* @property-write bool $isPrimary
* @property-read string $formattedDescription
* @property-read null|int $maxLength
* @property-read null|int $minLength
*/
class Attribute extends BaseObject
{
Expand All @@ -27,7 +29,7 @@ class Attribute extends BaseObject
public $propertyName;

/**
* should be string/integer/boolean/float/double
* should be string/integer/boolean/float/double/array
* @var string
*/
public $phpType = 'string';
Expand Down Expand Up @@ -213,6 +215,16 @@ public function camelName():string
return Inflector::camelize($this->propertyName);
}

public function getMaxLength():?int
{
return $this->size;
}

public function getMinLength():?int
{
return $this->limits['minLength'];
}

public function getFormattedDescription():string
{
$comment = $this->columnName.' '.$this->description;
Expand Down
23 changes: 2 additions & 21 deletions src/lib/items/ValidationRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,14 @@

namespace cebe\yii2openapi\lib\items;

use yii\base\BaseObject;
use yii\helpers\ArrayHelper;
use yii\helpers\VarDumper;
use function gettype;
use function implode;
use function is_string;
use function sprintf;

class ValidationRule extends BaseObject
final class ValidationRule
{
/**@var array * */
public $attributes = [];
Expand All @@ -26,29 +25,11 @@ class ValidationRule extends BaseObject
/**@var array * */
public $params = [];

public function __construct(array $attributes, string $validator, array $params = [], $config = [])
public function __construct(array $attributes, string $validator, array $params = [])
{
$this->attributes = array_values($attributes);
$this->validator = $validator;
$this->params = $params;
parent::__construct($config);
}

/**
* @param string $key
* @param int|string|array $value
* @return $this
*/
public function addParam(string $key, $value):ValidationRule
{
$this->params[$key] = $value;
return $this;
}

public function withParams(array $params):ValidationRule
{
$this->params = $params;
return $this;
}

public function __toString():string
Expand Down
3 changes: 2 additions & 1 deletion tests/specs/blog/models/base/Category.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ public function rules()
return [
[['title'], 'trim'],
[['title', 'active'], 'required'],
[['title'], 'string'],
[['title'], 'unique'],
[['title'], 'string', 'max' => 255],
[['active'], 'boolean'],
];
}
Expand Down
4 changes: 3 additions & 1 deletion tests/specs/blog/models/base/Comment.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,11 @@ public function rules()
{
return [
[['post_id', 'author_id', 'message', 'created_at'], 'required'],
[['post_id', 'author_id', 'created_at'], 'integer'],
[['post_id'], 'integer'],
[['post_id'], 'exist', 'targetRelation' => 'Post'],
[['author_id'], 'integer'],
[['author_id'], 'exist', 'targetRelation' => 'Author'],
[['created_at'], 'integer'],
[['message'], 'safe'],
];
}
Expand Down
17 changes: 14 additions & 3 deletions tests/specs/blog/models/base/Fakerable.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,21 @@ public function rules()
{
return [
[['uuid', 'str_text', 'str_varchar', 'str_date', 'str_datetime', 'str_country'], 'trim'],
[['int_min', 'int_max', 'int_minmax', 'int_created_at', 'int_simple'], 'integer'],
[['uuid', 'str_text', 'str_varchar', 'str_date', 'str_datetime', 'str_country'], 'string'],
[['floatval', 'floatval_lim', 'doubleval'], 'double'],
[['active'], 'boolean'],
[['floatval'], 'double'],
[['floatval_lim'], 'double', 'min' => 0, 'max' => 1],
[['doubleval'], 'double'],
[['int_min'], 'integer', 'min' => 5],
[['int_max'], 'integer', 'max' => 5],
[['int_minmax'], 'integer', 'min' => 5, 'max' => 25],
[['int_created_at'], 'integer'],
[['int_simple'], 'integer'],
[['uuid'], 'string'],
[['str_text'], 'string'],
[['str_varchar'], 'string', 'max' => 100],
[['str_date'], 'date'],
[['str_datetime'], 'datetime'],
[['str_country'], 'string'],
];
}

Expand Down
9 changes: 7 additions & 2 deletions tests/specs/blog/models/base/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,16 @@ public function rules()
return [
[['title', 'slug', 'created_at'], 'trim'],
[['title', 'category_id', 'active'], 'required'],
[['category_id', 'created_by_id'], 'integer'],
[['category_id'], 'integer'],
[['category_id'], 'exist', 'targetRelation' => 'Category'],
[['created_by_id'], 'integer'],
[['created_by_id'], 'exist', 'targetRelation' => 'CreatedBy'],
[['title', 'slug', 'created_at'], 'string'],
[['title'], 'unique'],
[['title'], 'string', 'max' => 255],
[['slug'], 'unique'],
[['slug'], 'string', 'min' => 1, 'max' => 200],
[['active'], 'boolean'],
[['created_at'], 'date'],
];
}

Expand Down
9 changes: 8 additions & 1 deletion tests/specs/blog/models/base/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,14 @@ public function rules()
return [
[['username', 'email', 'password', 'role', 'created_at'], 'trim'],
[['username', 'email', 'password'], 'required'],
[['username', 'email', 'password', 'role', 'created_at'], 'string'],
[['username'], 'unique'],
[['username'], 'string', 'max' => 200],
[['email'], 'unique'],
[['email'], 'string', 'max' => 200],
[['email'], 'email'],
[['password'], 'string'],
[['role'], 'string', 'max' => 20],
[['created_at'], 'datetime'],
];
}

Expand Down
4 changes: 3 additions & 1 deletion tests/specs/blog_v2/models/base/Category.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ public function rules()
return [
[['title', 'cover'], 'trim'],
[['title', 'cover', 'active'], 'required'],
[['title', 'cover'], 'string'],
[['title'], 'unique'],
[['title'], 'string', 'max' => 100],
[['cover'], 'string'],
[['active'], 'boolean'],
];
}
Expand Down
Loading