Download the PHP package sabberworm/php-css-parser without Composer
On this page you can find all versions of the php package sabberworm/php-css-parser. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download sabberworm/php-css-parser
More information about sabberworm/php-css-parser
Files in sabberworm/php-css-parser
Package php-css-parser
Short Description Parser for CSS Files written in PHP
License MIT
Homepage https://www.sabberworm.com/blog/2010/6/10/php-css-parser
Informations about the package php-css-parser
PHP CSS Parser
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
Extraction
To use the CSS Parser, create a new instance. The constructor takes the following form:
To read a file, for example, you’d do the following:
The resulting CSS document structure can be manipulated prior to being output.
Options
Charset
The charset option will only be used if the CSS file does not contain an @charset
declaration. 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.
Strict parsing
To have the parser throw an exception when encountering invalid/unknown constructs (as opposed to trying to ignore them and carry on parsing), supply a thusly configured \Sabberworm\CSS\Settings
object:
Note that this will also disable a workaround for parsing the unquoted variant of the legacy IE-specific filter
rule.
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 using this with input you have no control over as it’s not thoroughly covered by test cases.
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.
To access the items stored in a CSSList
– like the document you got back when calling $parser->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 for generic at-rules which are not covered by specific classes, i.e., not@import
,@charset
or@media
. A common example for this is@font-face
.DeclarationBlock
– aRuleSet
constrained by aSelector
; 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 CSSList
s (and Import
s as well as a Charset
), while a RuleSet
can only contain Rule
s.
If you want to manipulate a RuleSet
, use the methods addRule(Rule $rule)
, getRules()
and removeRule($rule)
(which accepts either a Rule
or a rule name; optionally suffixed by a dash to remove all related rules).
Rule
Rule
s just have a string key (the rule) and 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 numericsize
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 inURL("")
notation.
There is another abstract subclass of Value
, ValueList
: A ValueList
represents a lists of Value
s, separated by some separation character (mostly ,
, whitespace, or /
).
There are two types of ValueList
s:
RuleValueList
– The default type, used to represent all multivalued rules likefont: bold 12px/3 Helvetica, Verdana, sans-serif;
(where the value would be a whitespace-separated list of the primitive valuebold
, 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 likefilter: 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 the selectors are. Aliased asgetAllSelectors()
.getAllRuleSets()
– does what it says; no matter how deeply nested the rule sets are.getAllValues()
– finds allValue
objects insideRule
s.
To-Do
- More convenience methods (like
selectorsWithElement($sId/Class/TagName)
,attributesOfType($type)
,removeAttributesOfType($type)
) - 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
Shrink all absolute sizes to half
Remove unwanted rules
Output
To output the entire CSS document into a variable, just use ->render()
:
If you want to format the output, pass an instance of type \Sabberworm\CSS\OutputFormat
:
Or use one of the predefined formats:
To see what you can do with output formatting, look at the tests in tests/OutputFormatTest.php
.
Examples
Example 1 (At-Rules)
Input
Structure (var_dump()
)
Output (render()
)
Example 2 (Values)
Input
Structure (var_dump()
)
Output (render()
)
Class diagram
API and deprecation policy
Please have a look at our API and deprecation policy.
Contributing
Contributions in the form of bug reports, feature requests, or pull requests are more than welcome. :pray: Please have a look at our contribution guidelines to learn more about how to contribute to PHP-CSS-Parser.
Contributors/Thanks to
- oliverklee for lots of refactorings, code modernizations and CI integrations
- raxbg for contributions to parse
calc
, grid lines, and various bugfixes. - westonruter for bugfixes and improvements.
- FMCorz for many patches and suggestions, for being able to parse comments and IE hacks (in lenient mode).
- Lullabot for a patch that allows to know the line number for each parsed token.
- ju1ius for the specificity parsing code and the ability to expand/compact shorthand properties.
- ossinkine for a 150 time performance boost.
- GaryJones for lots of input and https://css-specificity.info/.
- docteurklein for output formatting and
CSSList->remove()
inspiration. - nicolopignatelli for PSR-0 compatibility.
- diegoembarcadero for keyframe at-rule parsing.
- goetas for
@namespace
at-rule support. - ziegenberg for general housekeeping and cleanup.
- View full list
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 continuous integration (CI) checks for this project (including unit tests),
- run
composer install
to install the development dependencies managed with Composer; - run
phive install
to install the development dependencies managed with PHIVE; - run
composer ci
to run all static and dynamic CI checks.
Details of other Composer scripts available (e.g. to run one specific CI check) are provided with composer list
.
All versions of php-css-parser with dependencies
ext-iconv Version *