4 * @license https://opensource.org/licenses/Apache-2.0 Apache-2.0
7 namespace Wikimedia\CSS\Sanitizer;
9 use Wikimedia\CSS\Objects\CSSObject;
10 use Wikimedia\CSS\Objects\DeclarationList;
11 use Wikimedia\CSS\Grammar\MatcherFactory;
12 use Wikimedia\CSS\Parser\Parser;
15 * Sanitizes a CSS style attribute (i.e. `<tag style="...">`)
16 * @see https://www.w3.org/TR/2013/REC-css-style-attr-20131107/
18 class StyleAttributeSanitizer extends Sanitizer {
21 protected $propertySanitizer;
24 * @param PropertySanitizer $propertySanitizer Sanitizer to test property declarations.
25 * Probably an instance of StylePropertySanitizer.
27 public function __construct( PropertySanitizer $propertySanitizer ) {
28 $this->propertySanitizer = $propertySanitizer;
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
37 public static function newDefault() {
38 // First, we need a matcher factory for the stuff all the sanitizers
40 $matcherFactory = MatcherFactory::singleton();
42 // This is the sanitizer for a single "property: value"
43 $propertySanitizer = new StylePropertySanitizer( $matcherFactory );
45 // StyleAttributeSanitizer brings it all together
46 $sanitizer = new StyleAttributeSanitizer( $propertySanitizer );
51 protected function doSanitize( CSSObject $object ) {
52 if ( !$object instanceof DeclarationList ) {
53 $this->sanitizationError( 'expected-declaration-list', $object );
56 return $this->sanitizeList( $this->propertySanitizer, $object );
60 * Sanitize a string value.
61 * @param string $string
62 * @return DeclarationList
64 public function sanitizeString( $string ) {
65 $parser = Parser::newFromString( $string );
66 $declarations = $parser->parseDeclarationList();
67 $this->sanitizationErrors = array_merge( $this->sanitizationErrors, $parser->getParseErrors() );
68 return $this->sanitizeList( $this->propertySanitizer, $declarations );