PHP Array Structure Validator: Validate complex array structure using rules

Recommend this page to a friend!
  Info   View files Documentation   View files View files (9)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2020-11-24 (7 months ago) RSS 2.0 feedNot yet rated by the usersTotal: 44 All time: 10,105 This week: 213Up
Version License PHP version Categories
yii2-array-structure 1.0.0MIT/X Consortium ...7.1PHP 5, Data types, Validation
Description Author

This class can validate complex array structure using rules.

It takes a nested associative array that defines how a given array of data should be validated.

Currently the rules can define the names of the keys of the array entries, the type of value for the each key and parameters that are specific for the type of validation that needs to be performed on the array values.

Picture of Insolita
  Performance   Level  
Name: Insolita <contact>
Classes: 7 packages by
Country: Russian Federation Russian Federation
Age: 35
All time rank: 3735106 in Russian Federation Russian Federation
Week rank: 490 Up19 in Russian Federation Russian Federation Up
Innovation award
Innovation award
Nominee: 5x

Details

Yii2 validator for complex array structures

yii2-array-structure-validator

Validator for array attributes, unlike builtin "each" validator, that support only one rule, this validator can * validate multiple array attributes and even nested data structures * All keys that should be present in array must be described, for optional keys default value should be set * When input array not contains key defined in rules, this key added automatically with null value * When input array contains key not defined in rules, "unexpected item" error will be defined

Installation


#### Usage

For a simple array with known keys like `['id'=>1, 'name'=>'John Doe']`;

public function rules() { return [ //...

   ['simpleArray', ArrayStructureValidator::class, 
      'rules'=>[
             'id'=>[['required'], ['integer','min'=>0]],
             'name'=>[['required'], ['string', 'max'=>100]],
             'sex'=>[['default', 'value'=>'male'], ['in','range'=>['male','female']]
        ]]
   ],

]; }


For multidimensional arrays like 
`
[
    ['id'=>1, 'name'=>'John Doe'],
    ['id'=>2, 'name'=>'Jane Doe','sex'=>'female'],
     ...
]`
 set each = true

public function rules() { return [ //...

   [['multiArray', 'some', 'attrs'], 'required'],
   ['multiArray', ArrayStructureValidator::class, 
      'each'=>true,
       'rules'=>[
             'id'=>[['required'], ['integer','min'=>0]],
             'name'=>[['required'], ['string', 'max'=>100]],
             'sex'=>[['default', 'value'=>'male'], ['in','range'=>['male','female']]
        ]]
   ]

]; }


For nested structures like 

[

'user'=>['id'=>1, 'name'=>'John Doe'],
'coords'=>[['x'=>1, 'y'=>2],['x'=>3,'y'=>4]]

]

public function rules() { return [ //...

   ['complexArray', ArrayStructureValidator::class, 
    'rules'=>[
             'user'=>[[ArrayStructureValidator::class, 
                   'rules'=>[
                       'id'=>[['required'], ['integer','min'=>0]],
                       'name'=>[['required'], ['string', 'max'=>100]],
             ]]],
             'coords'=>[[ArrayStructureValidator::class, 
                  'each'=>true, 
                  'rules'=>[
                        'x'=>[['required'], ['integer','min'=>0]],
                        'y'=>[['required'], ['integer','min'=>0]],
             ], 'min'=>1, 'max'=>5]],
       ], 'min'=>2, 'max'=>2]

]; }


Model scenarios supported

public function rules() { return [ //...

    ['conditional', ArrayStructureValidator::class, 
    'rules'=>[
              'a'=>[['integer','min'=>0]], //will be checked on any scenario
              'b'=>[
                      ['default', 'value'=>1, 'on'=>['create']],
                      ['integer', 'max'=>10, 'except'=>['create']],
                      ['required',  'on'=>['update']],
                      ['integer', 'max'=>1000, 'on'=>['update']],
                  ]
         ]
    ]
];

}


Closure and Inline validators supported, but with signature different from default

Inline method in model class

public function rules() { return [

  ['array', ArrayStructureValidator::class,  'rules'=>[
         'item'=>[['required'], ['customValidator']]
  ]]

]; }

public function customValidator($attribute, $model, $index, $baseModel, $baseAttribute){ / * $model - Dynamic model with attributes equals value data, or value row, if used with each=>true * $attribute - current keyName * $index - current array index for multidimensional arrays, or null * $baseModel - instance of initial model, where validator was attached * $baseAttribute - name of initial attributed, where validator was attached

* access to validated value - $model->$attribute * access to whole validated array $baseModel->$baseAttribute * $model->addError($attribute, '[{index}][{attribute}] Error message', ['index'=>$index]); */ }


When conditions supported (But not whenClient!)

public function rules() { return [

  ['conditional', ArrayStructureValidator::class, 
      'rules'=>[
           'x'=>[['safe']],
           'y'=>[
               ['default', 'value'=>1, 'when'=>fn(DynamicModel $model) => $model->x < 10],
               [
                  'default',
                  'value'=>5,
                  'when'=>function($model, $attribute, $index, $baseModel, $baseAttribute){
                          return count($baseModel->$baseAttribute) > 5;
                     }],
               ]
       ]]

]; }


#### Note:
Database related validators (exists, unique) not covered by tests yet and not supported 
  Files folder image Files  
File Role Description
Files folder image.github (1 directory)
Files folder imagesrc (1 file)
Files folder imagetests (3 files)
Accessible without login Plain text file .php_cs Example Example script
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file phpunit.xml.dist Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files  /  .github  
File Role Description
Files folder imageworkflows (1 file)

  Files folder image Files  /  .github  /  workflows  
File Role Description
  Accessible without login Plain text file test.yml Data Auxiliary data

  Files folder image Files  /  src  
File Role Description
  Plain text file ArrayStructureValidator.php Class Class source

  Files folder image Files  /  tests  
File Role Description
  Plain text file ArrayStructureValidatorTest.php Class Class source
  Accessible without login Plain text file bootstrap.php Aux. Auxiliary script
  Plain text file TestCase.php Class Class source

 Version Control Unique User Downloads Download Rankings  
 100%
Total:44
This week:0
All time:10,105
This week:213Up

For more information send a message to info at phpclasses dot org.