/** * Create a node * * If parentId is not passed in, append to root node * * @param string $nodeId A unique identifier for the node * @param string|null $parentId Which node the node should be append to * @param mixed $data Arbitrary data * @param int|null $position Position the node should appear in parent's children * * @return Node * @throws DuplicateNodeException When node id is already in use */ public function createNode($nodeId, $parentId = null, $data = null, $position = null) { if ($this->nodeExists($nodeId)) { throw new DuplicateNodeException("ID '{$nodeId}' is already in use. Node ids must be unique."); } // use root node if parent id is not passed in $parent = null === $parentId ? $this->rootNode : $this->nodeCollection->find($parentId); // create a new node setting position and data $node = new Node($nodeId, $parent); $node->setPosition($position); $node->setData($data); // add node to parent and collection $parent->addChild($node); $this->nodeCollection->add($node); return $node; }