public function endArrayNode(ArrayNode $node) { $nested = $this->nodeData[$node]; unset($this->nodeData[$node]); if ($nested) { $this->indentLevel--; } $is_wrapped = $node->getElementList()->children(Filter::isNewline())->isNotEmpty(); if ($is_wrapped) { // Enforce trailing comma after last element. $node->getElementList()->append(Token::comma()); // Newline before closing ) or ]. $this->newlineBefore($node->lastChild(), !$nested); } }
private function updateArray(ArrayNode $node, $data) { $i = 0; foreach ($node->getElements() as $el) { if ($el instanceof ArrayPairNode) { $k = (string) $el->getKey(); $k = trim($k, '"\''); $v = $el->getValue(); if (!isset($data[$k])) { $this->cleanAround($el); } else { if ($v instanceof ArrayNode && is_array($data[$k])) { $v = $this->updateArray($v, $data[$k]); unset($data[$k]); } else { $v->replaceWith(Parser::parseExpression($data[$k])); unset($data[$k]); } } } elseif ($el instanceof ArrayNode && (!isset($data[$i]) || is_array($data[$i]))) { if (!isset($data[$i])) { $this->cleanAround($el); } else { $this->updateArray($el, $data[$i]); unset($data[$i]); $i++; } } else { if (!isset($data[$i])) { $this->cleanAround($el); } else { $el->replaceWith(Parser::parseExpression($data[$i])); unset($data[$i]); $i++; } } } foreach ($data as $key => $val) { $v = Parser::parseExpression(self::var_codify($val)); if (!is_integer($key)) { $v = ArrayPairNode::create(Node::fromValue($key), $v); } $comma = false; $list = $node->getElementList(); $children = []; foreach ($list->children() as $child) { $children[] = $child; } $prev = end($children); if ($prev) { do { if ((string) $prev === ',') { $comma = true; break; } } while (is_object($prev) && ($prev = $prev->previous()) instanceof WhitespaceNode); } else { $comma = true; } $indent = 0; $prev = end($children); while ($prev && strpos($prev, "\n") === false) { $prev = $prev->previous(); } $indent = ''; if ($prev) { $prev = explode("\n", (string) $prev); $prev = array_pop($prev); for ($i = 0; $i < strlen($prev); $i++) { if (in_array($prev[$i], ["\t", ' '])) { $indent .= $prev[$i]; } else { break; } } } if (!$comma) { $list->append(Token::comma()); } $list->append(Token::newline()); if ($indent) { $list->append(WhitespaceNode::create($indent)); } $list->append($v); } }
/** * Insert item before index. * * @param Node $item * @param int $index * @throws \OutOfBoundsException * Index out of bounds. * @return $this */ public function insertItem(Node $item, $index) { $items = $this->getItems(); if ($items->isEmpty()) { if ($index !== 0) { throw new \OutOfBoundsException('index out of bounds'); } $this->append($item); } else { $max_index = count($items) - 1; if ($index < 0 || $index > $max_index) { throw new \OutOfBoundsException('index out of bounds'); } $items[$index]->before([$item, Token::comma(), Token::space()]); } return $this; }