Exemple #1
0
 /**
  * Compiles file.
  * @param string $file path to phpsafe file.
  * @param bool $checkCache whether method must check hash. If true and cache
  * consits hash for this file it will not recompiled. If false method will
  * always recompile file.
  * @return string compiled file path.
  * @throws InvalidParamException if file does not exists.
  * @throws Exception if cannot create dir.
  */
 public function compileFile($file, $checkCache = true)
 {
     if ($checkCache && false !== ($hash = $this->loadHashFromCache($file))) {
         return $this->getCompiledFilePath($hash);
     }
     if (false === ($realFilePath = realpath($file)) || false === ($sourceContent = @file_get_contents($realFilePath))) {
         throw new InvalidParamException("File '{$file}' was not found.");
     }
     Yii::beginProfile($profileToken = "Compile file {$file}.", __METHOD__);
     $compilerConfig = array_merge($this->compilerConfig, ['compilingFilePath' => $realFilePath]);
     $compiler = Compiler::createFromCode($sourceContent, $compilerConfig);
     $content = $compiler->getCompiledCode();
     Yii::endProfile($profileToken, __METHOD__);
     while (file_exists($compiledFile = $this->getCompiledFilePath($hash = Yii::$app->security->generateRandomString(12)))) {
     }
     if (!FileHelper::createDirectory($dir = dirname($compiledFile), $this->mkDirMode, true)) {
         $mode = '0' . base_convert($this->mkDirMode, 10, 8);
         throw new Exception("Cannot create directory '{$dir}' with {$mode} mode.");
     }
     file_put_contents($compiledFile, $content);
     if ($this->fileMode !== null && !@chmod($compiledFile, $this->fileMode)) {
         $mode = '0' . base_convert($this->fileMode, 10, 8);
         Yii::warning("Cannot change mode to {$mode} for file: {$compiledFile}.", __METHOD__);
     }
     if ($compiler->collectMap && $compiler->getLinesMap()) {
         $mapFile = $this->getMapFilePath($hash);
         file_put_contents($mapFile, '<?php return ' . VarDumper::export(['source' => $realFilePath, 'map' => $compiler->getLinesMap()]) . ';');
         if ($this->fileMode !== null && !@chmod($mapFile, $this->fileMode)) {
             $mode = '0' . base_convert($this->fileMode, 10, 8);
             Yii::warning("Cannot change mode to {$mode} for file: {$mapFile}.", __METHOD__);
         }
     }
     $this->saveHashToCache($file, $hash);
     return $this->getCompiledFilePath($hash);
 }