Mutate compiled File into FileIgnored, FileCopy or FileWrite entities.

@param Project $project
@param Cache $cache
431102
private function mutateFilesToFilesystemInterfaces(Project $project, Cache $cache)
    {
        foreach ($this->files as &$file) {
            /** @var CachedFile $cachedFile */
            if ($cachedFile = $cache->getItem($file->getUid())) {
                if ($cachedFile->check($file)) {
                    $file = new FileIgnored(clone $file, $project->destinationDirectory);
                    continue;
                }
            }

            if ($file->isToCopy()) {
                $file = new FileCopier(clone $file, $project->destinationDirectory);
            } else {
                $file = new FileWriter(clone $file, $project->destinationDirectory);
            }
        }
        unset($file);
    }
136168
protected function writeFile(string $cacheFile, string $contents): bool
    {
        $dir = dirname($cacheFile);

        if ($dir !== $this->cacheDir && !is_dir($dir)) {
            mkdir($dir, 0775, true);
        }

        return (bool)file_put_contents($cacheFile, $contents);
    }
771839
public function writeCacheFile($api, $class, $version, $cacheArray)
    {
        $this->cacheDriver->save($api, $class, $version, $cacheArray);
    }
221329
private function renameFile($source, $target)
    {
        if (false === @rename($source, $target)) {
            throw new RuntimeException(sprintf('Could not write new cache file to %s.', $target));
        }
    }
567384
private function getTree(Project $project)
    {
        $key = $project->getBuildDir();
        if (!isset($this->cachedTree[$key])) {
            $this->cachedTree[$key] = $this->tree->getTree($project);
        }

        return $this->cachedTree[$key];
    }
1040143
public function writeCachedContent(Smarty_Internal_Template $_template, $content)
    {
        $this->addMetaTimestamp($content);

        return $this->write(array($_template->cached->filepath => $content), $_template->cache_lifetime);
    }
1194417
public function compileFile($source, $compiled)
    {
        $source = $this->alias->resolve($source);
        $compiled = $this->alias->resolve($compiled);

        $dir = dirname($compiled);

        /** @noinspection NotOptimalIfConditionsInspection */
        if (!is_dir($dir) && !@mkdir($dir, 0755, true) && !is_dir($dir)) {
            throw new CreateDirectoryFailedException(['create `:dir` directory failed: :last_error_message', 'dir' => $dir]);
        }

        if (($str = file_get_contents($source)) === false) {
            throw new InvalidArgumentException(['read `:file` sword source file failed: :last_error_message', 'file' => $source]);
        }

        $result = $this->compileString($str);

        $result = $this->_replaceAjaxLinks($source, $result);
        $result = $this->_replaceAxiosLinks($source, $result);
        $result = $this->_replaceAttrLinks($source, $result);
        $result = $this->_replaceVueAttrLinks($source, $result);
        $result = $this->_replaceUrlValLinks($source, $result);

        if (file_put_contents($compiled, $result, LOCK_EX) === false) {
            throw new RuntimeException(['write `:compiled` compiled file for `:source` file failed: :last_error_message',
                'complied' => $compiled,
                'source' => $source]);
        }

        return $this;
    }
872705
@SuppressWarnings("unchecked")
	private Map<String, String> loadOrCreateCache(String projectName, String projectVersion) {
		if (projectName != null && projectVersion != null) {
			// Get the project dir or create it
			File projectDir = new File(getCacheDir(), projectName);
			if (!projectDir.exists()) {
				projectDir.mkdir();
			}
			
			// Get the version file or create it
			File versionFile = new File(projectDir, projectVersion);
			if (versionFile.exists()) {
				ObjectInputStream ois = null;
				try {
					ois = new ObjectInputStream(new FileInputStream(versionFile));
					return (Map<String, String>) ois.readObject();
				}
				catch (IOException ioe) {
					LOGGER.warn("Unable to read the cache for {}-{}", projectName, projectVersion);
				}
				catch (ClassNotFoundException cnfe) {
					LOGGER.warn("The cache for {}-{} is corrupted.", projectName, projectVersion);
				}
				finally { if (ois != null) { try { ois.close(); } catch (IOException ioe) {} } }
			}
		}
		
		return new HashMap<>();
	}
1271962
protected void changedCacheData (String cache, final Streamable data)
    {
        // see if we have any observers
        ObserverList<StaleCacheObserver> list = _cacheobs.get(cache);
        if (list == null) {
            return;
        }
        // if so, notify them
        list.apply(new ObserverList.ObserverOp<StaleCacheObserver>() {
            public boolean apply (StaleCacheObserver observer) {
                observer.changedCacheData(data);
                return true;
            }
        });
    }
867134
public function setToCache($key, $value)
    {
        $fileName = $this->getCacheFilePath($key);
        $cacheDirectory = $this->getCacheDir();

        $tmpFile = $cacheDirectory . "/" . basename($fileName) . uniqid('.temp', true) . '.txt';
        file_put_contents($tmpFile, serialize($value), LOCK_EX);

        rename($tmpFile, $fileName);
    }
221822
public function createTemplateCodeFrame($content = '', $cache = false)
    {
        $plugins_string = '';
        // include code for plugins
        if (!$cache) {
            if (!empty($this->required_plugins['compiled'])) {
                $plugins_string = '<?php ';
                foreach ($this->required_plugins['compiled'] as $tmp) {
                    foreach ($tmp as $data) {
                        $file = addslashes($data['file']);
                        $plugins_string .= "if (!is_callable('{$data['function']}')) include '{$file}';\n";
                    }
                }
                $plugins_string .= '?>';
            }
            if (!empty($this->required_plugins['nocache'])) {
                $this->has_nocache_code = true;
                $plugins_string .= "<?php echo '/*%%SmartyNocache:{$this->properties['nocache_hash']}%%*/<?php \$_smarty = \$_smarty_tpl->smarty; ";
                foreach ($this->required_plugins['nocache'] as $tmp) {
                    foreach ($tmp as $data) {
                        $file = addslashes($data['file']);
                        $plugins_string .= addslashes("if (!is_callable('{$data['function']}')) include '{$file}';\n");
                    }
                }
                $plugins_string .= "?>/*/%%SmartyNocache:{$this->properties['nocache_hash']}%%*/';?>\n";
            }
        }
        // build property code
        $this->properties['has_nocache_code'] = $this->has_nocache_code;
        $output = '';
        if (!$this->source->recompiled) {
            $output = "<?php /*%%SmartyHeaderCode:{$this->properties['nocache_hash']}%%*/";
            if ($this->smarty->direct_access_security) {
                $output .= "if(!defined('SMARTY_DIR')) exit('no direct access allowed');\n";
            }
        }
        if ($cache) {
            // remove compiled code of{function} definition
            unset($this->properties['function']);
            if (!empty($this->smarty->template_functions)) {
                // copy code of {function} tags called in nocache mode
                foreach ($this->smarty->template_functions as $name => $function_data) {
                    if (isset($function_data['called_nocache'])) {
                        foreach ($function_data['called_functions'] as $func_name) {
                            $this->smarty->template_functions[$func_name]['called_nocache'] = true;
                        }
                    }
                }
                 foreach ($this->smarty->template_functions as $name => $function_data) {
                    if (isset($function_data['called_nocache'])) {
                        unset($function_data['called_nocache'], $function_data['called_functions'], $this->smarty->template_functions[$name]['called_nocache']);
                        $this->properties['function'][$name] = $function_data;
                    }
                }
            }
        }
        $this->properties['version'] = Smarty::SMARTY_VERSION;
        if (!isset($this->properties['unifunc'])) {
            $this->properties['unifunc'] = 'content_' . uniqid('', false);
        }
        if (!$this->source->recompiled) {
            $output .= "\$_valid = \$_smarty_tpl->decodeProperties(" . var_export($this->properties, true) . ',' . ($cache ? 'true' : 'false') . "); /*/%%SmartyHeaderCode%%*/?>\n";
        }
        if (!$this->source->recompiled) {
            $output .= '<?php if ($_valid && !is_callable(\'' . $this->properties['unifunc'] . '\')) {function ' . $this->properties['unifunc'] . '($_smarty_tpl) {?>';
        }
        $output .= $plugins_string;
        $output .= $content;
        if (!$this->source->recompiled) {
            $output .= '<?php }} ?>';
        }
        return $output;
    }
104564
public function evaluateDependency($cache): void
    {
        foreach ($this->dependencies as $dependency) {
            $dependency->evaluateDependency($cache);
        }
    }
1125577
protected function writeCacheFile($file, $content)
    {
        $dir = dirname($file);

        if (!is_dir($dir)) {
            if (false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
                throw new RuntimeException("Unable to create the cache directory ($dir).");
            }
        } elseif (!is_writable($dir)) {
            throw new RuntimeException("Unable to write in the cache directory ($dir).");
        }

        if (!file_put_contents($file, $content)) {
            throw new RuntimeException("Failed to write cache file ($file).");
        }
    }
843155
public static function unserialize(Project $project, $buildTimestamp = null, $statusDir = null)
    {
        if ($statusDir == null) {
            $statusDir = Xinc::getInstance()->getStatusDir();
        }

        if ($buildTimestamp == null) {
            //$fileName = $statusDir . DIRECTORY_SEPARATOR . $project->getName()
            //          . DIRECTORY_SEPARATOR . 'build.ser';
            $fileName = Xinc_Build_History::getLastBuildFile($project);
        } else {
            //$subDirectory = self::generateStatusSubDir($project->getName(), $buildTimestamp);

            // throws Xinc_Build_Exception_NotFound
            $fileName = Xinc_Build_History::getBuildFile($project, $buildTimestamp);
        }

        //Xinc_Build_Repository::getBuild($project, $buildTimestamp);
        if (!file_exists($fileName)) {
            throw new Xinc_Build_Exception_NotFound($project,
                                                    $buildTimestamp);
        } else {
            $serializedString = file_get_contents($fileName);
            $unserialized = @unserialize($serializedString);
            if (!$unserialized instanceof Xinc_Build) {
                throw new Xinc_Build_Exception_Unserialization($project,
                                                               $buildTimestamp);
            } else {
                /*
                 * compatibility with old Xinc_Build w/o statistics object
                 */
                if ($unserialized->getStatistics() === null) {
                    $unserialized->_statistics = new Xinc_Build_Statistics();
                }
                if ($unserialized->getConfigDirective('timezone.reporting') == true) {
                    $unserialized->setConfigDirective('timezone', null);
                }
                if (!isset($unserialized->_internalProperties)) {
                    if (method_exists($unserialized, 'init')) {
                        $unserialized->init();
                    }
                }

                return $unserialized;
            }
        }
    }
159085
public function writeToCache(FileStorage $storage, $file_contents)
    {
        $file_path = strtolower($storage->file_path);
        $cache_location = $this->getCacheLocationForPath($file_path, true);
        $storage->hash = $this->getCacheHash($file_path, $file_contents);

        if ($this->config->use_igbinary) {
            file_put_contents($cache_location, igbinary_serialize($storage));
        } else {
            file_put_contents($cache_location, serialize($storage));
        }
    }
593961
private function write()
    {
        $project = $this->getProject();

        if (!touch($this->file->getPath())) {
            throw new BuildException("Unable to write to " . $this->file->getPath() . ".");
        }

        $this->log("Writing to " . $this->file->__toString(), Project::MSG_INFO);

        if (is_array($this->checksum)) {
            $this->log("Using " . implode(', ', $this->checksum) . " for checksuming.", Project::MSG_INFO);
        }

        foreach ($this->filesets as $fs) {
            $dir = $fs->getDir($this->project)->getPath();

            $ds = $fs->getDirectoryScanner($project);
            $fromDir = $fs->getDir($project);
            $srcFiles = $ds->getIncludedFiles();
            $srcDirs = $ds->getIncludedDirectories();

            foreach ($ds->getIncludedFiles() as $file_path) {
                $line = $file_path;
                if ($this->checksum) {
                    foreach ($this->checksum as $algo) {
                        if (!$hash = $this->hashFile($dir . '/' . $file_path, $algo)) {
                            throw new BuildException("Hashing $dir/$file_path with $algo failed!");
                        }

                        $line .= "\t" . $hash;
                    }
                }
                $line .= "\n";
                $manifest[] = $line;
                $this->log("Adding file " . $file_path, Project::MSG_VERBOSE);
                $this->meta['totalFileCount']++;
                $this->meta['totalFileSize'] += filesize($dir . '/' . $file_path);
            }
        }

        file_put_contents($this->file, $manifest);

        $this->log(
            "Done. Total files: " . $this->meta['totalFileCount'] . ". Total file size: " . $this->meta['totalFileSize'] . " bytes.",
            Project::MSG_INFO
        );
    }
656760
public function process($file, $cache_time = null, $cache_id = null, $compile_id = null, $data = '_root', $assign = null, array $rest = array())
    {
        $include = null;
        if ($file === '') {
            return '';
        }

        if (preg_match('#^([a-z]{2,}):(.*)$#i', $file, $m)) {
            // resource:identifier given, extract them
            $resource   = $m[1];
            $identifier = $m[2];
        } else {
            // get the current template's resource
            $resource   = $this->core->getTemplate()->getResourceName();
            $identifier = $file;
        }

        try {
            $include = $this->core->templateFactory($resource, $identifier, $cache_time, $cache_id, $compile_id);
        }
        catch (SecurityException $e) {
            $this->core->triggerError('Include : Security restriction : ' . $e->getMessage(), E_USER_WARNING);
        }
        catch (Exception $e) {
            $this->core->triggerError('Include : ' . $e->getMessage(), E_USER_WARNING);
        }

        if ($include === null) {
            $this->core->triggerError('Include : Resource "' . $resource . ':' . $identifier . '" not found.',
                E_USER_WARNING);
        } elseif ($include === false) {
            $this->core->triggerError('Include : Resource "' . $resource . '" does not support includes.',
                E_USER_WARNING);
        }

        if (is_string($data)) {
            $vars = $this->core->readVar($data);
        } else {
            $vars = $data;
        }

        if (count($rest)) {
            $vars = $rest + $vars;
        }

        $clone = clone $this->core;
        $out   = $clone->get($include, $vars);

        if ($assign !== null) {
            $this->core->assignInScope($out, $assign);
        }

        foreach ($clone->getReturnValues() as $name => $value) {
            $this->core->assignInScope($value, $name);
        }

        if ($assign === null) {
            return $out;
        }
    }