MyIntervals / 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
http://www.sabberworm.com/blog/2010/6/10/php-css-parser
MIT License
1.76k stars 148 forks source link

Consider new value Term #108

Open FMCorz opened 8 years ago

FMCorz commented 8 years ago

I really like the API but I find it tricky to manipulate as CSS terms (auto, left, center, ...) are plain strings. As I'd like to change them in place without having to reconstruct the rule list it would be highly beneficial if they were instance of, for instance:

class Term extends Value {
}

What I currently need to do:

    if (preg_match('/cursor/i', $rule->getRule())) {
        $value = $rule->getValue();
        $hasList = false;

        $parts = [$value];
        if ($value instanceof RuleValueList) {
            $hastList = true;
            $parts = $value->getListComponents();
        }

        foreach ($parts as $key => $part) {
            if (!is_object($part)) {
                $parts[$key] = 'new value';
            }
        }

        if ($hasList) {
            $value->setListComponents($parts);
        } else {
            $rule->setValue($parts[0]);
        }

    }

If I missed something please let me know.

Thanks!

PS: I understand this would be a non-backwards compatible breaking change, unless a parser setting is added. Note that this should handle colours as Color instead.

sabberworm commented 8 years ago

While I like the proposed change for clarity sake, I’m not sure it really fixes the problem: what if I wanted to switch a term for a ValueList or a Size for a CSSFunction?

Maybe we could add a method that returned the value as a reference that one could easily swap (and have the same for ValueLists)?

FMCorz commented 8 years ago

Not sure I fancy the reference thing, but maybe it's just my own preference. I don't think that both having a class for terms, and having a way to swap a Value for another need to be solved in the same issue.

However, you make a very valid point and I'd love to see the ability to swap a Value for another. Now, my direct problem is that I cannot swap the values left to right without the procedure explained above. That can be solved simply solely with Term.

I'd also like to solve the calc parsing problem, ultimately if we had an Abstract CSS expression class, that would greatly help me. At this stage, all I need is to parse the CSS function, not so much to change its operators and operands.