| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace AcyMailing\Libraries\Sabberworm\CSS\Property; |
| 6 |
|
| 7 |
use AcyMailing\Libraries\Sabberworm\CSS\CSSList\CSSList; |
| 8 |
use AcyMailing\Libraries\Sabberworm\CSS\OutputFormat; |
| 9 |
use AcyMailing\Libraries\Sabberworm\CSS\Property\Selector\SpecificityCalculator; |
| 10 |
use AcyMailing\Libraries\Sabberworm\CSS\Renderable; |
| 11 |
|
| 12 |
/** |
| 13 |
* Class representing a single CSS selector. Selectors have to be split by the comma prior to being passed into this |
| 14 |
* class. |
| 15 |
*/ |
| 16 |
class Selector implements Renderable |
| 17 |
{ |
| 18 |
/** |
| 19 |
* @var non-empty-string |
| 20 |
* |
| 21 |
* @internal since 8.5.2 |
| 22 |
*/ |
| 23 |
public const SELECTOR_VALIDATION_RX = '/ |
| 24 |
^( |
| 25 |
(?: |
| 26 |
# any sequence of valid unescaped characters, except quotes |
| 27 |
[a-zA-Z0-9\\x{00A0}-\\x{FFFF}_^$|*=~\\[\\]()\\-\\s\\.:#+>,]++ |
| 28 |
| |
| 29 |
# one or more escaped characters |
| 30 |
(?:\\\\.)++ |
| 31 |
| |
| 32 |
# quoted text, like in `[id="example"]` |
| 33 |
(?: |
| 34 |
# opening quote |
| 35 |
([\'"]) |
| 36 |
(?: |
| 37 |
# sequence of characters except closing quote or backslash |
| 38 |
(?:(?!\\g{-1}|\\\\).)++ |
| 39 |
| |
| 40 |
# one or more escaped characters |
| 41 |
(?:\\\\.)++ |
| 42 |
)*+ # zero or more times |
| 43 |
# closing quote or end (unmatched quote is currently allowed) |
| 44 |
(?:\\g{-1}|$) |
| 45 |
) |
| 46 |
)*+ # zero or more times |
| 47 |
)$ |
| 48 |
/ux'; |
| 49 |
|
| 50 |
/** |
| 51 |
* @var string |
| 52 |
*/ |
| 53 |
private $selector; |
| 54 |
|
| 55 |
/** |
| 56 |
* @internal since V8.8.0 |
| 57 |
*/ |
| 58 |
public static function isValid(string $selector): bool |
| 59 |
{ |
| 60 |
// Note: We need to use `static::` here as the constant is overridden in the `KeyframeSelector` class. |
| 61 |
$numberOfMatches = CSSList::preg_match(static::SELECTOR_VALIDATION_RX, $selector); |
| 62 |
|
| 63 |
return $numberOfMatches === 1; |
| 64 |
} |
| 65 |
|
| 66 |
public function __construct(string $selector) |
| 67 |
{ |
| 68 |
$this->setSelector($selector); |
| 69 |
} |
| 70 |
|
| 71 |
public function getSelector(): string |
| 72 |
{ |
| 73 |
return $this->selector; |
| 74 |
} |
| 75 |
|
| 76 |
public function setSelector(string $selector): void |
| 77 |
{ |
| 78 |
$this->selector = \trim($selector); |
| 79 |
} |
| 80 |
|
| 81 |
/** |
| 82 |
* @return int<0, max> |
| 83 |
*/ |
| 84 |
public function getSpecificity(): int |
| 85 |
{ |
| 86 |
return SpecificityCalculator::calculate($this->selector); |
| 87 |
} |
| 88 |
|
| 89 |
public function render(OutputFormat $outputFormat): string |
| 90 |
{ |
| 91 |
return $this->getSelector(); |
| 92 |
} |
| 93 |
} |
| 94 |
|