PHP Classes

File: src/Traits/ParameterAssertArrayTypeTrait.php

Recommend this page to a friend!
  Classes of Rodolfo Berrios Arce   Parameter   src/Traits/ParameterAssertArrayTypeTrait.php   Download  
File: src/Traits/ParameterAssertArrayTypeTrait.php
Role: Class source
Content type: text/plain
Description: Class source
Class: Parameter
Validate function parameters with PHP attributes
Author: By
Last change:
Date: 15 days ago
Size: 2,030 bytes
 

Contents

Class file image Download
<?php

/*
 * This file is part of Chevere.
 *
 * (c) Rodolfo Berrios <[email protected]>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace
Chevere\Parameter\Traits;

use
Chevere\Parameter\Interfaces\ParametersAccessInterface;
use
Chevere\Parameter\Interfaces\ParametersInterface;
use
InvalidArgumentException;
use
OutOfBoundsException;
use function
Chevere\Message\message;

trait
ParameterAssertArrayTypeTrait
{
    private
ParametersInterface $parameters;

    private function
assertArrayType(ParametersAccessInterface $parameter): void
   
{
       
$parametersCount = $this->parameters->count();
       
$providedCount = $parameter->parameters()->count();
        if (
$parametersCount === 0 && $providedCount !== 0) {
            throw new
InvalidArgumentException(
                (string)
message(
                   
'Expecting no parameters, `%provided%` provided',
                   
provided: strval($providedCount)
                )
            );
        }
        foreach (
$this->parameters as $name => $item) {
            try {
               
$tryParameter = $parameter->parameters()->get($name);
            } catch (
OutOfBoundsException) {
                throw new
OutOfBoundsException(
                    (string)
message(
                       
'Parameter `%name%` not found',
                       
name: $name
                   
)
                );
            }

            try {
               
$item->assertCompatible($tryParameter);
            } catch (\
TypeError) {
                throw new
InvalidArgumentException(
                    (string)
message(
                       
'Parameter `%name%` of type `%type%` is not compatible with type `%provided%`',
                       
name: $name,
                       
type: $item::class,
                       
provided: $tryParameter::class,
                    )
                );
            }
        }
    }
}