Dumps runonce file to the target file given in the constructor.

@throws \RuntimeException If the combined runonce file exists but is not writable.

@return void
350983
public function dump()
    {
        if (empty($this->files)) {
            return;
        }

        $buffer = <<<'PHP'
<?php

$runonce = function(array $files, $delete = false) {
    foreach ($files as $file) {
        try {
            include $file;
        } catch (\Exception $e) {}

        $relpath = str_replace(TL_ROOT . DIRECTORY_SEPARATOR, '', $file);

        if ($delete && !unlink($file)) {
            throw new \Exception(
                'The file ' . $relpath . ' cannot be deleted. ' .
                'Please remove the file manually and correct the file permission settings on your server.'
            );
        }
    }
};

PHP;

        if (file_exists($this->targetFile)) {
            if (!is_writable($this->targetFile) || !is_file($this->targetFile)) {
                throw new \RuntimeException(
                    sprintf('Runonce file "%s" exists but is not writable.', $this->targetFile)
                );
            }

            $current = str_replace('.php', '_'.substr(md5(mt_rand()), 0, 8).'.php', $this->targetFile);
            $this->filesystem->rename($this->targetFile, $current);

            $buffer .= "\n\$runonce(array('" . $current . "'), true);\n";
        }

        $buffer .= "\n\$runonce(" . var_export(array_unique($this->files), true) . ");\n";

        $this->filesystem->ensureDirectoryExists(dirname($this->targetFile));

        if (false === file_put_contents($this->targetFile, $buffer)) {
            throw new \RuntimeException(sprintf('Could not write runonce file to "%s"', $this->targetFile));
        }

        $this->files = [];
    }
382120
protected function setDerivedFileProperties()
    {
        if ( ! $this->file || ! file_exists($this->file->getRealPath())) {
            throw new RuntimeException("Local file not found at {$this->file->getPath()}");
        }

        $this->size = $this->file->getSize();

        if (null === $this->name) {
            $this->name = $this->file->getBasename();
        }
    }
1005141
private function checkDir() : void
    {
        $dir = dirname($this->path);
        if (!is_dir($dir)) {
            if (file_exists($dir)) {
                throw new \RuntimeException($dir . ' exists and is not a directory.');
            }
            if (!@mkdir($dir, 0755, true)) {
                throw new \RuntimeException($dir . ' does not exist and could not be created.');
            }
        }
    }
1321640
public function compile()
    {
        if($this->compiledExists() === false)
        {
            if(is_file($this->filepath) === false)
            {
                throw new \Exception('File "'.$this->filepath.'" does not exists.');
            }

            $this->raw = file_get_contents($this->filepath);

            if($this->options['add-source-line-numbers'])
                $this->prepared = $this->addLinesNumbers($this->raw);
            else
                $this->prepared = $this->raw;

            $this->removeComments();
            $this->resolveExtending();
            $this->compileRenders();
            $this->compileEchoes();
            $this->compileConditions();
            $this->compileLoops();
            $this->compileSpecialStatements();
            $this->prepareSections();
            $this->findSections();
            $this->replaceSections();
        }
    }
1133823
public function save($data): void
    {
        $filepath = $this->filepath;
        $dir = $this->getPath();

        if (!$this->mkdir($dir)) {
            throw new \RuntimeException('Creating directory failed for ' . $filepath);
        }

        try {
            if ($this->handle) {
                $tmp = true;
                // As we are using non-truncating locking, make sure that the file is empty before writing.
                if (@ftruncate($this->handle, 0) === false || @fwrite($this->handle, $data) === false) {
                    // Writing file failed, throw an error.
                    $tmp = false;
                }
            } else {
                // Create file with a temporary name and rename it to make the save action atomic.
                $tmp = $this->tempname($filepath);
                if (@file_put_contents($tmp, $data) === false) {
                    $tmp = false;
                } elseif (@rename($tmp, $filepath) === false) {
                    @unlink($tmp);
                    $tmp = false;
                }
            }
        } catch (\Exception $e) {
            $tmp = false;
        }

        if ($tmp === false) {
            throw new \RuntimeException('Failed to save file ' . $filepath);
        }

        // Touch the directory as well, thus marking it modified.
        @touch($dir);
    }
1078735
public function save()
    {
        $path = $this->_buildParamsPath($this->alias);

        if (file_exists($path)) {
            chmod($path, 0644);
        }

        $params = '';

        foreach ($this->params as $key => $value) {
          $params .= $key.'='.$value."\n";
        }

        try {
          file_put_contents($path, $params);
        } catch (Exception $e) {
            throw new \RuntimeException($e->getMessage());
        }

        chmod($path, 0444);

        return $this;
    }
1235979
public function run()
    {
        // If the truthTest failed, don't run
        if ($this->truthTest !== true) {
            return false;
        }

        // If overlapping, don't run
        if ($this->isOverlapping()) {
            return false;
        }

        $compiled = $this->compile();

        // Write lock file if necessary
        $this->createLockFile();

        if (is_callable($this->before)) {
            call_user_func($this->before);
        }

        if (is_callable($compiled)) {
            $this->output = $this->exec($compiled);
        } else {
            exec($compiled, $this->output, $this->returnCode);
        }

        $this->finalise();

        return true;
    }
563720
public function save($data = null)
    {
        if ($data !== null) {
            $this->content($data);
        }

        $filename = $this->filename;
        $dir = \dirname($filename);

        if (!$this->mkdir($dir)) {
            throw new \RuntimeException('Creating directory failed for ' . $filename);
        }

        try {
            if ($this->handle) {
                $tmp = true;
                // As we are using non-truncating locking, make sure that the file is empty before writing.
                if (@ftruncate($this->handle, 0) === false || @fwrite($this->handle, $this->raw()) === false) {
                    // Writing file failed, throw an error.
                    $tmp = false;
                }
            } else {
                // Create file with a temporary name and rename it to make the save action atomic.
                $tmp = $this->tempname($filename);
                if (file_put_contents($tmp, $this->raw()) === false) {
                    $tmp = false;
                } elseif (@rename($tmp, $filename) === false) {
                    @unlink($tmp);
                    $tmp = false;
                }
            }
        } catch (\Exception $e) {
            $tmp = false;
        }

        if ($tmp === false) {
            throw new \RuntimeException('Failed to save file ' . $filename);
        }

        // Touch the directory as well, thus marking it modified.
        @touch($dir);
    }
1352773
public function write($file)
    {
        if (file_exists($file) && !is_writable($file)) {
            throw new RuntimeException("$file is not writable");
        }
        $fp = fopen($file, 'w');
        foreach ($this->lines as $line) {
            fwrite($fp, $line['data']);
        }
        fclose($fp);
    }
711588
public function export()
    {
        if ( ! is_dir($this->_outputDir)) {
            mkdir($this->_outputDir, 0775, true);
        }

        foreach ($this->_metadata as $metadata) {
            // In case output is returned, write it to a file, skip otherwise
            if($output = $this->exportClassMetadata($metadata)){
                $path = $this->_generateOutputPath($metadata);
                $dir = dirname($path);
                if ( ! is_dir($dir)) {
                    mkdir($dir, 0775, true);
                }
                if (file_exists($path) && !$this->_overwriteExistingFiles) {
                    throw ExportException::attemptOverwriteExistingFile($path);
                }
                file_put_contents($path, $output);
                chmod($path, 0664);
            }
        }
    }
884402
protected function doExecute()
    {
        if ($this->console->getMode() !== 'dev') {
            throw new \RuntimeException(
                '<error>STOP!</error> please run <info>' . $this->getEnvCmd() . '</info>.'
            );
        }

        if (!(new BooleanPrompter())
            ->ask('This action will drop all tables, do you really want to do this? [N/y]', false)) {
            $this->out('  Canceled.');

            return false;
        }

        if (!$this->io->getOption('no-backup')) {
            // backup
            $this->backup();
        }

        $db = $this->console->database;

        $tables = $db->getDatabase()->getTables(true);

        foreach ($tables as $table) {
            $db->getTable($table, true)->drop(true);

            $this->out('  Drop table: <comment>' . $table . '</comment>');
        }

        return true;
    }
61112
protected function writeCache()
    {
        $chunkSize = 1024 * 8;

        // open remote file
        $arrContextOptions = array(
            "ssl" => array(
                "verify_peer" => false,
                "verify_peer_name" => false,
            ),
        );
        $remoteFile = fopen(
            $this->pathFile,
            'rb',
            null,
            stream_context_create($arrContextOptions)
        );
        if (!$remoteFile) {
            throw new \RuntimeException(
                sprintf(
                    "Couldn't open file at %s",
                    $this->pathFile
                )
            );
        }

        // open cache file
        $cacheFile = fopen($this->pathCache, 'wb');
        if (!$cacheFile) {
            fclose($remoteFile);
            throw new \RuntimeException(
                sprintf(
                    "Couldn't open cache file at %s",
                    $this->pathCache
                )
            );
        }

        // write file to cache
        while (!feof($remoteFile)) {
            fwrite(
                $cacheFile,
                fread($remoteFile, $chunkSize),
                $chunkSize
            );
        }

        // close cache file
        fclose($cacheFile);

        // close remote file
        fclose($remoteFile);
    }
54066
public function initialize()
    {
        if ($this->isActive()) {
            throw new RuntimeException('Process is already active');
        }

        $handle = $this->getFileResource();

        if (! @flock($handle, (LOCK_EX | LOCK_NB))) {
            throw new RuntimeException('Could not lock pidfile');
        }

        if (-1 === @fseek($handle, 0)) {
            throw new RuntimeException('Could not seek pidfile cursor');
        }

        if (! @ftruncate($handle, 0)) {
            throw new RuntimeException('Could not truncate pidfile');
        }

        if (! @fwrite($handle, $this->control->info()->getId().PHP_EOL)) {
            throw new RuntimeException('Could not write on pidfile');
        }
    }
161883
protected function doExecute()
    {
        $path = getcwd() . '/' . $this->getArgument(0);

        if (!is_file($path)) {
            throw new \RuntimeException('Not file');
        }

        $content = Yaml::parse(file_get_contents($path));
        $year = Chronos::create()->year;

        $content = PhpFormat::structToString(
            $content,
            [
                'header' => "/**
 * Part of Windwalker project.
 *
 * @copyright  Copyright (C) $year __ORGANIZATION__.
 * @license    __LICENSE__
 */"
            ]
        );

        $path = substr_replace($path, 'php', strrpos($path, '.') + 1);

        file_put_contents($path, $content);
        $this->out('Write to:' . $path);

        return true;
    }
910355
public function commitBuffer(): void
    {
        if (!$this->buffering) {
            throw new \RuntimeException('Not buffering.');
        }
        $this->buffering = false;
        if ($this->changed) {
            $this->xliff->save($this->filename);
            $this->changed = false;
        }
    }
51980
private function renderResult()
    {
        /* @var ResultEvent $resultEvent */
        $results = array();

        $file = static::getCacheFileName();
        if (!file_exists($file)) {
            throw new \RuntimeException(sprintf(
                'Unknown PhpSpec results'
            ));
        }

        $data = Filesystem::create()->unserialize($file);

        // processing succeed first
        foreach ($data as $resultEvent) {
            $file = $resultEvent->getArgument('file');
            $failedKey = md5($file);
            if ($resultEvent->isSucceed()) {
                if (isset($this->failed[$failedKey])) {
                    unset($this->failed[$failedKey]);
                }
            }
        }

        foreach ($data as $resultEvent) {
            $file = $resultEvent->getArgument('file');
            $failedKey = md5($file);
            if (!$resultEvent->isSucceed()) {
                $this->failed[$failedKey] = $resultEvent;
                $results[] = $resultEvent;
            }
        }

        return $results;
    }
311802
public function dump(): void
    {
        $dump = $this->config['dump'] ?? [];

        if (is_array($dump) && count($dump) > 0) {
            // 'speed', 'included_files', 'include_path', 'whitespace'
            $dump = array_flip($dump);

            $url = isset($_SERVER['REQUEST_METHOD']) ? ($_SERVER['REQUEST_METHOD'] . '=' . Application::getCurrentURL()) : ('CLI=' . Application::getCliName());

            if (array_key_exists('speed', $dump)) {
                $executedIn = Application::getRequestExecutionTime();
                $count = count(get_included_files());
                $this->logMessage(new Message('notice', "{$url} EXECUTED IN {$executedIn}ms, used {$count} files"));
            }

            if (array_key_exists('memory', $dump)) {
                $memory = memory_get_usage();
                $peak = memory_get_peak_usage();
                $allocatedMemory = memory_get_peak_usage(true);
                $memoryLimit = ini_get('memory_limit') ?? -1;

                $memoryKb = round($memory / 1024, 2);
                $peakKb = round($peak / 1024, 2);
                $allocatedMemoryKb = round($allocatedMemory / 1024, 2);

                $limit = '';
                $peakSpent = '';

                if ($memoryLimit > 0) {
                    $limitInt = Convert::stringToBytes($memoryLimit);
                    $limit = ", limit: {$memoryLimit}";

                    $spent = round($peak / $limitInt * 100, 2);
                    $peakSpent = " ({$spent}% of limit)";
                }

                $this->logMessage(new Message('notice', "{$url} CONSUMED MEM: current: {$memoryKb}kb, peak: {$peakKb}kb{$peakSpent}, allocated: {$allocatedMemoryKb}kb{$limit}"));
            }

            if (array_key_exists('included_files', $dump)) {
                $this->logMessage(new Message('notice', 'Included files: ' . print_r(get_included_files(), true)));
            }

            if (array_key_exists('whitespace', $dump)) {
                $this->logMessage(new Message('notice', "END OF {$url}\n" . str_repeat('#', 120) . "\n\n"));
            }
        }
    }