@param FileSystemInterface $fileSystem
@param TemplateOutput[]    $templateOutputs

@return void

@SuppressWarnings(PHPMD.ElseExpression)
332815
private function createTemplates(FileSystemInterface $fileSystem, array $templateOutputs): void
    {
        // before making any changes in the filesystem we have to check there is a good chance we can make it
        foreach ($templateOutputs as $templateOutput) {
            if ($fileSystem->exists($templateOutput->getOutputRootFolder()) === false) {
                $rootFolder = $templateOutput->getOutputRootFolder();
                throw new InvalidArgumentException("Folder `$rootFolder` do not exist.");
            }

            if ($fileSystem->exists($templateOutput->getOutputPath()) === true) {
                $filePath = $templateOutput->getOutputPath();
                throw new InvalidArgumentException("File `$filePath` already exists.");
            }

            $outFolder = $templateOutput->getOutputFolder();
            if ($fileSystem->exists($outFolder) === true) {
                // the folder already exist so we have to check it is writable
                if ($fileSystem->isWritable($outFolder) === false) {
                    throw new InvalidArgumentException("Folder `$outFolder` is not writable.");
                }
            } else {
                // it should be a root folder with not yet existing sub-folder so root should be writable
                $rootFolder = $templateOutput->getOutputRootFolder();
                if ($fileSystem->isWritable($rootFolder) === false) {
                    throw new InvalidArgumentException("Folder `$rootFolder` is not writable.");
                }
            }
        }

        foreach ($templateOutputs as $templateOutput) {
            if ($fileSystem->exists($templateOutput->getOutputFolder()) === false) {
                $fileSystem->createFolder($templateOutput->getOutputFolder());
            }
            $fileSystem->write($templateOutput->getOutputPath(), $templateOutput->getOutputContent());
        }
    }
1184707
private function writeToFiles(
        array $content,
        string $baseDir,
        ConfigCache $dump,
        SymfonyBuilder $container
    ): void {
        $rootCode = array_pop($content);
        assert(is_string($rootCode));

        $filesystem = new Filesystem();

        foreach ($content as $file => $code) {
            $filesystem->dumpFile($baseDir . $file, $code);
        }

        $dump->write($rootCode, $container->getResources());
    }
460354
protected function executeClear(IoInterface $inOut, ContainerInterface $container): void
    {
        $settings    = $this->getTemplatesSettings($container);
        $cacheFolder = $settings[TemplatesSettings::KEY_CACHE_FOLDER];

        /** @var FileSystemInterface $fileSystem */
        $fileSystem = $container->get(FileSystemInterface::class);
        foreach ($fileSystem->scanFolder($cacheFolder) as $fileOrFolder) {
            $fileSystem->isFolder($fileOrFolder) === false ?: $fileSystem->deleteFolderRecursive($fileOrFolder);
        }

        $inOut->writeInfo('Cache has been cleared.' . PHP_EOL);
    }
332885
protected function renderTemplate($input, $outputFile, $template, $templates, $data = [])
    {
        $paths = [$templates];

        if ($templates = $input->getOption('templates')) {
            $paths []= $templates;
        }

        $paths = array_filter($paths);

        $loader = new Twig_Loader_Filesystem($paths);
        $twig = new Twig_Environment($loader);


        $template = $twig->loadTemplate($template);

        $dataOption = $input->getOption('data');

        if (file_exists($dataOption)) {
            $dataOption = file_get_contents($dataOption);
        }

        $dataOption = json_decode(stripcslashes($dataOption), true);

        if (!is_array($dataOption)) {
            $dataOption = [];
        }

        $data = array_merge($data, $dataOption);

        @mkdir(dirname($outputFile), 0755, true);
        file_put_contents($outputFile, $template->render($data));
    }
424569
protected static function registerPlugins($protocol, FilesystemInterface $filesystem)
    {
        $filesystem->addPlugin(new ForcedRename());
        $filesystem->addPlugin(new Mkdir());
        $filesystem->addPlugin(new Rmdir());

        $stat = new Stat(
            static::$config[$protocol]['permissions'],
            static::$config[$protocol]['metadata']
        );

        $filesystem->addPlugin($stat);
        $filesystem->addPlugin(new Touch());
    }
862589
protected function runPhp(\Everon\View\Interfaces\TemplateCompilerContext $Context, \Everon\Interfaces\FileSystem $FileSystem)
    {
        $handleError = function($errno, $errstr, $errfile, $errline, array $errcontext) {
            // error was suppressed with the @-operator
            if (0 === error_reporting()) {
                return false;
            }

            throw new \Everon\Exception\TemplateEvaluationError($errstr, 0, $errno, $errfile, $errline);
        };

        $old_error_handler = set_error_handler($handleError);

        $TmpPhpFile = $FileSystem->createTmpFile();
        try {
            $TmpPhpFile->write($Context->getPhp());
            $php_file = $TmpPhpFile->getFilename();
            
            ob_start();


            $callback = function() use ($php_file, $Context) {
                extract([
                    'Tpl' => new PopoProps($Context->getData()),
                ]);
                include $php_file;
            };
            
            $callback = $callback->bindTo($Context->getScope() ?: $this);
            $callback();
            
            $Context->setCompiled(ob_get_contents());
        }
        finally {
            ob_end_clean();
            $TmpPhpFile->close();
            restore_error_handler($old_error_handler);
        }
    }
722442
private void process( Collection<File> templateFiles ) {

		// Compile them all
		Collection<TemplateEntry> templateEntries = new ArrayList<> ();
		for( File f : templateFiles ) {
			final TemplateEntry templateEntry = compileTemplate( f );
			if( templateEntry != null )
				templateEntries.add( templateEntry );
		}

		// Add all the template entries
		this.lock.writeLock().lock();
		try {
			for( final TemplateEntry te : templateEntries )
				this.fileToTemplate.put( te.getTemplateFile(), te );

		} finally {
			this.lock.writeLock().unlock();
		}

		// Notify the templating manager
		this.manager.processNewTemplates( templateEntries );
	}
230093
private function work(CacheItem $cacheItem, ImageTemplate $template, array $attributes, $inputFilename = null, $missing = false)
    {
        $cacheFilename = null;

        $tempFilename = $this->tempDir.'/'.$cacheItem->getId().'.'.$template->getParameter('format');

        $cacheItem
            ->setTemplateKey($template->getKey())
            ->setTemplateRevision($template->getRevision())
            ->setCacheStatus(CacheItem::STATUS_DELEGATE)
            ->setQueueStatus(CacheItem::QUEUE_DONE)
            ->setFileSize(0)
            ->setError(null);

        if ($missing) {
            $this->applyError(
                $cacheItem,
                CacheItem::STATUS_MISSING,
                'Input file not found.',
                $inputFilename,
                $template->getType(),
                $template->getKey()
            );
        } elseif ($inputFilename === null) {
            $this->applyError(
                $cacheItem,
                CacheItem::STATUS_DELEGATE,
                'No preview image.',
                $inputFilename,
                $template->getType(),
                $template->getKey(),
                'warning'
            );
        } elseif (!$this->applier->isAvailable($inputFilename)) {
            $this->applyError(
                $cacheItem,
                CacheItem::STATUS_MISSING,
                'No suitable image template applier found.',
                $inputFilename,
                $template->getType(),
                $template->getKey()
            );
        } else {
            $filesystem = new Filesystem();
            if (!$filesystem->exists($this->tempDir)) {
                $filesystem->mkdir($this->tempDir, 0777);
            }
            if ($filesystem->exists($tempFilename)) {
                $filesystem->remove($tempFilename);
            }

            try {
                $image = $this->applier->apply($template, $attributes, $inputFilename, $tempFilename);

                $filesystem->chmod($tempFilename, 0777);

                $mediaType = $this->mediaTypeManager->findByFilename($tempFilename);

                $cacheItem
                    ->setCacheStatus(CacheItem::STATUS_OK)
                    ->setQueueStatus(CacheItem::QUEUE_DONE)
                    ->setMimeType($mediaType->getMimetype())
                    ->setMediaType($mediaType->getName())
                    ->setExtension(pathinfo($tempFilename, PATHINFO_EXTENSION))
                    ->setFileSize(filesize($tempFilename))
                    ->setWidth($image->getSize()->getWidth())
                    ->setHeight($image->getSize()->getHeight())
                    ->setFinishedAt(new \DateTime());
            } catch (\Exception $e) {
                $this->logger->error('Image worker error', array('exception' => $e, 'template' => $template->getId(), 'file' => $cacheItem->getFileId()));

                $cacheItem
                    ->setCacheStatus(CacheItem::STATUS_ERROR)
                    ->setQueueStatus(CacheItem::QUEUE_ERROR)
                    ->setError($e)
                    ->setFinishedAt(new \DateTime());
            }

            if ($cacheItem->getCacheStatus() === CacheItem::STATUS_OK) {
                $storage = $this->storageManager->get($template->getStorage());
                $storage->store($cacheItem, $tempFilename);
            }
        }

        $this->cacheManager->updateCacheItem($cacheItem);
    }
323890
public function handle(Filesystem $filesystem)
    {
        $this->publishing($filesystem, $this->option('force'));

        $this->info('Publishing complete!');
    }
521030
protected function publishRoute(Filesystem $filesystem, $route)
    {
        if (is_null($route)) {
            return ;
        }

        $routeFile = app_path('Http/routes.php');

        if ($filesystem->exists($routeFile) && $filesystem->exists($route)) {
            $filesystem->append($routeFile, $filesystem->get($route));

            $this->line('<info>Append routes from</info> <comment>['.$route.']</comment>');
        }
    }
429857
public function handle(ValidateFilenameService $validateFilename, Filesystem $filesystem)
    {
        $files = [];

        foreach ($this->files as $file) {
            $filename = $validateFilename->execute($this->targetDir, $file);

            $filesystem->move(
                $this->originDir . '/' . $file,
                $this->targetDir . '/' . $filename
            );

            $files[] = $filename;
        }

        return $files;
    }
1098523
public function onLoadTemplate(ITemplateFactory $templateFactory, $templateFile, $presenterName)
	{
		if (!$this->activeTheme) {
			return;
		}
		$templateFactory->addTemplate(
			$this->formatTemplateFilePath($this->activeTheme, $templateFile, $presenterName)
		);
		$templateFactory->addTemplate(
			$this->formatTemplateFilePath($this->activeTheme, $templateFile)
		);

		$parent = $this->activeTheme->getParent();
		if (!$parent) {
			return;
		}
		$parentTheme = $this->getTheme($parent);
		$templateFactory->addTemplate(
			$this->formatTemplateFilePath($parentTheme, $templateFile, $presenterName)
		);
		$templateFactory->addTemplate(
			$this->formatTemplateFilePath($parentTheme, $templateFile)
		);
	}
159610
public function setTemplateFile(string $templateFile)
    {
        if (!$templateFile) {
            return $this;
        }
        $this->templateFile = (string) $templateFile;

        return $this;
    }
928286
private function setTemplatesPath($templatesPath)
    {
        $this->templatesPath = $templatesPath;
        if (!is_readable($this->templatesPath)) {
            $this->error("Template Root Path ({$this->templatesPath}) does not exist or not readable.");
        }
    }
624252
protected function resolveTemplateFile(array $templates = array())
    {
        $templatePath = $this->getTemplatePath();

        $templates = array_merge($templates, $this->getDefaultTemplates());

        if (empty($templates)) {
            throw new Exception("No templates available.");
        }

        foreach ($templates as $templateFile) {
            $filePath = "$templatePath/$templateFile";

            if (is_file($filePath)) {
                return $filePath;
            }
        }

        return null;
    }
1124661
private List<OutputFile> processTemplates(List<TemplateFile> inputs) throws IOException {
    List<OutputFile> outputs = new ArrayList<>();
    for (TemplateFile f : inputs) {
      String fileName = f.getFileName();
      if (!fileName.contains("VType") && fileName.contains("KType")) {
        for (Type ktype : Type.values()) {
          TemplateOptions options = new TemplateOptions(ktype);
          options.templateFile = f.path;
          generate(f, outputs, options);
        }
      }
      if (fileName.contains("KTypeVType")) {
        for (Type ktype : Type.values()) {
          for (Type vtype : Type.values()) {
            TemplateOptions options = new TemplateOptions(ktype, vtype);
            options.templateFile = f.path;
            generate(f, outputs, options);
          }
        }
      }
    }
    return outputs;
  }
806887
public void setFileSystems(java.util.Collection<FileSystem> fileSystems) {
        if (fileSystems == null) {
            this.fileSystems = null;
            return;
        }

        this.fileSystems = new java.util.ArrayList<FileSystem>(fileSystems);
    }