Вход Регистрация
Файл: vendor/intervention/image/src/Colors/Rgb/Decoders/HexColorDecoder.php
Строк: 103
<?php

declare(strict_types=1);

namespace 
InterventionImageColorsRgbDecoders;

use 
InterventionImageColorsRgbColorspace as Rgb;
use 
InterventionImageDriversAbstractDecoder;
use 
InterventionImageExceptionsColorDecoderException;
use 
InterventionImageExceptionsInvalidArgumentException;
use 
InterventionImageInterfacesColorInterface;
use 
InterventionImageInterfacesDecoderInterface;

class 
HexColorDecoder extends AbstractDecoder implements DecoderInterface
{
    
/**
     * Regex pattern of hexadecimal color syntax.
     */
    
protected const string PATTERN '/^#?(?P<hex>[a-fd]{3}(?:[a-fd]?|(?:[a-fd]{3}(?:[a-fd]{2})?)?)b)$/i';

    
/**
     * {@inheritdoc}
     *
     * @see DecoderInterface::supports()
     */
    
public function supports(mixed $input): bool
    
{
        if (!
is_string($input)) {
            return 
false;
        }

        if (
str_starts_with($input'#')) {
            return 
true;
        }

        
// matching max. length & only hexadecimal
        
if (strlen($input) <= && preg_match('/^[a-fd]+$/i'$input) === 1) {
            return 
true;
        }

        return 
preg_match(static::PATTERN$input) === 1;
    }

    
/**
     * Decode hexadecimal rgb colors with and without transparency.
     *
     * @throws InvalidArgumentException
     * @throws ColorDecoderException
     */
    
public function decode(mixed $input): ColorInterface
    
{
        if (
preg_match(static::PATTERN$input$matches) !== 1) {
            throw new 
InvalidArgumentException('Hex color has an invalid format');
        }

        
// split into hex chunks
        
$values match (strlen($matches['hex'])) {
            
3=> str_split($matches['hex']),
            
6=> str_split($matches['hex'], 2),
            default => throw new 
InvalidArgumentException('Hex color has an incorrect length'),
        };

        
// convert to decimal
        
$values array_map(function (string $value): int {
            return 
match (strlen($value)) {
                
=> (int) hexdec($value $value),
                
=> (int) hexdec($value),
                default => throw new 
ColorDecoderException('Failed to decode hex color'),
            };
        }, 
$values);

        
// normalize
        
$values count($values) === array_pad($values4255) : $values;
        
$values array_map(fn(int $value): float => $value 255$values);

        return 
Rgb::colorFromNormalized($values);
    }
}
Онлайн: 4
Реклама