A Parser for CSS Files written in PHP. Allows extraction of CSS files into a data structure, manipulation of said structure and output as (optimized) CSS

Overview

PHP CSS Parser

Build Status

A Parser for CSS Files written in PHP. Allows extraction of CSS files into a data structure, manipulation of said structure and output as (optimized) CSS.

Usage

Installation using composer

Add php-css-parser to your composer.json

{
    "require": {
        "sabberworm/php-css-parser": "*"
    }
}

Extraction

To use the CSS Parser, create a new instance. The constructor takes the following form:

new Sabberworm\CSS\Parser($sText);

To read a file, for example, you’d do the following:

$oCssParser = new Sabberworm\CSS\Parser(file_get_contents('somefile.css'));
$oCssDocument = $oCssParser->parse();

The resulting CSS document structure can be manipulated prior to being output.

Options

Charset

The charset option is used only if no @charset declaration is found in the CSS file. UTF-8 is the default, so you won’t have to create a settings object at all if you don’t intend to change that.

$oSettings = Sabberworm\CSS\Settings::create()->withDefaultCharset('windows-1252');
new Sabberworm\CSS\Parser($sText, $oSettings);

Strict parsing

To have the parser choke on invalid rules, supply a thusly configured Sabberworm\CSS\Settings object:

$oCssParser = new Sabberworm\CSS\Parser(file_get_contents('somefile.css'), Sabberworm\CSS\Settings::create()->beStrict());

Disable multibyte functions

To achieve faster parsing, you can choose to have PHP-CSS-Parser use regular string functions instead of mb_* functions. This should work fine in most cases, even for UTF-8 files, as all the multibyte characters are in string literals. Still it’s not recommended to use this with input you have no control over as it’s not thoroughly covered by test cases.

$oSettings = Sabberworm\CSS\Settings::create()->withMultibyteSupport(false);
new Sabberworm\CSS\Parser($sText, $oSettings);

Manipulation

The resulting data structure consists mainly of five basic types: CSSList, RuleSet, Rule, Selector and Value. There are two additional types used: Import and Charset which you won’t use often.

CSSList

CSSList represents a generic CSS container, most likely containing declaration blocks (rule sets with a selector) but it may also contain at-rules, charset declarations, etc. CSSList has the following concrete subtypes:

  • Document – representing the root of a CSS file.
  • MediaQuery – represents a subsection of a CSSList that only applies to a output device matching the contained media query.

To access the items stored in a CSSList – like the document you got back when calling $oCssParser->parse() –, use getContents(), then iterate over that collection and use instanceof to check whether you’re dealing with another CSSList, a RuleSet, a Import or a Charset.

To append a new item (selector, media query, etc.) to an existing CSSList, construct it using the constructor for this class and use the append($oItem) method.

RuleSet

RuleSet is a container for individual rules. The most common form of a rule set is one constrained by a selector. The following concrete subtypes exist:

  • AtRuleSet – for generic at-rules which do not match the ones specifically mentioned like @import, @charset or @media. A common example for this is @font-face.
  • DeclarationBlock – a RuleSet constrained by a Selector; contains an array of selector objects (comma-separated in the CSS) as well as the rules to be applied to the matching elements.

Note: A CSSList can contain other CSSLists (and Imports as well as a Charset) while a RuleSet can only contain Rules.

If you want to manipulate a RuleSet, use the methods addRule(Rule $oRule), getRules() and removeRule($mRule) (which accepts either a Rule instance or a rule name; optionally suffixed by a dash to remove all related rules).

Rule

Rules just have a key (the rule) and a value. These values are all instances of a Value.

Value

Value is an abstract class that only defines the render method. The concrete subclasses for atomic value types are:

  • Size – consists of a numeric size value and a unit.
  • Color – colors can be input in the form #rrggbb, #rgb or schema(val1, val2, …) but are always stored as an array of ('s' => val1, 'c' => val2, 'h' => val3, …) and output in the second form.
  • CSSString – this is just a wrapper for quoted strings to distinguish them from keywords; always output with double quotes.
  • URL – URLs in CSS; always output in URL("") notation.

There is another abstract subclass of Value, ValueList. A ValueList represents a lists of Values, separated by some separation character (mostly ,, whitespace, or /). There are two types of ValueLists:

  • RuleValueList – The default type, used to represent all multi-valued rules like font: bold 12px/3 Helvetica, Verdana, sans-serif; (where the value would be a whitespace-separated list of the primitive value bold, a slash-separated list and a comma-separated list).
  • CSSFunction – A special kind of value that also contains a function name and where the values are the function’s arguments. Also handles equals-sign-separated argument lists like filter: alpha(opacity=90);.

Convenience methods

There are a few convenience methods on Document to ease finding, manipulating and deleting rules:

  • getAllDeclarationBlocks() – does what it says; no matter how deeply nested your selectors are. Aliased as getAllSelectors().
  • getAllRuleSets() – does what it says; no matter how deeply nested your rule sets are.
  • getAllValues() – finds all Value objects inside Rules.

To-Do

  • More convenience methods [like selectorsWithElement($sId/Class/TagName), attributesOfType($sType), removeAttributesOfType($sType)]
  • Real multibyte support. Currently only multibyte charsets whose first 255 code points take up only one byte and are identical with ASCII are supported (yes, UTF-8 fits this description).
  • Named color support (using Color instead of an anonymous string literal)

Use cases

Use Parser to prepend an id to all selectors

$sMyId = "#my_id";
$oParser = new Sabberworm\CSS\Parser($sText);
$oCss = $oParser->parse();
foreach($oCss->getAllDeclarationBlocks() as $oBlock) {
	foreach($oBlock->getSelectors() as $oSelector) {
		//Loop over all selector parts (the comma-separated strings in a selector) and prepend the id
		$oSelector->setSelector($sMyId.' '.$oSelector->getSelector());
	}
}

Shrink all absolute sizes to half

$oParser = new Sabberworm\CSS\Parser($sText);
$oCss = $oParser->parse();
foreach($oCss->getAllValues() as $mValue) {
	if($mValue instanceof CSSSize && !$mValue->isRelative()) {
		$mValue->setSize($mValue->getSize()/2);
	}
}

Remove unwanted rules

$oParser = new Sabberworm\CSS\Parser($sText);
$oCss = $oParser->parse();
foreach($oCss->getAllRuleSets() as $oRuleSet) {
	$oRuleSet->removeRule('font-'); //Note that the added dash will make this remove all rules starting with font- (like font-size, font-weight, etc.) as well as a potential font-rule
	$oRuleSet->removeRule('cursor');
}

Output

To output the entire CSS document into a variable, just use ->render():

$oCssParser = new Sabberworm\CSS\Parser(file_get_contents('somefile.css'));
$oCssDocument = $oCssParser->parse();
print $oCssDocument->render();

If you want to format the output, pass an instance of type Sabberworm\CSS\OutputFormat:

$oFormat = Sabberworm\CSS\OutputFormat::create()->indentWithSpaces(4)->setSpaceBetweenRules("\n");
print $oCssDocument->render($oFormat);

Or use one of the predefined formats:

print $oCssDocument->render(Sabberworm\CSS\OutputFormat::createPretty());
print $oCssDocument->render(Sabberworm\CSS\OutputFormat::createCompact());

To see what you can do with output formatting, look at the tests in tests/Sabberworm/CSS/OutputFormatTest.php.

Examples

Example 1 (At-Rules)

Input

@charset "utf-8";

@font-face {
  font-family: "CrassRoots";
  src: url("../media/cr.ttf")
}

html, body {
    font-size: 1.6em
}

@keyframes mymove {
	from { top: 0px; }
	to { top: 200px; }
}

Structure (var_dump())

class Sabberworm\CSS\CSSList\Document#4 (2) {
  protected $aContents =>
  array(4) {
    [0] =>
    class Sabberworm\CSS\Property\Charset#6 (2) {
      private $sCharset =>
      class Sabberworm\CSS\Value\CSSString#5 (2) {
        private $sString =>
        string(5) "utf-8"
        protected $iLineNo =>
        int(1)
      }
      protected $iLineNo =>
      int(1)
    }
    [1] =>
    class Sabberworm\CSS\RuleSet\AtRuleSet#7 (4) {
      private $sType =>
      string(9) "font-face"
      private $sArgs =>
      string(0) ""
      private $aRules =>
      array(2) {
        'font-family' =>
        array(1) {
          [0] =>
          class Sabberworm\CSS\Rule\Rule#8 (4) {
            private $sRule =>
            string(11) "font-family"
            private $mValue =>
            class Sabberworm\CSS\Value\CSSString#9 (2) {
              private $sString =>
              string(10) "CrassRoots"
              protected $iLineNo =>
              int(4)
            }
            private $bIsImportant =>
            bool(false)
            protected $iLineNo =>
            int(4)
          }
        }
        'src' =>
        array(1) {
          [0] =>
          class Sabberworm\CSS\Rule\Rule#10 (4) {
            private $sRule =>
            string(3) "src"
            private $mValue =>
            class Sabberworm\CSS\Value\URL#11 (2) {
              private $oURL =>
              class Sabberworm\CSS\Value\CSSString#12 (2) {
                private $sString =>
                string(15) "../media/cr.ttf"
                protected $iLineNo =>
                int(5)
              }
              protected $iLineNo =>
              int(5)
            }
            private $bIsImportant =>
            bool(false)
            protected $iLineNo =>
            int(5)
          }
        }
      }
      protected $iLineNo =>
      int(3)
    }
    [2] =>
    class Sabberworm\CSS\RuleSet\DeclarationBlock#13 (3) {
      private $aSelectors =>
      array(2) {
        [0] =>
        class Sabberworm\CSS\Property\Selector#14 (2) {
          private $sSelector =>
          string(4) "html"
          private $iSpecificity =>
          NULL
        }
        [1] =>
        class Sabberworm\CSS\Property\Selector#15 (2) {
          private $sSelector =>
          string(4) "body"
          private $iSpecificity =>
          NULL
        }
      }
      private $aRules =>
      array(1) {
        'font-size' =>
        array(1) {
          [0] =>
          class Sabberworm\CSS\Rule\Rule#16 (4) {
            private $sRule =>
            string(9) "font-size"
            private $mValue =>
            class Sabberworm\CSS\Value\Size#17 (4) {
              private $fSize =>
              double(1.6)
              private $sUnit =>
              string(2) "em"
              private $bIsColorComponent =>
              bool(false)
              protected $iLineNo =>
              int(9)
            }
            private $bIsImportant =>
            bool(false)
            protected $iLineNo =>
            int(9)
          }
        }
      }
      protected $iLineNo =>
      int(8)
    }
    [3] =>
    class Sabberworm\CSS\CSSList\KeyFrame#18 (4) {
      private $vendorKeyFrame =>
      string(9) "keyframes"
      private $animationName =>
      string(6) "mymove"
      protected $aContents =>
      array(2) {
        [0] =>
        class Sabberworm\CSS\RuleSet\DeclarationBlock#19 (3) {
          private $aSelectors =>
          array(1) {
            [0] =>
            class Sabberworm\CSS\Property\Selector#20 (2) {
              private $sSelector =>
              string(4) "from"
              private $iSpecificity =>
              NULL
            }
          }
          private $aRules =>
          array(1) {
            'top' =>
            array(1) {
              [0] =>
              class Sabberworm\CSS\Rule\Rule#21 (4) {
                private $sRule =>
                string(3) "top"
                private $mValue =>
                class Sabberworm\CSS\Value\Size#22 (4) {
                  private $fSize =>
                  double(0)
                  private $sUnit =>
                  string(2) "px"
                  private $bIsColorComponent =>
                  bool(false)
                  protected $iLineNo =>
                  int(13)
                }
                private $bIsImportant =>
                bool(false)
                protected $iLineNo =>
                int(13)
              }
            }
          }
          protected $iLineNo =>
          int(13)
        }
        [1] =>
        class Sabberworm\CSS\RuleSet\DeclarationBlock#23 (3) {
          private $aSelectors =>
          array(1) {
            [0] =>
            class Sabberworm\CSS\Property\Selector#24 (2) {
              private $sSelector =>
              string(2) "to"
              private $iSpecificity =>
              NULL
            }
          }
          private $aRules =>
          array(1) {
            'top' =>
            array(1) {
              [0] =>
              class Sabberworm\CSS\Rule\Rule#25 (4) {
                private $sRule =>
                string(3) "top"
                private $mValue =>
                class Sabberworm\CSS\Value\Size#26 (4) {
                  private $fSize =>
                  double(200)
                  private $sUnit =>
                  string(2) "px"
                  private $bIsColorComponent =>
                  bool(false)
                  protected $iLineNo =>
                  int(14)
                }
                private $bIsImportant =>
                bool(false)
                protected $iLineNo =>
                int(14)
              }
            }
          }
          protected $iLineNo =>
          int(14)
        }
      }
      protected $iLineNo =>
      int(12)
    }
  }
  protected $iLineNo =>
  int(1)
}

Output (render())

@charset "utf-8";
@font-face {font-family: "CrassRoots";src: url("../media/cr.ttf");}
html, body {font-size: 1.6em;}
@keyframes mymove {from {top: 0px;}
	to {top: 200px;}}

Example 2 (Values)

Input

#header {
	margin: 10px 2em 1cm 2%;
	font-family: Verdana, Helvetica, "Gill Sans", sans-serif;
	color: red !important;
}

Structure (var_dump())

class Sabberworm\CSS\CSSList\Document#4 (2) {
  protected $aContents =>
  array(1) {
    [0] =>
    class Sabberworm\CSS\RuleSet\DeclarationBlock#5 (3) {
      private $aSelectors =>
      array(1) {
        [0] =>
        class Sabberworm\CSS\Property\Selector#6 (2) {
          private $sSelector =>
          string(7) "#header"
          private $iSpecificity =>
          NULL
        }
      }
      private $aRules =>
      array(3) {
        'margin' =>
        array(1) {
          [0] =>
          class Sabberworm\CSS\Rule\Rule#7 (4) {
            private $sRule =>
            string(6) "margin"
            private $mValue =>
            class Sabberworm\CSS\Value\RuleValueList#12 (3) {
              protected $aComponents =>
              array(4) {
                [0] =>
                class Sabberworm\CSS\Value\Size#8 (4) {
                  private $fSize =>
                  double(10)
                  private $sUnit =>
                  string(2) "px"
                  private $bIsColorComponent =>
                  bool(false)
                  protected $iLineNo =>
                  int(2)
                }
                [1] =>
                class Sabberworm\CSS\Value\Size#9 (4) {
                  private $fSize =>
                  double(2)
                  private $sUnit =>
                  string(2) "em"
                  private $bIsColorComponent =>
                  bool(false)
                  protected $iLineNo =>
                  int(2)
                }
                [2] =>
                class Sabberworm\CSS\Value\Size#10 (4) {
                  private $fSize =>
                  double(1)
                  private $sUnit =>
                  string(2) "cm"
                  private $bIsColorComponent =>
                  bool(false)
                  protected $iLineNo =>
                  int(2)
                }
                [3] =>
                class Sabberworm\CSS\Value\Size#11 (4) {
                  private $fSize =>
                  double(2)
                  private $sUnit =>
                  string(1) "%"
                  private $bIsColorComponent =>
                  bool(false)
                  protected $iLineNo =>
                  int(2)
                }
              }
              protected $sSeparator =>
              string(1) " "
              protected $iLineNo =>
              int(2)
            }
            private $bIsImportant =>
            bool(false)
            protected $iLineNo =>
            int(2)
          }
        }
        'font-family' =>
        array(1) {
          [0] =>
          class Sabberworm\CSS\Rule\Rule#13 (4) {
            private $sRule =>
            string(11) "font-family"
            private $mValue =>
            class Sabberworm\CSS\Value\RuleValueList#15 (3) {
              protected $aComponents =>
              array(4) {
                [0] =>
                string(7) "Verdana"
                [1] =>
                string(9) "Helvetica"
                [2] =>
                class Sabberworm\CSS\Value\CSSString#14 (2) {
                  private $sString =>
                  string(9) "Gill Sans"
                  protected $iLineNo =>
                  int(3)
                }
                [3] =>
                string(10) "sans-serif"
              }
              protected $sSeparator =>
              string(1) ","
              protected $iLineNo =>
              int(3)
            }
            private $bIsImportant =>
            bool(false)
            protected $iLineNo =>
            int(3)
          }
        }
        'color' =>
        array(1) {
          [0] =>
          class Sabberworm\CSS\Rule\Rule#16 (4) {
            private $sRule =>
            string(5) "color"
            private $mValue =>
            string(3) "red"
            private $bIsImportant =>
            bool(true)
            protected $iLineNo =>
            int(4)
          }
        }
      }
      protected $iLineNo =>
      int(1)
    }
  }
  protected $iLineNo =>
  int(1)
}

Output (render())

#header {margin: 10px 2em 1cm 2%;font-family: Verdana,Helvetica,"Gill Sans",sans-serif;color: red !important;}

Contributors/Thanks to

Misc

  • Legacy Support: The latest pre-PSR-0 version of this project can be checked with the 0.9.0 tag.
  • Running Tests: To run all unit tests for this project, run composer install to install phpunit and use ./vendor/phpunit/phpunit/phpunit.

License

PHP-CSS-Parser is freely distributable under the terms of an MIT-style license.

Copyright (c) 2011 Raphael Schweikert, http://sabberworm.com/

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments
  • Add line number support in the sabberworm CSS parser

    Add line number support in the sabberworm CSS parser

    AMP HTML is a restricted subset of HTML (See https://www.ampproject.org/ for more details) and the AMP PHP Library provide validation and HTML to AMP HTML conversion utilities. We're using the masterminds/html5-php library to parse HTML5 and we're using sabberworm/php-css-parser to parse the CSS in the AMP PHP Library

    After parsing the CSS parse we report any problems in the CSS (for e.g. !important is disallowed in the AMP dialect of HTML, we use the sabberworm parser to find all the uses of !important for instance)

    Now the CSS supplied by the user could be hundreds / thousands of lines long. So its not useful to simply say that !important was used and is not allowed. We should be able to say which line the problem occurred.

    This pull request adds support for line numbers. Here is how we're using this https://github.com/Lullabot/amp-library/pull/80#issuecomment-222695630 Notice the line numbers reported in the validation errors which coming from code submitted in this PR.

    Would greatly appreciate if you had a look and merge it if you believe this feature would be useful. Hopefully the code changes have not missed anything out.

    Thanks for this useful library BTW.

    opened by sidkshatriya 23
  • Support CSS3 calc()

    Support CSS3 calc()

    Following document throws Sabberworm\CSS\Parsing\UnexpectedTokenException with message Identifier expected. Got “+ 20p”. This is expected to be valid CSS document:

    body
    {
        border-top: solid green 0em;
        border-top-width: calc(1em + 20px);
    }
    

    The parser is initialized like this:

    $settings = Sabberworm\CSS\Settings::create();
    $settings->beStrict();
    $parser = new Sabberworm\CSS\Parser($css, $settings);
    

    I think Parser::parseValue() would need to be modified but I have no idea how to fix this.

    tbd css3 
    opened by mikkorantalainen 9
  • added support for merging imported stylesheets

    added support for merging imported stylesheets

    This commit allows to resolve @import rules, merging their declarations into the main stylesheet. Required a few changes to the API, see the comments.

    opened by ju1ius 8
  • CSSRule->__toString doesn't work with sized values

    CSSRule->__toString doesn't work with sized values

    If I have a CSS rule as follows (this is in your example css): div.rating-cancel,div.star-rating{width:17px;height:15px;}

    The CSSRule->__toString either throws an error, or it looks like this: width: Object;

    The problem is on line 707 when it tries to implode a comma into the values. When a value is a CSSSize, it produces the above result.

    For you to test this, in your CSSParserTests.php file, change line 19 to: $oDoc = $oParser->parse(); and add this line after the catch clause echo $oDoc->__toString();

    opened by lieutdan13 8
  • retain CSSList and Rule comments when rendering CSS

    retain CSSList and Rule comments when rendering CSS

    Hi, was banging my head against the wall as my css comments would vanish when using a autoprefixer repo that utilizes this repo. Found out that the issue was that comments are only partly implemented in this repo: they are recognized, but when rendering the parsed css code they are not added back.

    So I rolled up my sleeves and did this PR.

    This PR does two things:

    1. fix the comments implementation as only the first comments where taken and not the subsequent comments in a CSSList
    2. adds the comments back into the rendered CSS (as also requested in #38 )

    So this is my first PR in this repo, would love to have some feedback / discussion / tests :)

    Thanks in advance, regards, Ruud

    opened by Ruud68 7
  • How to remove @import

    How to remove @import

    Hi,

    Just like

    foreach($oCssDocument->getAllRuleSets() as $oRuleSet) {
    	$oRuleSet->removeRule('-moz-binding');
    	$oRuleSet->removeRule('behavior');
    	$oRuleSet->removeRule('background-image');
    	$oRuleSet->removeRule('xss');
    }
    

    Can we remove @import url("chrome://communicator/skin/"); line via removeRule ?

    opened by teckkid 7
  • Lacks PHP v8.1 compatibility

    Lacks PHP v8.1 compatibility

    PHP v8.1 (currently a release candidate) deprecates several parameter types and throws warnings such as Deprecated: preg_split(): Passing null to parameter #3 ($limit) of type int is deprecated in PHP-CSS-Parser\lib\Sabberworm\CSS\Parsing\ParserState.php on line 285

    opened by dleffler 6
  • Drop support for older PHP versions

    Drop support for older PHP versions

    I propose this library drops support for older PHP versions so it can use newer PHP features.

    According to https://www.php.net/supported-versions.php, PHP 7.2 recently reached its end of life. So I propose to drop support for all PHP versions < 7.2.

    (We then can use Rector to upgrade the code accordingly.)

    What do you think?

    opened by oliverklee 5
  • Selector validation

    Selector validation

    The way we currently detect extra closing block brackets } is not perfect and still causes issues, because we just ignore them. This however does not match the browsers' behavior. Depending on the case the extra closing brackets might end up as part of the selector. Take a look at the following:

    @keyframes mymove {
      from { top: 0px; }
    }
    
    #test {
      color: white;
      background: green;
    }
    
    body
      background: black;
      }
    
    #test {
      display: block;
      background: red;
      color: white;
    }
    #test {
      display: block;
      background: white;
      color: black;
    }
    

    The body selector is missing an opening { so the selector string will be everything up to the next { found at the first #test { declaration. This makes the selector invalid, so the first definition of #test must be skipped, but parsing must continue. The final tree must include the @keyframes, first #test definition and the last #test definition. The rules in between must be skipped.

    This is why I think we should have a selector validation and skip the rule sets for invalid selectors (which matches the browsers' behavior).

    The modifications in this PR will change the output of the library, so this change might be considered BC breaking, but I believe it is a move in the right direction. I tried to build the selector validation according to the definition found in this document. More specifically this line In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_);. It is not perfect yet, because it doesn't check for escaped characters, or a valid start of the selector. I might try to add these if we agree that this is a viable approach to the problem.

    Let me know what you think.

    opened by raxbg 5
  • unicode-range is not parsed

    unicode-range is not parsed

    I try to parse this below mentioned font-face, unicode-range is missing in output.. INPUT: @font-face { font-family: 'specialCharacters'; src: url('/fonts/some.otf') format('truetype'); unicode-range: U+26; font-weight: normal; font-style: normal; }

    OUTPUT: @font-face {font-family: "specialCharacters";src: url("/fonts/some.otf") format("truetype");font-weight: normal;font-style: normal;}

    Is there any solution for this ?

    opened by aruntvr 5
  • Nested calc() values are not parsed

    Nested calc() values are not parsed

    Nested calc values are used in Bootstrap 4 on things like tooltips, for example:

    .testclass1 {
        bottom: calc(( 0.5rem - 1px ) * -1);
    }
    

    The php css parser seems to ignore these.

    #79 has fixed calc values for subtraction, would supporting nesting be possible too?

    opened by bmbrands 5
  • Is there a way to render block wrapper with @media

    Is there a way to render block wrapper with @media

    @media (min-width: 992px){ .footer__ajax-modal-dialog{ max-width: 1380px; margin: 2.87rem auto !important; } .footer__ajax-modal{ padding: 0 !important; overflow: hidden !important; } }

    As i want just want to render the .footer__ajax-modal class from @media(min-width:992px) below are the php code.

    PHP code:

    $criticalCss = array(); $parser = new Parser(file_get_contents($sourceCssFile)); $cssDocument = $parser->parse(); $_select = '.footer__ajax-modal'; foreach ($cssDocument->getAllDeclarationBlocks() as $block) { $selectors = array(); foreach ($block->getSelectors() as $selector) { $selectors[] = $selector->getSelector(); } if(in_array($_select,$selectors)){ $format = OutputFormat::create() ->indentWithSpaces(4)->setSpaceBetweenRules("\n"); $criticalCss[] = $block->render($format); } }

    so the problem is,we can get the block but the @media is gone.anyone can help ?

    thanks

    opened by TangLiang 0
  • Allow rgb(R G B / A) notation

    Allow rgb(R G B / A) notation

    it's valid to write a color value as rgb(R G B / A), see MDN.

    I've tackled this with a simple approach, converting it to rgba during parsing and recognizing this notation with a regexp on a peek, see this commit: https://github.com/jhard/PHP-CSS-Parser/commit/a477cb4697b3ee1bf98d4f48463173c0febbb0a8

    I'm a monkey and I'm terrible at git and github (and PHP, some will say, and they're not wrong). If this approach is up to your standards, I'd be happy to create a pull request (I might need some hand-holding and encouragement, but I've done this before). If there's a better approach than using a regexp and peek, I might be able to do that, too.

    It would change the CSS: rgb(R G B / A) goes in, rgba(R, G, B, A) is rendered out, I'm not sure what your policy on that is. If you don't like the conversion to rgba, I understand.

    Thanks for your time!

    opened by jhard 0
  • Fix the `Size` constructor arguments in `DeclarationBlock`

    Fix the `Size` constructor arguments in `DeclarationBlock`

    This will fix the following PHPStan warning:

    			message: "#^Class Sabberworm\\\\CSS\\\\Value\\\\Size constructor invoked with 5 parameters, 1\\-4 required\\.$#"
    			count: 2
    			path: ../src/RuleSet/DeclarationBlock.php
    

    Note: We'll need to check which argument is superfluous. It's not the last one (the line number).

    hacktoberfest 
    opened by oliverklee 0
  • Add proper setters and getters to `OutputFormat`

    Add proper setters and getters to `OutputFormat`

    We should add proper getters and setters for the properties of OutputFormat. This should be covered with unit tests similar to this one: https://github.com/oliverklee/ext-oelib/blob/main/Tests/Unit/Domain/Model/GermanZipCodeTest.php#L48

    Adding setIndentation will also fix a PHPStan warning, i.e., we'll need to regenerate the baseline then using composer phpstan:baseline.

    When the last property is covered accordingly, we should remove the get and set methods as well as __call.

    This should be split in multiple PRs in order to keep the PRs small, e.g., one property at a time.

    hacktoberfest 
    opened by oliverklee 0
  • Fix undefined `$oVal` in `CalcFunction`

    Fix undefined `$oVal` in `CalcFunction`

    There is one instance in CalcFunction where $oVal might not be defined. We need to make sure that it is always defined (e.g., as null), and handle those cases.

    This fixes a PHPStan warning in the baseline (i.e., we need to regenerate the baseline with composer phpstan:baseline after this has been fixed).

    hacktoberfest 
    opened by oliverklee 0
Releases(8.3.0)
  • 8.3.0(Feb 22, 2019)

    8.3.0 (2019-02-22)

    • Refactor parsing logic to mostly reside in the class files whose data structure is to be parsed (this should eventually allow us to unit-test specific parts of the parsing logic individually).
    • Fix error in parsing calc expessions when the first operand is a negative number, thanks to @raxbg.
    • Support parsing CSS4 colors in hex notation with alpha values, thanks to @raxbg.
    • Swallow more errors in lenient mode, thanks to @raxbg.
    • Allow specifying arbitrary strings to output before and after declaration blocks, thanks to @westonruter.
    • No backwards-incompatible changes
    • No deprecations
    Source code(tar.gz)
    Source code(zip)
  • 8.2.0(Feb 22, 2019)

    8.2.0 (2018-07-13)

    • Support parsing calc(), thanks to @raxbg.
    • Support parsing grid-lines, again thanks to @raxbg.
    • Support parsing legacy IE filters (progid:) in lenient mode, thanks to @FMCorz
    • Performance improvements parsing large files, again thanks to @FMCorz
    • No backwards-incompatible changes
    • No deprecations
    Source code(tar.gz)
    Source code(zip)
  • 8.1.0(Jul 19, 2016)

    8.1.0 (2016-07-19)

    • Comments are no longer silently ignored but stored with the object with which they appear (no render support, though). Thanks to @FMCorz.
    • The IE hacks using \0 and \9 can now be parsed (and rendered) in lenient mode. Thanks (again) to @FMCorz.
    • Media queries with or without spaces before the query are parsed. Still no real parsing support, though. Sorry…
    • PHPUnit is now listed as a dev-dependency in composer.json.
    • No backwards-incompatible changes
    • No deprecations
    Source code(tar.gz)
    Source code(zip)
  • 8.0.0(Jun 30, 2016)

    8.0.0 (2016-06-30)

    • Store source CSS line numbers in tokens and parsing exceptions.
    • No deprecations

    Backwards-incompatible changes

    • Unrecoverable parser errors throw an exception of type Sabberworm\CSS\Parsing\SourceException instead of \Exception.
    Source code(tar.gz)
    Source code(zip)
  • 7.0.3(Apr 26, 2016)

  • 7.0.2(Feb 11, 2016)

  • 7.0.1(Dec 25, 2015)

  • 7.0.0(Aug 24, 2015)

    7.0.0 (2015-08-24)

    • Compatibility with PHP 7. Well timed, eh?

    Deprecations

    • The Sabberworm\CSS\Value\String class has been renamed to Sabberworm\CSS\Value\CSSString.
    Source code(tar.gz)
    Source code(zip)
  • 6.0.1(Aug 24, 2015)

  • 6.0.0(Jul 4, 2014)

    6.0.0 (2014-07-03)

    • Format output using Sabberworm\CSS\OutputFormat
    • No backwards-incompatible changes

    Deprecations

    • The parse() method replaces __toString with an optional argument (instance of the OutputFormat class)
    Source code(tar.gz)
    Source code(zip)
  • 5.2.0(Jul 4, 2014)

    5.2.0 (2014-06-30)

    • Support removing a selector from a declaration block using $oBlock->removeSelector($mSelector)
    • Introduce a specialized exception (Sabberworm\CSS\Parsing\OuputException) for exceptions during output rendering
    • No deprecations

    Backwards-incompatible changes

    • Outputting a declaration block that has no selectors throws an OuputException instead of outputting an invalid {…} into the CSS document.
    Source code(tar.gz)
    Source code(zip)
  • 5.1.2(Apr 24, 2014)

    5.1.2 (2013-10-30)

    • Remove the use of consumeUntil in comment parsing. This makes it possible to parse comments such as /** Perfectly valid **/
    • Add fr relative size unit
    • Fix some issues with HHVM
    • No backwards-incompatible changes
    • No deprecations
    Source code(tar.gz)
    Source code(zip)
  • 5.1.1(Jul 4, 2014)

The Asset component manages URL generation and versioning of web assets such as CSS stylesheets, JavaScript files and image files.

Asset Component The Asset component manages URL generation and versioning of web assets such as CSS stylesheets, JavaScript files and image files. Res

Symfony 2.9k Jan 5, 2023
:cake: Less parser plugin for CakePHP

Less parser plugin for CakePHP 3.X This plugin has a helper to help you parsing .less files in CakePHP 3.0 applications. By default, the helper will p

Òscar Casajuana 17 Jan 1, 2022
Combines. minifies, and serves CSS or Javascript files

Welcome to Minify! Minify is an HTTP server for JS and CSS assets. It compresses and combines files and serves it with appropriate headers, allowing c

Steve Clay 3k Jan 7, 2023
NotrinosERP is an open source, web-based enterprise management system that written in PHP and MySql.

NotrinosERP is an open source, web-based enterprise management system that written in PHP and MySql. NotrinosERP contains all the required modules for running any small to medium size businesses. It supports multi users, multi currencies, multi languages

Phương 56 Dec 20, 2022
Put your assets into the pipe and smoke them.

Pipe Put your assets into the pipe and smoke them. Pipe is an asset pipeline in the spirit of Sprockets. It's meant as the practical way for managing

Christoph Hochstrasser 121 May 5, 2021
GLPI is a Free Asset and IT Management Software package, Data center management, ITIL Service Desk, licenses tracking and software auditing.

GLPI stands for Gestionnaire Libre de Parc Informatique is a Free Asset and IT Management Software package, that provides ITIL Service Desk features, licenses tracking and software auditing.

GLPI 2.9k Jan 2, 2023
Assets Manager for "Vitewind" Theme, will inject CSS and JS assets for "Vitewind" theme to work properly with viteJS in development and production

Vitewind Manager plugin ?? Windi CSS and ⚡️ Vite, for ?? OctoberCMS & ❄️ WinterCMS Introduction This is a helper plugin for ?? Vitewind theme, don't i

Adil Chehabi 4 May 29, 2022
Commenting program developed with Html & Css & Php JavaScript Languages ​​and MySql

CommentSystem [BETA] Commenting program developed with Html & Css & Php JavaScript Languages and MySql How does it work ? After you set up your Databa

Azad 0 May 19, 2022
Middleware to minify the Html, CSS and Javascript content using wyrihaximus/compress

middlewares/minifier Middleware to minify the Html, CSS and Javascript content using wyrihaximus/compress and the following compressors by default: wy

Middlewares 15 Oct 25, 2022
An asset compression plugin for CakePHP. Provides file concatenation and a flexible filter system for preprocessing and minification.

Asset Compress Asset Compress is CakePHP plugin for helping reduce the number of requests, and optimizing the remaining requests your application make

Mark Story 367 Jul 20, 2022
A fast Javascript minifier that removes unnecessary whitespace and comments

js-minify A fast Javascript minifier that removes unnecessary whitespace and comments Installation If you are using Composer, use composer require gar

Patrick van Bergen 5 Aug 19, 2022
Asset Management for PHP

Assetic Assetic is an asset management framework for PHP. Project status This project is not maintained anymore. Development has been taken over at ht

Kris Wallsmith 3.8k Jan 4, 2023
Javascript Minifier built in PHP

JShrink JShrink is a php class that minifies javascript so that it can be delivered to the client quicker. This code can be used by any product lookin

Tedious Developments 678 Dec 31, 2022
A PHP implementation of bower :bird:

Bowerphp An implementation of bower in PHP. https://bowerphp.github.io/ Installation $ composer require beelab/bowerphp Configuration Currently, you c

BeeLab 473 Dec 30, 2022
PHP class to generate bookmarklets from Javascript code

Bookmarklet Gen Convert readable Javascript code into bookmarklet links Features removes comments compresses code by removing extraneous spaces, but n

྅༻ Ǭɀħ ༄༆ཉ 13 Oct 5, 2022
:accept: Stringy - A PHP string manipulation library with multibyte support, performance optimized

?? Stringy A PHP string manipulation library with multibyte support. Compatible with PHP 7+ 100% compatible with the original "Stringy" library, but t

Lars Moelleken 144 Dec 12, 2022
Stringy - A PHP string manipulation library with multibyte support, performance optimized

Stringy - A PHP string manipulation library with multibyte support, performance optimized

Lars Moelleken 145 Jan 1, 2023
YCOM Impersonate. Login as selected YCOM user 🧙‍♂️in frontend.

YCOM Impersonate Login as selected YCOM user in frontend. Features: Backend users with admin rights or YCOM[] rights, can be automatically logged in v

Friends Of REDAXO 17 Sep 12, 2022
[DEPRECATED] Library for extraction of domain parts e.g. TLD. Domain parser that uses Public Suffix List

DEPRECATED Consider to use https://github.com/jeremykendall/php-domain-parser as maintained alternative. TLDExtract TLDExtract accurately separates th

Oleksandr Fediashov 216 Oct 18, 2022
A full-featured Webpack + vue-loader setup with hot reload, linting, testing & css extraction.

#Vue-Cli Template for Larvel + Webpack + Hotreload (HMR) I had a really tough time getting my workflow rocking between Laravel and VueJS projects. I f

Gary Williams 73 Nov 29, 2022