<?php
namespace Helpers\Outil;

class ObjectHelper
{

    /**
     *
     * @param \stdClass|object $obj
     * @param string|array<string> $path String dot separated (TODO : handle array access ? '[]')
     * @param array{coalesce?:mixed} $option
     * @return mixed
     */
    public static function pathAccess(object $obj, $path, array $option = [])
    {
        if (!is_array($path)) {
            $path = explode('.', $path);
        }
        $tmp = $obj;
        foreach ($path as $field) {
            if (is_object($tmp)) {
                if (property_exists($tmp, $field)) {
                    $tmp = $tmp->{$field};
                    continue;
                }
                if (method_exists($tmp, $field)) {
                    $tmp = $tmp->{$field}();
                    continue;
                }
            }
            if (array_key_exists('coalesce', $option)) {
                return $option['coalesce'];
            }
            throw new \Exception('Invalid path "'.var_export($path, true).'" on "'.$field.'"');
        }
        return $tmp;
    }
}
