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 TypeScript into JavaScript. 20 * 21 * @link http://www.typescriptlang.org/ 22 * @author Jarrod Nettles <jarrod.nettles@icloud.com> 23 */ 24class TypeScriptFilter extends BaseNodeFilter 25{ 26 private $tscBin; 27 private $nodeBin; 28 29 public function __construct($tscBin = '/usr/bin/tsc', $nodeBin = null) 30 { 31 $this->tscBin = $tscBin; 32 $this->nodeBin = $nodeBin; 33 } 34 35 public function filterLoad(AssetInterface $asset) 36 { 37 $pb = $this->createProcessBuilder($this->nodeBin 38 ? array($this->nodeBin, $this->tscBin) 39 : array($this->tscBin)); 40 41 if ($sourcePath = $asset->getSourcePath()) { 42 $templateName = basename($sourcePath); 43 } else { 44 $templateName = 'asset'; 45 } 46 47 $inputDirPath = FilesystemUtils::createThrowAwayDirectory('typescript_in'); 48 $inputPath = $inputDirPath.DIRECTORY_SEPARATOR.$templateName.'.ts'; 49 $outputPath = FilesystemUtils::createTemporaryFile('typescript_out'); 50 51 file_put_contents($inputPath, $asset->getContent()); 52 53 $pb->add($inputPath)->add('--out')->add($outputPath); 54 55 $proc = $pb->getProcess(); 56 $code = $proc->run(); 57 unlink($inputPath); 58 rmdir($inputDirPath); 59 60 if (0 !== $code) { 61 if (file_exists($outputPath)) { 62 unlink($outputPath); 63 } 64 throw FilterException::fromProcess($proc)->setInput($asset->getContent()); 65 } 66 67 if (!file_exists($outputPath)) { 68 throw new \RuntimeException('Error creating output file.'); 69 } 70 71 $compiledJs = file_get_contents($outputPath); 72 unlink($outputPath); 73 74 $asset->setContent($compiledJs); 75 } 76 77 public function filterDump(AssetInterface $asset) 78 { 79 } 80} 81