Setting a value to an array in a given path

Inspired by \TYPO3\CMS\Core\Utility\ArrayUtility

@param array $array
@param string $configPath Path separated by "."
@param mixed $value
@throws InvalidArgumentException
@return array
349767
public static function setValue(array $array, string $configPath, $value): array
    {
        if (!is_string($configPath) || $configPath === '') {
            throw new InvalidArgumentException('Path must be not be empty string', 1496472912);
        }
        // Extract parts of the configPath
        $path = str_getcsv($configPath, '.');
        // Point to the root of the array
        $pointer = &$array;
        // Find configPath in given array
        foreach ($path as $segment) {
            // Fail if the part is empty
            if ($segment === '') {
                throw new InvalidArgumentException('Invalid path segment specified', 1496472917);
            }
            // Create cell if it doesn't exist
            if (!array_key_exists($segment, $pointer)) {
                $pointer[$segment] = [];
            }
            // Set pointer to new cell
            $pointer = &$pointer[$segment];
        }
        // Set value of target cell
        $pointer = $value;

        return $array;
    }
50320
public function set(string $path, array &$row, string $value = null): void
    {
        if (!array_key_exists($this->colName, $row) || (null === $row[$this->colName])) {
            $row[$this->colName] = $this->encode([]);
        }
        $content = $this->decode($row[$this->colName]);
        $chunks  = explode('.', $path);

        if (null === ($extractor = $this->extractors[$chunks[0]] ?? null)) {
            throw new \InvalidArgumentException('Sub extractor ' . $chunks[0] . ' not found');
        }

        switch (true) {
            case $extractor instanceof MultiStringExtractorInterface:
                $extractor->set(substr($path, (\strlen($chunks[0]) + 1)), $content, $value);
                break;
            case $extractor instanceof StringExtractorInterface:
                if (strlen($path) > strlen($chunks[0])) {
                    throw new \InvalidArgumentException('String extractor may not contain sub extractor: "'
                        . substr($path, (strlen($chunks[0]) + 1)) . '"');
                }
                $extractor->set($content, $value);
                break;
            default:
        }

        $row[$this->colName] = $this->encode($content);
    }
789743
protected function prepareArrayValue(array $value)
    {
        $rii = new \RecursiveIteratorIterator(
            new \RecursiveArrayIterator($value),
            \RecursiveIteratorIterator::SELF_FIRST
        );
        foreach ($rii as $key => $value) {
            if (($value instanceof ValueGenerator) === false) {
                $value = new self($value);
                $rii->getSubIterator()->offsetSet($key, $value);
            }

            $value->setIndentationLevel($value->getIndentationLevel() + $rii->getDepth());
        }

        return $rii->getSubIterator()->getArrayCopy();
    }
1178492
public static function dotSet(array $array, $key, $value)
    {
        $path = explode('.', $key);
        $total = count($path);

        $current = &$array;

        for ($ii = 0; $ii < $total; $ii++) {
            if ($ii === $total - 1) {
                $current[$path[$ii]] = $value;
            } else {
                if (!is_array($current)) {
                    throw new LackOfCoffeeException(
                        'Part of the path is not an array.'
                    );
                }

                if (!array_key_exists($path[$ii], $current)) {
                    $current[$path[$ii]] = [];
                }

                $current = &$current[$path[$ii]];
            }
        }
    }
548282
public static function set(array &$array, string $path, $value): void
    {
        $paths = explode('.', $path);
        $temp = &$array;
        while ($key = array_shift($paths)) {
            $temp = &$temp[$key];
        }
        $temp = $value;
    }
1232523
private function assertArray($key, $value)
    {
        if (!is_array($value)) {
            throw new InvalidConfigException(sprintf(
                'The config key "%s" must be an array. Got: %s',
                $key,
                is_object($value) ? get_class($value) : gettype($value)
            ));
        }
    }
136431
public function offsetSet($offset, $value): void
    {
        if (null === $offset) {
            throw new \InvalidArgumentException('Class `Common\Container\ArrayAccess` support only associative arrays');
        }
        $this->doSetContainer($offset, $value);
    }
156347
public static function set(&$array, $key, $value = null)
    {
        if (is_null($key)) {
            $array = $value;
            return;
        }
        if (is_array($key)) {
            foreach ($key as $k => $v) {
                static::set($array, $k, $v);
            }
        } else {
            $keys = explode('.', $key);
            while (count($keys) > 1) {
                $key = array_shift($keys);
                if (!isset($array[$key]) or !is_array($array[$key])) {
                    $array[$key] = [];
                }
                $array =& $array[$key];
            }
            $array[array_shift($keys)] = $value;
        }
    }
376087
public static function init($configPath = null)
    {
        if (!$configPath) {
            return new self();
        }
        if (!isset(self::$instances[$configPath])) {
            if (!file_exists($configPath) || !is_readable($configPath)) {
                throw new \InvalidArgumentException("Invalid config path '$configPath'");
            }
            self::$instances[$configPath] = new static(parse_ini_file($configPath, true));
        }

        return self::$instances[$configPath];
    }
29633
public static function getValueByPath(array $array, string $path, string $delimiter = '/')
    {
        $path = trim($path, $delimiter);
        $keys = $path ? explode($delimiter, $path) : [];
        $value = $array;
        foreach ($keys as $key) {
            $value = $value[$key];
        }

        return $value;
    }
1201055
public function set($path, $value)
    {
        $p = explode('.', $path);
        $cfg = &$this->config;
        $count = 1;

        foreach ($p as $part) {
            if ($count == count($p)) {
                $cfg[$part] = $value;
                continue;
            }
            if (array_key_exists($part, $cfg)) {
                $cfg = &$cfg[$part];
            } else {
                // create the path
                $cfg[$part] = array();
                $cfg = &$cfg[$part];
            }
            $count++;
        }
    }
639432
private function normalizePath(array $path)
    {
        // If the path is associative (i.e. not nested), wrap it up.
        if ($this->isAssoc($path)) {
            $path = [$path];
        }

        $res = [];
        foreach ($path as $index => $pathElement) {
            if (!isset($pathElement['kind'])) {
                throw new InvalidArgumentException('Each path element must contain a kind.');
            }

            $incomplete = (!isset($pathElement['id']) && !isset($pathElement['name']));
            if ($index < count($path) -1 && $incomplete) {
                throw new InvalidArgumentException(
                    'Only the final pathElement may omit a name or ID.'
                );
            }

            if (isset($pathElement['id']) && !is_string($pathElement['id'])) {
                $pathElement['id'] = (string) $pathElement['id'];
            }

            $res[] = $pathElement;
        }

        return $res;
    }
151400
public static function isArray($value, $message = null)
    {
        if (!is_array($value)) {
            throw new InvalidArgumentException(sprintf(
                $message ?: 'Expected array, but got %s',
                Helper::typeToString($value)
            ));
        }
    }
200688
public function setValue($value)
    {
        if ('checkbox' === $this->type && false === $value) {
            // uncheck
            $this->value = null;
        } elseif ('checkbox' === $this->type && true === $value) {
            // check
            $this->value = $this->options[0]['value'];
        } else {
            if (is_array($value)) {
                if (!$this->multiple) {
                    throw new \InvalidArgumentException(sprintf('The value for "%s" cannot be an array.', $this->name));
                }

                foreach ($value as $v) {
                    if (!$this->containsOption($v, $this->options)) {
                        throw new \InvalidArgumentException(sprintf('Input "%s" cannot take "%s" as a value (possible values: %s).', $this->name, $v, implode(', ', $this->availableOptionValues())));
                    }
                }
            } elseif (!$this->containsOption($value, $this->options)) {
                throw new \InvalidArgumentException(sprintf('Input "%s" cannot take "%s" as a value (possible values: %s).', $this->name, $value, implode(', ', $this->availableOptionValues())));
            }

            if ($this->multiple) {
                $value = (array) $value;
            }

            if (is_array($value)) {
                $this->value = $value;
            } else {
                parent::setValue($value);
            }
        }
    }
796296
public function set(string $path, array &$row, string $value = null): void
    {
        if (!$this->supports($row)) {
            return;
        }
        if (!array_key_exists($this->colName, $row)) {
            $row[$this->colName] = [];
        }

        $content = &$row[$this->colName];
        $chunks  = explode('.', $path);
        if (!array_key_exists($chunks[0], $content)) {
            $content[$chunks[0]] = [];
        }
        $content = &$content[$chunks[0]];

        if (null === ($extractor = $this->extractors[$chunks[1]] ?? null)) {
            throw new \InvalidArgumentException('Sub extractor ' . $chunks[1] . ' not found');
        }

        switch (true) {
            case $extractor instanceof MultiStringExtractorInterface:
                $extractor->set(implode('.', \array_slice($chunks, 2)), $content, $value);
                return;
            case $extractor instanceof StringExtractorInterface:
                $extractor->set($content, $value);
                return;
            default:
        }

        throw new \InvalidArgumentException('Unknown extractor type ' . \get_class($extractor));
    }
378934
protected function setPropertyByPath($path, $value)
    {
        $path = explode('.', $path);
        $root = $path[0];
        unset($path[0]);

        $array = ($this->hasProperty($root) ? $this->getProperty($root) : []);
        $pointer = &$array;

        // Loop through the array path and set array parts
        foreach ($path as $part) {
            if (!isset($pointer[$part])) {
                $pointer[$part] = [];
            }

            if (!is_array($pointer[$part])) {
                $pointer[$part] = [];
            }

            $pointer = &$pointer[$part];
        }

        $pointer = $value;
        unset($pointer);

        $this->setProperty($root, $array);
    }
471607
private function resolvePath(array $value, string $path)
    {
        $path = preg_replace('/\[(.*?)\]/', '.$1', $path);
        $path = explode('.', $path);

        foreach ($path as $item) {
            if (is_array($value) && isset($value[$item])) {
                $value = $value[$item];
            } else {
                return null;
            }
        }

        return $value;
    }