Created
August 29, 2011 13:44
-
-
Save nathggns/1178418 to your computer and use it in GitHub Desktop.
Need help putting things in the right place
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| require_once 'util.php'; | |
| class parser { | |
| public $instructions = array(); // Array - Instructions for the interpreter | |
| public $css; // String - The formatted css code | |
| public $tree = array(); // Array - The output tree | |
| public $lines = array(); // Array - Lines of the formatted css code | |
| public $level = array(); // Array - List of different arrays to append to | |
| public $nest = 0; // Int - How far nested are we? | |
| public function tokenize() { | |
| $in = $this->instructions; | |
| $lines = $this->lines; | |
| foreach ($lines as $line) { | |
| $parts = explode(" ", $line); | |
| $ending = $parts[count($parts) - 1]; | |
| switch ($ending) { | |
| case '{': | |
| $in[] = array('opcode' => 'OPEN_BRACE', 'args' => $parts); | |
| break; | |
| case '}': | |
| $in[] = array('opcode' => 'CLOSE_BRACE', 'args' => $parts); | |
| break; | |
| case "\n": | |
| $in[] = array('opcode' => 'END_LINE', 'args' => $parts); | |
| break; | |
| default: | |
| $in[] = array('opcode' => 'OTHER', 'args' => $parts); | |
| break; | |
| } | |
| } | |
| $this->instructions = $in; | |
| } | |
| public function interpret() { | |
| $name = ''; | |
| foreach ($this->instructions as $index => $in) { | |
| $code = $in['opcode']; | |
| $args = $in['args']; | |
| switch($code) { | |
| case 'OPEN_BRACE': | |
| $this->nest++; | |
| $name = $args; | |
| array_pop($name); | |
| array_map('trim', $name); | |
| $name = implode(' ', $name); | |
| $this->level[] = array(); | |
| break; | |
| case 'CLOSE_BRACE': | |
| $this->nest--; | |
| $this->tree[$name] = $this->level[-1]; | |
| array_pop($this->level); | |
| break; | |
| default: | |
| $this->level[-1][] = $args; | |
| break; | |
| } | |
| } | |
| } | |
| public function parse($css) { | |
| $this->css = Util::normalise($css, false); | |
| $this->lines = explode("\n", $this->css); | |
| $this->lines = array_map("trim", $this->lines); | |
| $this->lines = array_filter($this->lines); | |
| $this->tokenize(); | |
| $this->interpret(); | |
| print_r($this->tree); | |
| } | |
| } | |
| $parser = new parser(); | |
| $parser->parse(file_get_contents('css.css')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment