API::createItems PHP Method

createItems() protected method

Add an object to GLPI
protected createItems ( $itemtype, $params = [] ) : array
$itemtype string itemtype (class) of object
$params array with theses options : - 'input' : object with fields of itemtype to be inserted. You can add several items in one action by passing array of input object. Mandatory.
return array of id
    protected function createItems($itemtype, $params = array())
    {
        $this->initEndpoint();
        $input = isset($params['input']) ? $params["input"] : null;
        $item = new $itemtype();
        $response = "";
        if (is_object($input)) {
            $input = array($input);
            $isMultiple = false;
        } else {
            $isMultiple = true;
        }
        if (is_array($input)) {
            $idCollection = array();
            $failed = 0;
            foreach ($input as $object) {
                $object = self::inputObjectToArray($object);
                //check rights
                if (!$item->can(-1, CREATE, $object)) {
                    $failed++;
                    $idCollection[] = array('id' => false, 'message' => __("You don't have permission to perform this action."));
                } else {
                    // add missing entity
                    if (!isset($object['entities_id'])) {
                        $object['entities_id'] = $_SESSION['glpiactive_entity'];
                    }
                    //add current item
                    $object = Toolbox::sanitize($object);
                    $new_id = $item->add($object);
                    if ($new_id === false) {
                        $failed++;
                    }
                    $idCollection[] = array('id' => $new_id, 'message' => $this->getGlpiLastMessage());
                }
            }
            if ($isMultiple) {
                if ($failed == count($input)) {
                    $this->returnError($idCollection, 400, "ERROR_GLPI_ADD", false);
                } else {
                    if ($failed > 0) {
                        $this->returnError($idCollection, 207, "ERROR_GLPI_PARTIAL_ADD", false);
                    }
                }
            } else {
                if ($failed > 0) {
                    $this->returnError($idCollection[0]['message'], 400, "ERROR_GLPI_ADD", false);
                } else {
                    return $idCollection[0];
                }
            }
            return $idCollection;
        } else {
            $this->messageBadArrayError();
        }
    }