/** * Adds a component as a child to the component. * * The function also validates the component. * * The function checks multiple things and only adds the component if all requirements are met. * It returns the added component or an error object. * * @since 0.5.0 * @param WPDLib\Components\Base the component to add as a child * @return WPDLib\Components\Base|WPDLib\Util\Error either the added component or an error object */ public function add($component) { if (ComponentManager::is_too_late()) { return new UtilError('too_late_component', sprintf(__('Components must not be added later than the %s hook.', 'wpdlib'), '<code>init</code>'), '', ComponentManager::get_scope()); } if (!is_a($component, 'WPDLib\\Components\\Base')) { return new UtilError('no_component', __('The object is not a component.', 'wpdlib'), '', ComponentManager::get_scope()); } $component_class = get_class($component); $children = ComponentManager::get_children(get_class($this)); if (!in_array($component_class, $children)) { return new UtilError('no_valid_child_component', sprintf(__('The component %1$s of class %2$s is not a valid child for the component %3$s.', 'wpdlib'), $component->slug, get_class($component), $this->slug), '', ComponentManager::get_scope()); } $status = $component->validate($this); if (is_wp_error($status)) { return $status; } if (!$component->is_valid_slug()) { return new UtilError('no_valid_slug_component', sprintf(__('A component of class %1$s with slug %2$s already exists.', 'wpdlib'), get_class($component), $component->slug), '', ComponentManager::get_scope()); } if (!isset($this->children[$component_class])) { $this->children[$component_class] = array(); } $this->children[$component_class] = Util::object_array_insert($this->children[$component_class], $component, 'slug', 'position'); return $component; }