Skip to content

Latest commit

 

History

History
executable file
·
113 lines (95 loc) · 2.69 KB

10.5 - Template.md

File metadata and controls

executable file
·
113 lines (95 loc) · 2.69 KB

10.5 - Template

When retrieving the validated data, sometimes you only want part of the data structure with their corresponding values. You can achieve this by using the template() method.

This method extracts data from the validated data by giving a blueprint/template of the expected structure.

use KrisKuiper\Validator\Validator;

$data = [
    'name' => 'Brenda',
    'hobbies' => [
        'Swimming',
        'Coding'
    ],
    'address' => [
        'city' => 'Amsterdam',
        'street' => 'Bovenover',
        'house_number' => '180',
        'zip_code' => '1025JS',
    ],
    'age' => 67
];

$validator = new Validator($data);
$validator->field('name')->isString();
$validator->field('hobbies', 'address')->isArray();
$validator->field('age')->isInt();

$this->assertTrue($validator->execute());

$output = $validator->validatedData()->template([
    'name',
    'address' => [
        'zip_code',
        'house_number'
    ],
    'age'
])->toArray();

This will return:

[
    'name' => 'Brenda',
    'address' => [
        'zip_code' => '1025JS',
        'house_number' => '180'
    ],
    'age' => 67
];

As you can see, the template() method extracts the data for you into a new array with all the fields/paths you defined.

Matching nested arrays with wildcards

Sometimes, array's may contain other arrays. In this situation, you may use the * character to match the structure of all the items in the array:

use KrisKuiper\Validator\Validator;

$data = [
    'addresses' => [
        [
            'city' => 'Amsterdam',
            'street' => 'Bovenover',
            'house_number' => '180',
            'zip_code' => '1025JS'
        ],
        [
            'city' => 'London',
            'street' => 'Queens Road',
            'house_number' => '97',
            'zip_code' => 'WC17 6GF'
        ]
    ]
];

$validator = new Validator($data);
$validator->field('addresses')->isArray();

$this->assertTrue($validator->execute());

$output = $validator->validatedData()->template([
    'addresses' => [
        '*' => [ 
            'zip_code',
            'house_number'
        ]
    ]
])->toArray();

This will return:

[
    'addresses' => [
        [
            'zip_code' => '1025JS',
            'house_number' => '180'
        ],
        [
            'zip_code' => 'WC17 6GF',
            'house_number' => '97'
        ]
    ]
]

Go to the previous section.

Go to the next section.