<?php

namespace Hecate;


class Lodash {
	/**
	 * @param mixed[] $array
	 */
	static function get( &$array, $parents, $default = null, $glue = '.' ) {
		if ( ! $array || ! is_array( $array ) ) {
			return $default;
		}

		if ( ! is_array( $parents ) ) {
			$parents = explode( $glue, $parents );
		}

		$ref = &$array;

		foreach ( (array) $parents as $parent ) {
			if ( is_array( $ref ) && array_key_exists( $parent, $ref ) ) {
				$ref = &$ref[ $parent ];
				// walk inside object
			} elseif ( is_object( $ref ) && property_exists( $ref, $parent ) ) {
				$ref = &$ref->$parent;
			} else {
				return $default;
			}
		}

		return $ref;
	}

	/**
	 * @param mixed[] $array
	 */
	static function set( &$array, $parents, $value, $glue = '.' ) {
		if ( ! is_array( $parents ) ) {
			$parents = explode( $glue, (string) $parents );
		}

		$ref = &$array;

		foreach ( $parents as $parent ) {
			if ( isset( $ref ) && ! is_array( $ref ) ) {
				$ref = array();
			}

			$ref = &$ref[ $parent ];
		}

		$ref = $value;
	}

	static function unsetValue( &$array, $parents, $glue = '.' ) {
		if ( ! is_array( $parents ) ) {
			$parents = explode( $glue, $parents );
		}

		$key = array_shift( $parents );

		if ( empty( $parents ) ) {
			unset( $array[ $key ] );
		} else {
			self::unsetValue( $array[ $key ], $parents );
		}
	}

	static function compact( $array ) {
		return \array_values( \array_filter( $array ? $array : array() ) );
	}
	static function merge( ...$values ) {
		$not_null_values = static::compact( $values );
		if ( count( $not_null_values ) > 0 ) {
			return array_replace_recursive( ...$not_null_values );
		}
		return array();
	}
    static function keyBy($array, $property) {
        $result   = [];

        foreach ( $array as $element ) {
            $propertyValue = Lodash::get($element, $property, null);
            if($propertyValue === null) {
                continue;
            }
            $result[$propertyValue] = $element;
        }
        return $result;
    }
}
