| 1 |
<?php |
| 2 |
/** |
| 3 |
* @file |
| 4 |
* @license https://opensource.org/licenses/Apache-2.0 Apache-2.0 |
| 5 |
*/ |
| 6 |
|
| 7 |
namespace Wikimedia\CSS\Sanitizer; |
| 8 |
|
| 9 |
use Wikimedia\CSS\Objects\AtRule; |
| 10 |
use Wikimedia\CSS\Objects\CSSObject; |
| 11 |
use Wikimedia\CSS\Objects\Rule; |
| 12 |
use Wikimedia\CSS\Util; |
| 13 |
|
| 14 |
/** |
| 15 |
* Sanitizes the margin at-rules inside a CSS \@page rule |
| 16 |
* @see https://www.w3.org/TR/2023/WD-css-page-3-20230914/ |
| 17 |
*/ |
| 18 |
class MarginAtRuleSanitizer extends RuleSanitizer { |
| 19 |
|
| 20 |
/** @var string[] */ |
| 21 |
protected static $marginRuleNames = [ |
| 22 |
'top-left-corner', 'top-left', 'top-center', 'top-right', 'top-right-corner', |
| 23 |
'bottom-left-corner', 'bottom-left', 'bottom-center', 'bottom-right', 'bottom-right-corner', |
| 24 |
'left-top', 'left-middle', 'left-bottom', 'right-top', 'right-middle', 'right-bottom', |
| 25 |
]; |
| 26 |
|
| 27 |
/** @var PropertySanitizer */ |
| 28 |
protected $propertySanitizer; |
| 29 |
|
| 30 |
/** |
| 31 |
* @param PropertySanitizer $propertySanitizer Sanitizer for declarations |
| 32 |
*/ |
| 33 |
public function __construct( PropertySanitizer $propertySanitizer ) { |
| 34 |
$this->propertySanitizer = $propertySanitizer; |
| 35 |
} |
| 36 |
|
| 37 |
/** @inheritDoc */ |
| 38 |
public function handlesRule( Rule $rule ) { |
| 39 |
return $rule instanceof AtRule && |
| 40 |
in_array( strtolower( $rule->getName() ), self::$marginRuleNames, true ); |
| 41 |
} |
| 42 |
|
| 43 |
/** @inheritDoc */ |
| 44 |
protected function doSanitize( CSSObject $object ) { |
| 45 |
if ( !$object instanceof AtRule || !$this->handlesRule( $object ) ) { |
| 46 |
$this->sanitizationError( 'expected-page-margin-at-rule', $object ); |
| 47 |
return null; |
| 48 |
} |
| 49 |
|
| 50 |
if ( $object->getBlock() === null ) { |
| 51 |
$this->sanitizationError( 'at-rule-block-required', $object, [ $object->getName() ] ); |
| 52 |
return null; |
| 53 |
} |
| 54 |
|
| 55 |
// No non-whitespace prelude allowed |
| 56 |
if ( Util::findFirstNonWhitespace( $object->getPrelude() ) ) { |
| 57 |
$this->sanitizationError( 'invalid-page-margin-at-rule', $object, [ $object->getName() ] ); |
| 58 |
return null; |
| 59 |
} |
| 60 |
|
| 61 |
$ret = clone $object; |
| 62 |
$this->fixPreludeWhitespace( $ret, false ); |
| 63 |
$this->sanitizeDeclarationBlock( $ret->getBlock(), $this->propertySanitizer ); |
| 64 |
|
| 65 |
// @phan-suppress-next-line PhanTypeMismatchReturn generics weakness |
| 66 |
return $ret; |
| 67 |
} |
| 68 |
} |