PhpPeg\PHPBuilder::replace PHP Method

replace() public method

public replace ( $replacements, &$array = NULL )
    function replace($replacements, &$array = NULL)
    {
        if ($array === NULL) {
            unset($array);
            $array =& $this->lines;
        }
        $i = 0;
        while ($i < count($array)) {
            /* Recurse into blocks */
            if (is_array($array[$i])) {
                $this->replace($replacements, $array[$i][1]);
                if (count($array[$i][1]) == 0) {
                    $nextelse = isset($array[$i + 1]) && is_array($array[$i + 1]) && preg_match('/^\\s*else\\s*$/i', $array[$i + 1][0]);
                    $delete = preg_match('/^\\s*else\\s*$/i', $array[$i][0]);
                    $delete = $delete || preg_match('/^\\s*if\\s*\\(/i', $array[$i][0]) && !$nextelse;
                    if ($delete) {
                        // Is this always safe? Not if the expression has side-effects.
                        // print "/* REMOVING EMPTY BLOCK: " . $array[$i][0] . "*/\n" ;
                        array_splice($array, $i, 1);
                        continue;
                    }
                }
            } else {
                if (array_key_exists($array[$i], $replacements)) {
                    $rep = $replacements[$array[$i]];
                    if ($rep === NULL) {
                        array_splice($array, $i, 1);
                        continue;
                    }
                    if (is_string($rep)) {
                        $array[$i] = $rep;
                        $i++;
                        continue;
                    }
                    if ($rep instanceof PHPBuilder) {
                        $rep = $rep->lines;
                    }
                    if (is_array($rep)) {
                        array_splice($array, $i, 1, $rep);
                        $i += count($rep) + 1;
                        continue;
                    }
                    throw new \Exception('Unknown type passed to PHPBuilder#replace');
                }
            }
            $i++;
        }
        return $this;
    }