1<?php
2
3/*
4 * This file is part of the Assetic package, an OpenSky project.
5 *
6 * (c) 2010-2014 OpenSky Project Inc
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Assetic\Filter;
13
14use Assetic\Asset\AssetInterface;
15use Assetic\Util\FilesystemUtils;
16
17/**
18 * Runs assets through Packager.
19 *
20 * @link https://github.com/kamicane/packager
21 * @author Kris Wallsmith <kris.wallsmith@gmail.com>
22 */
23class PackagerFilter implements FilterInterface
24{
25    private $packages;
26
27    public function __construct(array $packages = array())
28    {
29        $this->packages = $packages;
30    }
31
32    public function addPackage($package)
33    {
34        $this->packages[] = $package;
35    }
36
37    public function filterLoad(AssetInterface $asset)
38    {
39        static $manifest = <<<EOF
40name: Application%s
41sources: [source.js]
42
43EOF;
44
45        $hash = substr(sha1(time().rand(11111, 99999)), 0, 7);
46        $package = FilesystemUtils::getTemporaryDirectory().'/assetic_packager_'.$hash;
47
48        mkdir($package);
49        file_put_contents($package.'/package.yml', sprintf($manifest, $hash));
50        file_put_contents($package.'/source.js', $asset->getContent());
51
52        $packager = new \Packager(array_merge(array($package), $this->packages));
53        $content = $packager->build(array(), array(), array('Application'.$hash));
54
55        unlink($package.'/package.yml');
56        unlink($package.'/source.js');
57        rmdir($package);
58
59        $asset->setContent($content);
60    }
61
62    public function filterDump(AssetInterface $asset)
63    {
64    }
65}
66