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