phpffcms/ffcms-core

View on GitHub
src/Network/Extends/InputBag.php

Summary

Maintainability
A
0 mins
Test Coverage
<?php 

namespace Ffcms\Core\Network\Extends;

use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;


/**
 * Override Symfony InputBag to allow using array-driver access.
 * Class InputBag marked as "final". In this case - extending ParameterBag.
 */
class InputBag extends ParameterBag 
{
    /**
     * Returns a scalar input value by name.
     *
     * @param string|int|float|bool|null|array $default The default value if the input key does not exist
     */
    public function get(string $key, mixed $default = null): string|int|float|bool|null|array
    {
        $value = ParameterBag::get($key, $this);
        return $this === $value ? $default : $value;
    }

    /**
     * Sets an input by name.
     *
     * @param string|int|float|bool|array|null $value
     */
    public function set(string $key, mixed $value)
    {
        $this->parameters[$key] = $value;
    }

        /**
     * Replaces the current input values by a new set.
     */
    public function replace(array $inputs = [])
    {
        $this->parameters = [];
        $this->add($inputs);
    }

    /**
     * Adds input values.
     */
    public function add(array $inputs = [])
    {
        foreach ($inputs as $input => $value) {
            $this->set($input, $value);
        }
    }

        /**
     * {@inheritdoc}
     */
    public function filter(string $key, mixed $default = null, int $filter = \FILTER_DEFAULT, mixed $options = []): mixed
    {
        $value = $this->has($key) ? $this->all()[$key] : $default;

        // Always turn $options into an array - this allows filter_var option shortcuts.
        if (!\is_array($options) && $options) {
            $options = ['flags' => $options];
        }

        if (\is_array($value) && !(($options['flags'] ?? 0) & (\FILTER_REQUIRE_ARRAY | \FILTER_FORCE_ARRAY))) {
            throw new BadRequestException(sprintf('Input value "%s" contains an array, but "FILTER_REQUIRE_ARRAY" or "FILTER_FORCE_ARRAY" flags were not set.', $key));
        }

        if ((\FILTER_CALLBACK & $filter) && !(($options['options'] ?? null) instanceof \Closure)) {
            throw new \InvalidArgumentException(sprintf('A Closure must be passed to "%s()" when FILTER_CALLBACK is used, "%s" given.', __METHOD__, get_debug_type($options['options'] ?? null)));
        }

        return filter_var($value, $filter, $options);
    }
}