Kahlan\Jit\Patcher\Monkey::_monkeyPatch PHP Method

_monkeyPatch() protected method

Monkey patch a node body.
protected _monkeyPatch ( object $node, array $parent, integer $index )
$node object The node to monkey patch.
$parent array The parent array.
$index integer The index of node in parent children.
    protected function _monkeyPatch($node, $parent, $index)
    {
        if (!preg_match_all($this->_regex, $node->body, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
            return;
        }
        $offset = 0;
        foreach (array_reverse($matches) as $match) {
            $len = strlen($match[0][0]);
            $pos = $match[0][1];
            $name = $match[3][0];
            $nextChar = $node->body[$pos + $len];
            $isInstance = !!$match[1][0];
            $isClass = $nextChar === ':' || $isInstance;
            if (!isset(static::$_blacklist[strtolower($name)]) && ($isClass || $nextChar === '(')) {
                $tokens = explode('\\', $name, 2);
                if ($name[0] === '\\') {
                    $name = substr($name, 1);
                    $args = "null , '{$name}'";
                } elseif (isset($this->_uses[$tokens[0]])) {
                    $ns = $this->_uses[$tokens[0]];
                    if (count($tokens) === 2) {
                        $ns .= '\\' . $tokens[1];
                    }
                    $args = "null, '" . $ns . "'";
                } else {
                    $args = "__NAMESPACE__ , '{$name}'";
                }
                if (!isset($this->_variables[$this->_depth][$name])) {
                    $variable = '$__' . $this->_prefix . '__' . $this->_counter++;
                    if ($isClass) {
                        $args .= ', false, ' . $variable . '__';
                    }
                    $this->_variables[$this->_depth][$name] = ['name' => $variable, 'isClass' => $isClass, 'patch' => "=\\Kahlan\\Plugin\\Monkey::patched({$args});"];
                } else {
                    $variable = $this->_variables[$this->_depth][$name]['name'];
                }
                $substitute = $variable . '__';
                if (!$isInstance) {
                    $replace = $match[2][0] . $variable . $match[4][0];
                } else {
                    $added = $this->_addClosingParenthesis($pos + $len, $index, $parent);
                    if ($added) {
                        $replace = '(' . $substitute . '?' . $substitute . ':' . $match[1][0] . $match[2][0] . $variable . $match[4][0];
                    } else {
                        $replace = $match[1][0] . $match[2][0] . $variable . $match[4][0];
                    }
                }
                $node->body = substr_replace($node->body, $replace, $pos, $len);
                $offset = $pos + strlen($replace);
            } else {
                $offset = $pos + $len;
            }
        }
    }