/** * backup single database table to file * * @param string $table * @param string $path */ public function backupTableToFile(string $table, string $path) { $sql = $this->getHeader(); $sql .= $this->backupTable($table); FileSystem::createDir($path); $path .= '/' . $table . '_' . date('Y-m-d_H-i-s') . '.sql'; FileSystem::write($path, $sql); }
/** * Stores mail to a file. * * @param Message $message * @return void */ public function send(Message $message) { // get message with generated html instead of set FileTemplate etc $ref = new \ReflectionMethod('Nette\\Mail\\Message', 'build'); $ref->setAccessible(TRUE); /** @var Message $builtMail */ $builtMessage = $ref->invoke($message); $time = date('YmdHis'); $hash = substr(md5($builtMessage->getHeader('Message-ID')), 0, 6); $path = "{$this->tempDir}/{$time}-{$hash}.mail"; FileSystem::write($path, serialize($builtMessage)); $this->files = NULL; }
public function compileConfig() { $repositories = $this->getAll(); $domain = $this->httpRequest->getUrl()->getHostUrl(); $config = ['homepage' => $domain, 'repositories' => []]; foreach ($this->parameters as $property => $value) { $config[$property] = $value; } foreach ($repositories as $repository) { $config['repositories'][] = ['type' => $repository->type, 'url' => $repository->url]; } $json = Json::encode($config, Json::PRETTY); FileSystem::write($this->configFile, $json); }
/** * @param IListingPdfFile[] $pdfFiles * @param string $zipStorageFilePath * @return null */ private function zipFiles(array $pdfFiles, $zipStorageFilePath) { if (file_exists($zipStorageFilePath) and !is_dir($zipStorageFilePath)) { FileSystem::delete($zipStorageFilePath); } $zip = new \ZipArchive(); if ($zip->open($zipStorageFilePath, \ZipArchive::CREATE) !== true) { return null; } /** @var IListingPdfFile $pdfFile */ foreach ($pdfFiles as $pdfFile) { if (!file_exists($pdfFile->getStoragePath())) { FileSystem::write($pdfFile->getStoragePath(), $pdfFile->getPdfContent()); } $zip->addFile($pdfFile->getStoragePath(), $pdfFile->getFileName()); } $zip->close(); return $zipStorageFilePath; }
/** * @param IListingPdfSource $pdfSource * @return IListingPdfFile */ public function generate(IListingPdfSource $pdfSource) { $cache = $this->pdfCacheFactory->getCache($pdfSource->getOwnerId(), $pdfSource->getListingYear()); $pdfFileCacheKey = $this->createListingCacheKey($pdfSource->getListingId(), $pdfSource->getHashedListingSettings()); $listingCacheKey = 'listing/' . $pdfSource->getListingId(); $listingPdfFile = $cache->load($pdfFileCacheKey); if ($listingPdfFile === null) { $pdfContent = $this->pdfContentGenerator->createPdfContent($pdfSource); $listingPdfFile = $this->createPdfFile($pdfContent, $pdfSource); $cache->save($pdfFileCacheKey, $listingPdfFile, [Cache::TAGS => [$listingCacheKey]]); } $generatedPdfFilesCacheKey = 'generatedPdfFilesByListing/' . $listingPdfFile->getListingId(); $generatedPdfFilesByListings = $cache->load($generatedPdfFilesCacheKey); if ($generatedPdfFilesByListings === null) { $generatedPdfFilesByListings = []; } $generatedPdfFilesByListings[$pdfFileCacheKey] = $listingPdfFile->getStoragePath(); $cache->save($generatedPdfFilesCacheKey, $generatedPdfFilesByListings, [Cache::TAGS => [$listingCacheKey]]); FileSystem::write($listingPdfFile->getStoragePath(), $listingPdfFile->getPdfContent()); return $listingPdfFile; }
/** * Sends a request for satis build * @param bool $rewrite */ public function update($rewrite = false) { if (is_file($this->composerJsonFile)) { // read the composer.json file and post it's content via REST API $config = $this->configurationReader->read($this->composerJsonFile); // create payload to send $payload = new \stdClass(); $payload->{'name'} = Strings::webalize($config->name()); $payload->{'composer.json'} = $config->rawData(); /** @var Response $response */ $response = Request::post($this->apiEndpoint . '/repository')->body($payload)->sendsJson()->send(); if ($response->code == 200) { // success if ($rewrite) { // rewrite original composer.json with modified one // with occasionally modified 'repositories' section $newComposerJsonContent = $response->body->{'generated-files'}->{'composer.json'}->{'content'}; // $newComposerJsonContent is pretty printed string FileSystem::write($this->composerJsonFile, $newComposerJsonContent); } } } }
/** * @param string $policyNo * @param Response $response * @return bool|string */ public function savePdfFile($policyNo, Response $response) { if ($response->getHeaders()['Content-Type'] !== 'application/pdf') { return FALSE; } $body = $response->getResponse(); $filename = $this->tempDir . '/' . $policyNo . '-' . Strings::substring(md5($body), 0, 5) . '.pdf'; $this->toDelete[] = $filename; FileSystem::write($filename, $body); return $filename; }
/** * activate configuration * @param string $sopClassPath * @return void */ public function activateConfig($sopClassPath) { $outputText = $this->defaultValues; $table = $this->getTable(); $values = $table->where("active", 1); foreach ($values as $value) { $outputText .= $value->name . "\t" . $value->sop . "\t" . $value->application . "\t" . $value->transfer . "\n"; } \Nette\Utils\FileSystem::delete($sopClassPath); \Nette\Utils\FileSystem::write($sopClassPath, $outputText); $table2 = $this->getTable(); $table2->where("activated", 0); $table2->update(array("activated" => 1)); return; }
private function saveTemplate($destination, $content) { return \Nette\Utils\FileSystem::write($destination, $content, 0777) ? $content : FALSE; }
public function generateTests($outputFolder) { $container = \Testbench\ContainerFactory::create(FALSE); $presenterFactory = $container->getByType('Nette\\Application\\IPresenterFactory'); $presenters = $container->findByType('Nette\\Application\\UI\\Presenter'); foreach ($presenters as $presenter) { $this->renderMethods = $this->handleMethods = $this->componentMethods = []; /** @var \Nette\Application\UI\Presenter $service */ $service = $container->getService($presenter); if ($service instanceof \Testbench\Mocks\PresenterMock) { continue; } if ($service instanceof \KdybyModule\CliPresenter) { //Oh, Kdyby! :-( continue; } $rc = new \ReflectionClass($service); $renderPrefix = $service->formatActionMethod('') . '|' . $service->formatRenderMethod(''); $methods = $rc->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED); foreach ($methods as $method) { $methodName = $method->getName(); if (preg_match("~^({$renderPrefix})[a-z0-9]+~i", $methodName)) { try { $optionalArgs = $this->tryCall($service, $methodName, $service->getParameters(), TRUE); if (preg_match('~.*rss.*~i', $methodName)) { $this->renderMethods[$methodName] = 'rss'; } elseif (preg_match('~.*sitemap.*~i', $methodName)) { $this->renderMethods[$methodName] = 'sitemap'; } else { $requiredArgs = $this->tryCall($service, $methodName, $service->getParameters(), FALSE); $this->renderMethods[$methodName] = ['action', [$optionalArgs, $requiredArgs]]; } } catch (\Nette\Application\AbortException $exc) { $this->renderMethods[$methodName] = ['action', $this->getResponse($service)]; } catch (\Exception $exc) { $this->renderMethods[$methodName] = ['exception', $exc]; } } if (preg_match('~^handle[a-z0-9]+~i', $methodName)) { if ($methodName === 'handleInvalidLink') { //internal method continue; } $this->handleMethods[] = $methodName; } if (preg_match('~^createComponent[a-z0-9]+~i', $methodName)) { $method->setAccessible(TRUE); $form = $method->invoke($service); if ($form instanceof \Nette\Application\UI\Form) { $this->componentMethods[$methodName] = $form; } } } $testClassName = $rc->getShortName() . 'Test'; $testClass = new PhpGenerator\ClassType($testClassName); $testClass->setExtends('\\Tester\\TestCase'); $testClass->addTrait('\\Testbench\\TPresenter'); $testClass->addComment('@testCase'); foreach ($this->renderMethods as $testMethod => $testMethodType) { $generatedMethod = $testClass->addMethod('test' . ucfirst($testMethod)); $destination = $presenterFactory->unformatPresenterClass($rc->getName()) . ':'; $destination .= lcfirst(preg_replace('~^(action|render)([a-z]+)~i', '$2', $testMethod)); $extra = NULL; if (is_array($testMethodType)) { /** @var \Exception|\Nette\Application\IResponse $extra */ $extra = $testMethodType[1]; $testMethodType = $testMethodType[0]; //FIXME: fuj, hnus } switch ($testMethodType) { case 'rss': $generatedMethod->addBody('$this->checkRss(?);', [$destination]); break; case 'sitemap': $generatedMethod->addBody('$this->checkSitemap(?);', [$destination]); break; case 'action': if ($extra instanceof \Nette\Application\Responses\RedirectResponse) { $url = new \Nette\Http\Url($extra->getUrl()); $generatedMethod->addBody('$this->checkRedirect(?, ?);', [$destination, $url->getPath()]); } elseif ($extra instanceof \Nette\Application\Responses\JsonResponse) { $generatedMethod->addBody('$this->checkJson(?);', [$destination]); } else { if ($extra[0]) { $generatedMethod->addBody('//FIXME: parameters may not be correct'); $generatedMethod->addBody("\$this->checkAction(?, ?);\n", [$destination, $extra[0]]); $generatedMethod->addBody('$this->checkAction(?, ?);', [$destination, $extra[1]]); } else { $generatedMethod->addBody('$this->checkAction(?);', [$destination]); } } break; case 'exception': $this->generateExceptionBody($generatedMethod, $destination, $extra); break; } } foreach ($this->handleMethods as $testMethod) { $destination = $presenterFactory->unformatPresenterClass($rc->getName()); $action = lcfirst(preg_replace('~^handle([a-z]+)~i', '$1', $testMethod)); $testClass->addMethod('test' . ucfirst($testMethod))->addBody('$this->checkSignal(?, ?);', [$destination . ':', $action]); } foreach ($this->componentMethods as $testMethod => $form) { $destination = $presenterFactory->unformatPresenterClass($rc->getName()); $action = lcfirst(preg_replace('~^createComponent([a-z]+)~i', '$1', $testMethod)); $controls = ''; /** @var \Nette\Application\UI\Form $form */ foreach ($form->getControls() as $control) { if ($control->getName() === '_token_' || $control instanceof \Nette\Forms\Controls\SubmitButton) { continue; } $value = "'###', //FIXME: replace with value"; if ($control instanceof \Nette\Forms\Controls\Checkbox) { $value = 'FALSE'; } $controls .= "\t'" . $control->getName() . "' => {$value}\n"; } try { $form->onSuccess($form, $form->getValues()); $testClass->addMethod('test' . ucfirst($testMethod))->addBody("\$this->checkForm(?, ?, [\n" . $controls . '], ?);', [$destination . ':', $action, FALSE]); } catch (\Nette\Application\AbortException $exc) { $extra = $this->getResponse($service); $path = $extra ? (new \Nette\Http\Url($extra->getUrl()))->getPath() : '/'; $testClass->addMethod('test' . ucfirst($testMethod))->addBody("\$this->checkForm(?, ?, [\n" . $controls . '], ?);', [$destination . ':', $action, $path]); } catch (\Exception $exc) { //This sucks but we have to move on - failure is not an option } } $namespace = $rc->getNamespaceName(); $namespace = $namespace ? '\\' . $namespace : ''; $generatedTest = "<?php\n\nnamespace Tests{$namespace};\n\nuse Tester\\Assert;\n\n"; $depth = substr_count($namespace, '\\'); $levelsUp = str_repeat('../', $depth); $generatedTest .= "require __DIR__ . '/{$levelsUp}bootstrap.php';\n\n"; $generatedTest .= $testClass; $generatedTest .= "\n(new {$testClassName})->run();\n"; $testFileName = preg_replace('~\\\\~', DIRECTORY_SEPARATOR, get_class($service)); \Nette\Utils\FileSystem::write($outputFolder . '/' . $testFileName . '.phpt', $generatedTest); \Nette\Utils\FileSystem::createDir($outputFolder . '/_temp'); \Nette\Utils\FileSystem::write($outputFolder . '/tests.neon', <<<'NEON' # WARNING: it is CRITICAL that this file & directory are NOT accessible directly via a web browser! # http://nette.org/security-warning # (this is just an example) routing: routes: '/x/y[[[/<presenter>]/<action>][/<id>]]': 'Presenter:default' NEON ); } }
/** * @param string $file * @param string $code */ protected function writeIfChanged($file, $code) { $content = @file_get_contents($file); // @ file may not exist if (!$content || $content != $code) { FileSystem::createDir(dirname($file)); FileSystem::write($file, $code, NULL); $this->changed = TRUE; } }
/** * activate configuration * @param string $acrNemaPath * @return void */ public function activateConfig($acrNemaPath) { $outputText = $this->defaultValues; $table = $this->getTable(); $values = $table->where("active", 1); foreach ($values as $value) { $outputText .= $value->aet . "\t" . $value->ip_address . "\t" . $value->port . "\t" . $value->compression . "\n"; } \Nette\Utils\FileSystem::delete($acrNemaPath); \Nette\Utils\FileSystem::write($acrNemaPath, $outputText); $table2 = $this->getTable(); $table2->where("activated", 0); $table2->update(array("activated" => 1)); return; }
/** * Writes a string to a file. * * @param string $file File path * @param string $content Content to write * @param int $mode File mode * * @return bool */ public function write($file, $content, $mode = 0666) { return \Nette\Utils\FileSystem::write($file, $content, $mode); }
/** * activate configuration * @param string $dicomIniPath * @return void */ public function activateConfig($dicomIniPath) { $outputText = "[sscscp]\n"; $table = $this->getTable(); $table->where("active", 1); if (is_array($this->defaultValues)) { $values = array_merge($this->defaultValues, $table->fetchPairs("item", "value")); } else { $values = $table->fetchPairs("item", "value"); } foreach ($values as $key => $value) { $outputText .= $key . " = " . $value . "\n"; } \Nette\Utils\FileSystem::delete($dicomIniPath); \Nette\Utils\FileSystem::write($dicomIniPath, $outputText); $table2 = $this->getTable(); $table2->where("activated", 0); $table2->update(array("activated" => 1)); return; }
/** * @param string $token * @param string $xml * @throws FioFailureException * @throws FioWarningException * @throws FioTemporaryUnavailableException */ private function upload($token, $xml) { $filepath = tempnam(sys_get_temp_dir(), 'fio'); FileSystem::write($filepath, $xml); $post = ['token' => $token, 'type' => 'xml', 'lng' => 'cs', 'file' => new CURLFile($filepath)]; $request = new Request(Request::POST, self::UPLOAD_URL, [], $post); $response = $this->sendRequest($request); $this->checkUploadResponse($response->getBody()); }
/** * Runs the whole suite of steps * * @param boolean $preserveScript */ public function run($preserveScript = false) { $fragment = <<<FRAGMENT casper.run(); FRAGMENT; $this->addFragment($fragment); // for work with files must be required fs module if ($this->useFsModule) { $fragment = <<<FRAGMENT var fs = require('fs'); FRAGMENT; $this->shiftFragment($fragment); } $filename = uniqid('casper-') . '.js'; FileSystem::write($filename, $this->script); $this->doRun($filename); $this->logOutput(); if (!$preserveScript) { FileSystem::delete($filename); } }
/** Check Nette extensions configuration */ public function checkExtensionsConfiguration() { $newInstall = FALSE; CLI::write('Verifying extensions configuration:', 1, TRUE, TRUE, TRUE); $config = (new \Nette\Neon\Decoder())->decode(\Bruha\Generator\Utils\File::read(static::$settings->netteRoot . '/app/config/config.neon')); if (isset($config['nette'])) { // Nette ~2.2.* $config['nette']['session']['autoStart'] = TRUE; } else { $config['session']['autoStart'] = TRUE; } CLI::write('Kdyby\\Translation:', 2, TRUE, FALSE); if (!isset($config['extensions']['translation'])) { $config['extensions']['translation'] = 'Kdyby\\Translation\\DI\\TranslationExtension'; CLI::write('NOT INSTALLED', 0, FALSE); CLI::write('Installing: SUCCESS', 3); $newInstall = TRUE; } else { CLI::write('INSTALLED', 0, FALSE); } CLI::write('Kdyby\\Replicator:', 2, TRUE, FALSE); if (!isset($config['extensions']['replicator'])) { $config['extensions']['replicator'] = 'Kdyby\\Replicator\\DI\\ReplicatorExtension'; CLI::write('NOT INSTALLED', 0, FALSE); CLI::write('Installing: SUCCESS', 3); $newInstall = TRUE; } else { CLI::write('INSTALLED', 0, FALSE); } CLI::write('Kdyby\\Annotations:', 2, TRUE, FALSE); if (!isset($config['extensions']['annotations'])) { $config['extensions']['annotations'] = 'Kdyby\\Annotations\\DI\\AnnotationsExtension'; CLI::write('NOT INSTALLED', 0, FALSE); CLI::write('Installing: SUCCESS', 3); $newInstall = TRUE; } else { CLI::write('INSTALLED', 0, FALSE); } CLI::write('Kdyby\\Console:', 2, TRUE, FALSE); if (!isset($config['extensions']['console'])) { $config['extensions']['console'] = 'Kdyby\\Console\\DI\\ConsoleExtension'; CLI::write('NOT INSTALLED', 0, FALSE); CLI::write('Installing: SUCCESS', 3); $newInstall = TRUE; } else { CLI::write('INSTALLED', 0, FALSE); } CLI::write('Kdyby\\Events:', 2, TRUE, FALSE); if (!isset($config['extensions']['events'])) { $config['extensions']['events'] = 'Kdyby\\Events\\DI\\EventsExtension'; CLI::write('NOT INSTALLED', 0, FALSE); CLI::write('Installing: SUCCESS', 3); $newInstall = TRUE; } else { CLI::write('INSTALLED', 0, FALSE); } CLI::write('Kdyby\\Doctrine:', 2, TRUE, FALSE); if (!isset($config['extensions']['doctrine'])) { $config['extensions']['doctrine'] = 'Kdyby\\Doctrine\\DI\\OrmExtension'; $database = static::$settings->netteDatabase; $config['doctrine'] = ['host' => $database->hostname, 'user' => $database->username, 'password' => $database->password, 'dbname' => $database->database, 'metadata' => ['App' => '%appDir%'], 'dql' => ['string' => ['CONCAT_WS' => 'DoctrineExtensions\\Query\\Mysql\\ConcatWs']]]; CLI::write('NOT INSTALLED', 0, FALSE); CLI::write('Installing: SUCCESS', 3); $newInstall = TRUE; } else { CLI::write('INSTALLED', 0, FALSE); } \Nette\Utils\FileSystem::write(static::$settings->netteRoot . '/app/config/config.neon', preg_replace('~(^[\\r\\n]*|[\\r\\n]+)[\\s\\t]*[\\r\\n]+~', "\n", (new \Nette\Neon\Encoder())->encode($config, \Nette\Neon\Encoder::BLOCK))); return $newInstall; }
/** * Generate file * * @param string $filename * @param string $code */ protected function generateFile($filename, $code) { FileSystem::write($this->config->get('output') . DIRECTORY_SEPARATOR . $filename, "<?php\n\n{$code}"); }