<?php

namespace AppBundle\Twig;

/**
 *
 * @author Bastien Gatellier <contact@bgatellier.fr>
 */
class FileGetContentsExtension extends \Twig_Extension
{
    private $projectDir;

    /**
     * 
     * @param string $projectDir
     */
    public function __construct(string $projectDir)
    {
        $this->projectDir = $projectDir;
    }

    public function getFunctions(): array
    {
        return [
            new \Twig_Function('file_get_contents', [$this, 'fileGetContents'], ['is_safe' => ['html']]),
        ];
    }

    /**
     * Get the file content of the given path, or an empty string if the file does not exist or is unreadable.
     * @param  string $path 
     * @return string
     */
    public function fileGetContents(string $path): string
    {
        // Check if the path is an absolute path,
        // and make it so otherwise.
        if (false === strpos($this->projectDir . '/web', $path)) {
            $path = $this->projectDir . '/web' . $path;
        } elseif (false === strpos($this->projectDir, $path)) {
            $path = $this->projectDir . $path;
        }

        return is_readable($path)
            ? file_get_contents($path)
            : ''
        ;
    }
}
