<?php

namespace WPD\WordPress;

final class PathGuard
{
    private $allowedRoot;

    public function __construct($allowedRoot)
    {
        $real = realpath($allowedRoot);
        if ($real === false || !is_dir($real)) {
            throw new \InvalidArgumentException('La raíz permitida no es válida.');
        }
        $this->allowedRoot = rtrim($real, '/\\');
    }

    public function allowedRoot()
    {
        return $this->allowedRoot;
    }

    public function resolveDirectory($path)
    {
        $real = realpath((string) $path);
        if ($real === false || !is_dir($real) || !$this->contains($real)) {
            return null;
        }
        return rtrim($real, '/\\');
    }

    public function safeFile($path)
    {
        if (is_link($path)) {
            return null;
        }
        $real = realpath($path);
        if ($real === false || !is_file($real) || !$this->contains($real)) {
            return null;
        }
        return $real;
    }

    public function contains($path)
    {
        $path = rtrim((string) $path, '/\\');
        return $path === $this->allowedRoot || strpos($path . DIRECTORY_SEPARATOR, $this->allowedRoot . DIRECTORY_SEPARATOR) === 0;
    }
}

