phabel/src/Context.php

91 lines
2.0 KiB
PHP
Raw Normal View History

2020-08-03 21:31:32 +02:00
<?php
namespace Phabel;
2020-08-14 20:40:01 +02:00
use PhpParser\Node;
2020-08-30 20:27:43 +02:00
use PhpParser\Node\Expr\Isset_;
2020-08-14 14:43:29 +02:00
use SplStack;
2020-08-13 18:30:12 +02:00
/**
* @author Daniil Gentili <daniil@daniil.it>
2020-08-14 14:43:29 +02:00
* @license MIT
2020-08-13 18:30:12 +02:00
*/
2020-08-03 21:31:32 +02:00
class Context
{
2020-08-14 14:43:29 +02:00
/**
2020-08-14 20:40:01 +02:00
* Parent nodes stack.
*
2020-08-14 14:43:29 +02:00
* @var SplStack<Node>
*/
public SplStack $parents;
2020-08-30 20:27:43 +02:00
/**
* Whether we're inside an isset expression
*/
public bool $insideIsset = false;
/**
* Constructor
*/
2020-08-14 14:43:29 +02:00
public function __construct()
{
$this->parents = new SplStack;
}
2020-08-30 20:27:43 +02:00
/**
* Push node
*
* @param Node $node Node
*
* @return void
*/
public function push(Node $node): void
{
$this->parents->push($node);
if ($node instanceof Isset_) {
$this->insideIsset = true;
}
}
/**
* Pop node
*
* @return void
*/
public function pop(): void
{
if ($this->parents->pop() instanceof Isset_) {
$this->insideIsset = false;
}
}
2020-08-14 20:40:01 +02:00
/**
* Insert nodes before node.
*
* @param Node $node
* @param Node ...$nodes
* @return void
*/
public function insertBefore(Node $node, Node ...$nodes): void
{
2020-08-23 20:54:56 +02:00
if (empty($nodes)) {
return;
}
2020-08-14 20:40:01 +02:00
$subNode = $node->getAttribute('currentNode');
$subNodeIndex = $node->getAttribute('currentNodeIndex');
\array_splice($node->{$subNode}, $subNodeIndex, 0, $nodes);
2020-08-23 20:54:56 +02:00
$skips = $node->getAttribute('skipNodes', []);
$skips []= $subNodeIndex+\count($nodes);
$node->setAttribute('skipNodes', $skips);
$node->setAttribute('currentNodeIndex', $subNodeIndex - 1);
2020-08-14 20:40:01 +02:00
}
/**
* Insert nodes after node.
*
* @param Node $node
* @param Node ...$nodes
* @return void
*/
public function insertAfter(Node $node, Node ...$nodes): void
{
$subNode = $node->getAttribute('currentNode');
$subNodeIndex = $node->getAttribute('currentNodeIndex');
\array_splice($node->{$subNode}, $subNodeIndex+1, 0, $nodes);
}
2020-08-09 13:49:19 +02:00
}