<?php

namespace AppBundle\Twig;

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

    /**
     * 
     * @param string $appDir Kernel root dir
     */
    public function __construct(string $appDir)
    {
        $this->appDir = $appDir;
    }

    public function getFilters(): array
    {
        return array(
            new \Twig_SimpleFilter('asset_rev', array($this, 'getAssetRev')),
        );
    }

    /**
     * Get the versioned name of the given asset filename
     *
     * @param  string $filename filename without revision name
     *
     * @return string           filename with revision name
     * @throws \Exception
     */
    public function getAssetRev(string $filename): string
    {
        $manifestPath = $this->appDir.'/Resources/assets/rev-manifest.json';
        if (!file_exists($manifestPath)) {
            throw new \Exception(sprintf('Cannot find manifest file: "%s"', $manifestPath));
        }

        $paths = json_decode(file_get_contents($manifestPath), true);

        $filenameManifest = 'web/' . $filename;

        if (!isset($paths[$filenameManifest])) {
            throw new \Exception(sprintf('There is no file "%s" in the version manifest!', $filename));
        }
        return substr($paths[$filenameManifest]['path'], strpos($paths[$filenameManifest]['path'], '/') + 1);
    }
}
