0

Final Class Yiisoft\Hydrator\Attribute\Parameter\ToArrayOfStringsResolver

InheritanceYiisoft\Hydrator\Attribute\Parameter\ToArrayOfStringsResolver
ImplementsYiisoft\Hydrator\Attribute\Parameter\ParameterAttributeResolverInterface

Resolver for {@see ToArrayOfStrings} attribute.

Method Details

Hide inherited methods

__construct() public method

public mixed __construct ( boolean $multibyte = false, string|null $encoding = null )
$multibyte boolean

Whether to use multibyte-aware trimming that strips Unicode whitespace characters such as U+00A0 (no-break space) as well, when it is not specified in the attribute. Requires PHP 8.4 or later with mbstring extension, or symfony/polyfill-mbstring package.

$encoding string|null

The encoding to use in multibyte mode when it is not specified in the attribute.

                public function __construct(
    private readonly bool $multibyte = false,
    private readonly ?string $encoding = null,
) {
    TrimCharacters::checkMultibyteFunctionsExist($multibyte);
}

            
getParameterValue() public method

public Yiisoft\Hydrator\Result getParameterValue ( Yiisoft\Hydrator\Attribute\Parameter\ParameterAttributeInterface $attribute, Yiisoft\Hydrator\AttributeHandling\ParameterAttributeResolveContext $context )
$attribute Yiisoft\Hydrator\Attribute\Parameter\ParameterAttributeInterface
$context Yiisoft\Hydrator\AttributeHandling\ParameterAttributeResolveContext

                public function getParameterValue(
    ParameterAttributeInterface $attribute,
    ParameterAttributeResolveContext $context,
): Result {
    if (!$attribute instanceof ToArrayOfStrings) {
        throw new UnexpectedAttributeException(ToArrayOfStrings::class, $attribute);
    }
    if (!$context->isResolved()) {
        return Result::fail();
    }
    $resolvedValue = $context->getResolvedValue();
    if (is_iterable($resolvedValue)) {
        $array = array_map(
            $this->castValueToString(...),
            $resolvedValue instanceof Traversable ? iterator_to_array($resolvedValue) : $resolvedValue,
        );
    } else {
        $value = $this->castValueToString($resolvedValue);
        /**
         * @var string[] $array We assume valid regular expression is used here, so `preg_split()` always returns
         * an array of strings.
         */
        $array = $attribute->splitResolvedValue
            ? preg_split('~' . $attribute->separator . '~u', $value)
            : [$value];
    }
    if ($attribute->trim) {
        $multibyte = $attribute->multibyte ?? $this->multibyte;
        $encoding = $attribute->encoding ?? $this->encoding;
        $array = array_map(
            $multibyte ? static fn(string $value): string => mb_trim($value, null, $encoding) : trim(...),
            $array,
        );
    }
    if ($attribute->removeEmpty) {
        $array = array_filter(
            $array,
            static fn(string $value): bool => $value !== '',
        );
    }
    return Result::success($array);
}