<?php
namespace Newland\Toubiz\Poi\Neos\Utility;

/*
 * This file is part of the "toubiz-poi-neos" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

class ArrayUtility
{
    /**
     * Get an item from an array using "dot" notation.
     *
     * @param  array $array
     * @param  string $key
     * @param  mixed $default
     * @return mixed
     */
    public static function get(array $array, string $key, $default = null)
    {
        if (array_key_exists($key, $array)) {
            return $array[$key];
        }
        if (strpos($key, '.') === false) {
            return $array[$key] ?? $default;
        }
        foreach (explode('.', $key) as $segment) {
            if (array_key_exists($segment, $array)) {
                $array = $array[$segment];
            } else {
                return $default;
            }
        }

        return $array;
    }

    public static function extractSubKey(array $array, string $subKey): array
    {
        $extracted = [];

        foreach ($array as $key => $value) {
            if (\is_array($value) && !empty($value[$subKey])) {
                $extracted[$key] = $value[$subKey];
            }
        }

        return $extracted;
    }
}
