noccylabs/csslike

$ git tag
0.1.0
0.1.1
0.1.2

$ git branch
* master

CssLike

This is a parser for CSS-like stylesheets.

Usage

Create a stylesheet and parse files and strings:

$style = new Stylesheet();
$style->parse("theme.style");
$style->parseString("style { property: value; }");

You can also pass a filename to the constructor:

$style = new Stylesheet("theme.style");

Get directives using the getDirective(name) and getAllDirectives() methods. Both functions return arrays even if only a single directive matches.

$style->parseString("color(red,#ff0000);");
$directives = $style->getDirective("color");

The result would be:

[
  [ 'color', [ 'red', '#ff0000' ]]
]

To match rules, use select(rule, ...):

$logformat = [
    'debug' => $style->select("log","log.debug","log:good"),
    'info'  => $style->select("log","log.info","log:good"),
    'warn'  => $style->select("log","log.warning","log:bad"),
    'error' => $style->select("log","log.error","log:bad")
];

In this case, the following would be returned:

[
  'debug' => [ 'style'=>'bold', 'color'=>'green' ],
  'info'  => [ 'style'=>'bold', 'color'=>'green' ],
  'warn'  => [ 'style'=>'bold' ],
  'error' => [ 'style'=>'bold', 'color'=>'red' ],
]

Definitions

Directives

Directives consist of a name and a number of parameters, and can be likened with functions. They can be used to define variables or add custom functionality.

foo('answer',42);
bar();
@baz(1,2,3);
#bin(hello world);

Rulesets

Rulesets combine properties and values based on a selector.

log {
    style: bold;
}
log.error { color: red; }
log:good
{
    color: green;
}

Comments

Comments are supported as blocks (/* .. */) and not as single lines (//):

/*  This is a comment! Comments can
    span multiple lines */

Patterns

Patterns can be thought of as functions, and can also be used to substitute placeholders with variable values etc.

$vars = [];
$style->onDirective("set", function ($name,$value) use (&$vars) {
    $vars[$name] = $value;
});
$style->onPattern("\${(.+?)}", function ($varname) use (&$vars) {
    return $vars[$varname];
});


set("foocolor","blue");

foo {
    /* will parse as 'color: blue' */
    color: ${foocolor};
}