Example #1
0
 /**
  * Prepend or append to self/child.
  *
  * @param Element $child
  * @param string  $name
  * @param null    $subject
  * @param null    $position
  * @param boolean $before
  *
  * @return $this
  */
 protected function insertChildAtPosition($child, $name = null, $subject = null, $position = null, $before = false)
 {
     // Get default child name
     $subject = $subject ?: $this;
     $name = $name ?: count($this->children);
     // Bind parent to child
     if ($child instanceof TreeObject) {
         $child->setParent($subject);
     }
     // Add object to children
     $child->parentIndex = $name;
     // If the position is a child name, get its index
     $before = $before ? 0 : 1;
     $position = is_null($position) ? count($subject->children) : $position;
     if (is_string($position)) {
         $position = array_search($position, array_keys($subject->children));
     }
     if (is_string($name) && isset($subject->children[$name])) {
         $subject->children[$name] = $child;
         return $this;
     }
     // Slice and recompose children
     $subject->children = array_slice($subject->children, 0, $position + $before, true) + array($name => $child) + array_slice($subject->children, $position, count($subject->children), true);
     return $this;
 }