Debian Codegraph @

vendor/wikimedia/css-sanitizer/src/Sanitizer/StyleAttributeSanitizer.php

raw
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\Grammar\MatcherFactory;
10 use Wikimedia\CSS\Objects\CSSObject;
11 use Wikimedia\CSS\Objects\DeclarationList;
12 use Wikimedia\CSS\Parser\Parser;
13
14 /**
15 * Sanitizes a CSS style attribute (i.e. `<tag style="...">`)
16 * @see https://www.w3.org/TR/2013/REC-css-style-attr-20131107/
17 */
18 class StyleAttributeSanitizer extends Sanitizer {
19
20 /** @var Sanitizer */
21 protected $propertySanitizer;
22
23 /**
24 * @param PropertySanitizer $propertySanitizer Sanitizer to test property declarations.
25 * Probably an instance of StylePropertySanitizer.
26 */
27 public function __construct( PropertySanitizer $propertySanitizer ) {
28 $this->propertySanitizer = $propertySanitizer;
29 }
30
31 /**
32 * Create and return a default StyleAttributeSanitizer.
33 * @note This method exists more to be an example of how to put everything
34 * together than to be used directly.
35 * @return StyleAttributeSanitizer
36 */
37 public static function newDefault() {
38 // First, we need a matcher factory for the stuff all the sanitizers
39 // will need.
40 $matcherFactory = MatcherFactory::singleton();
41
42 // This is the sanitizer for a single "property: value"
43 $propertySanitizer = new StylePropertySanitizer( $matcherFactory );
44
45 // StyleAttributeSanitizer brings it all together
46 return new StyleAttributeSanitizer( $propertySanitizer );
47 }
48
49 /** @inheritDoc */
50 protected function doSanitize( CSSObject $object ) {
51 if ( !$object instanceof DeclarationList ) {
52 '@phan-var CSSObject $object';
53 $this->sanitizationError( 'expected-declaration-list', $object );
54 return null;
55 }
56 // @phan-suppress-next-line PhanTypeMismatchReturn generics weakness
57 return $this->sanitizeList( $this->propertySanitizer, $object );
58 }
59
60 /**
61 * Sanitize a string value.
62 * @param string $string
63 * @return DeclarationList
64 */
65 public function sanitizeString( $string ) {
66 $parser = Parser::newFromString( $string );
67 $declarations = $parser->parseDeclarationList();
68 $this->sanitizationErrors = array_merge( $this->sanitizationErrors, $parser->getParseErrors() );
69 return $this->sanitizeList( $this->propertySanitizer, $declarations );
70 }
71 }