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\Exception\FilterException;
16use Assetic\Util\FilesystemUtils;
17
18/**
19 * Compiles Dart into Javascript.
20 *
21 * @link http://dartlang.org/
22 */
23class DartFilter extends BaseProcessFilter
24{
25    private $dartBin;
26
27    public function __construct($dartBin = '/usr/bin/dart2js')
28    {
29        $this->dartBin = $dartBin;
30    }
31
32    public function filterLoad(AssetInterface $asset)
33    {
34        $input  = FilesystemUtils::createTemporaryFile('dart');
35        $output = FilesystemUtils::createTemporaryFile('dart');
36
37        file_put_contents($input, $asset->getContent());
38
39        $pb = $this->createProcessBuilder()
40            ->add($this->dartBin)
41            ->add('-o'.$output)
42            ->add($input)
43        ;
44
45        $proc = $pb->getProcess();
46        $code = $proc->run();
47        unlink($input);
48
49        if (0 !== $code) {
50            $this->cleanup($output);
51
52            throw FilterException::fromProcess($proc);
53        }
54
55        if (!file_exists($output)) {
56            throw new \RuntimeException('Error creating output file.');
57        }
58
59        $asset->setContent(file_get_contents($output));
60        $this->cleanup($output);
61    }
62
63    public function filterDump(AssetInterface $asset)
64    {
65    }
66
67    private function cleanup($file)
68    {
69        foreach (glob($file.'*') as $related) {
70            unlink($related);
71        }
72    }
73}
74