StyleRule.php
72 lines
| 1 | <?php |
| 2 | |
| 3 | declare (strict_types=1); |
| 4 | namespace ProfilePressVendor\Pelago\Emogrifier\Css; |
| 5 | |
| 6 | use ProfilePressVendor\Sabberworm\CSS\Property\Selector; |
| 7 | use ProfilePressVendor\Sabberworm\CSS\RuleSet\DeclarationBlock; |
| 8 | /** |
| 9 | * This class represents a CSS style rule, including selectors, a declaration block, and an optional containing at-rule. |
| 10 | * |
| 11 | * @internal |
| 12 | */ |
| 13 | class StyleRule |
| 14 | { |
| 15 | /** |
| 16 | * @var DeclarationBlock |
| 17 | */ |
| 18 | private $declarationBlock; |
| 19 | /** |
| 20 | * @var string |
| 21 | */ |
| 22 | private $containingAtRule; |
| 23 | /** |
| 24 | * @param DeclarationBlock $declarationBlock |
| 25 | * @param string $containingAtRule e.g. `@media screen and (max-width: 480px)` |
| 26 | */ |
| 27 | public function __construct(DeclarationBlock $declarationBlock, string $containingAtRule = '') |
| 28 | { |
| 29 | $this->declarationBlock = $declarationBlock; |
| 30 | $this->containingAtRule = \trim($containingAtRule); |
| 31 | } |
| 32 | /** |
| 33 | * @return array<int, string> the selectors, e.g. `["h1", "p"]` |
| 34 | */ |
| 35 | public function getSelectors(): array |
| 36 | { |
| 37 | /** @var array<int, Selector> $selectors */ |
| 38 | $selectors = $this->declarationBlock->getSelectors(); |
| 39 | return \array_map(static function (Selector $selector): string { |
| 40 | return (string) $selector; |
| 41 | }, $selectors); |
| 42 | } |
| 43 | /** |
| 44 | * @return string the CSS declarations, separated and followed by a semicolon, e.g., `color: red; height: 4px;` |
| 45 | */ |
| 46 | public function getDeclarationAsText(): string |
| 47 | { |
| 48 | return \implode(' ', $this->declarationBlock->getRules()); |
| 49 | } |
| 50 | /** |
| 51 | * Checks whether the declaration block has at least one declaration. |
| 52 | */ |
| 53 | public function hasAtLeastOneDeclaration(): bool |
| 54 | { |
| 55 | return $this->declarationBlock->getRules() !== []; |
| 56 | } |
| 57 | /** |
| 58 | * @returns string e.g. `@media screen and (max-width: 480px)`, or an empty string |
| 59 | */ |
| 60 | public function getContainingAtRule(): string |
| 61 | { |
| 62 | return $this->containingAtRule; |
| 63 | } |
| 64 | /** |
| 65 | * Checks whether the containing at-rule is non-empty and has any non-whitespace characters. |
| 66 | */ |
| 67 | public function hasContainingAtRule(): bool |
| 68 | { |
| 69 | return $this->getContainingAtRule() !== ''; |
| 70 | } |
| 71 | } |
| 72 |