/** * Create an express view from the given XML view, will utilize the cache directory * to dump and load a template compiled into plain PHP code. * * @param ExpressViewRenderer $renderer * @param string $resource The resource to be compiled into a view. * @return string The fully-qualified name of the compiled view. * * @throws \RuntimeException When the given resource could not be found. */ public function createView(ExpressViewRenderer $renderer, $resource) { $resource = (string) $resource; if (!is_file($resource)) { throw new \RuntimeException(sprintf('Express view not found: "%s"', $resource)); } $key = $this->createKey($resource); $typeName = $this->createTypeName($resource); if (class_exists($typeName, false)) { return $typeName; } $file = $this->cachePath . '/' . $key . '.php'; if (!is_file($file) || filemtime($file) < filemtime($resource)) { $time = microtime(true); try { $code = $this->parseView($renderer, file_get_contents($resource), $resource)->generateCode($key); } catch (\Exception $e) { throw new \RuntimeException(sprintf('Unable to parse express view "%s"', $resource), 0, $e); } Filesystem::writeFile($file, $code); $diff = sprintf('%.2f', microtime(true) - $time); if ($this->logger) { $this->logger->info('Compiled express view {view}, time spent {time} seconds', ['view' => $resource, 'time' => $diff]); } } require_once $file; if (!class_exists($typeName, false)) { throw new \RuntimeException(sprintf('Unable to load compiled express view "%s"', $resource)); } return $typeName; }
protected function setupDatabase(InputInterface $input, OutputInterface $output) { if ($this->manager === NULL) { $questionHelper = $this->getHelper('question'); $file = Filesystem::normalizePath($this->configFile); if (!is_file($file)) { $output->writeln(sprintf('Missing config file: <info>%s</info>', $this->configFile)); $question = new ConfirmationQuestion('Do you want to generate the config file? [n] ', false); if ($questionHelper->ask($input, $output, $question)) { $tpl = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'ConfigTemplate.txt'); $replacements = []; $question = new Question('Database DSN (PDO): ', ''); $dsn = $questionHelper->ask($input, $output, $question); $question = new Question('DB username: '******''); $username = $questionHelper->ask($input, $output, $question); $question = new Question('DB password: '******''); $password = $questionHelper->ask($input, $output, $question); $replacements['###DSN###'] = var_export((string) $dsn, true); $replacements['###USERNAME###'] = var_export(trim($username) === '' ? NULL : $username, true); $replacements['###PASSWORD###'] = var_export(trim($password) === '' ? NULL : $password, true); $code = strtr($tpl, $replacements); Filesystem::writeFile($file, $code); $output->writeln(sprintf('Generated <info>%s</file> with this contents:', $file)); $output->writeln(''); $output->writeln($code); } return false; } $config = new Configuration($this->processConfigData(require $file)); $this->manager = new ConnectionManager($config->getConfig('ConnectionManager')); $this->migrationDirectories = $config->getConfig('Migration.MigrationManager.directories')->toArray(); } return true; }
public function __invoke(RoutingContextInterface $context) { $match = $context->getRouteMatch(); $identifier = (string) $match->getParameter('identifier'); $pipeline = $this->manager->findPipeline($identifier); $pipeHash = $pipeline->getHash(); $etag = new EntityTag($pipeHash); $ttl = $pipeline->getTtl(); $expires = new \DateTimeImmutable('@' . (time() + $ttl)); $response = $context->getRequest()->evaluatePreconditions($etag); if ($response !== NULL) { $response->setHeader('Cache-Control', sprintf('public, max-age=%u', $ttl)); $response->setHeader(new ExpiresHeader($expires)); return $response; } if (is_dir($this->cachePath)) { foreach (glob($this->cachePath . '/' . $identifier . '-*', GLOB_NOSORT) as $file) { @unlink($file); } } $response = new HttpResponse(); $response->setHeader('Content-Type', sprintf('%s; charset="%s"', $pipeline->getMediaType(), $pipeline->getEncoding())); $response->setHeader('Access-Control-Allow-Origin', '*'); $response->setHeader('Cache-Control', sprintf('public, max-age=%u', $ttl)); $response->setHeader('ETag', $etag); $response->setHeader(new ExpiresHeader($expires)); if (is_dir($this->cachePath)) { $file = $this->cachePath . '/' . $identifier . '-' . $pipeHash; Filesystem::writeFile($file, $pipeline->dump($this->publisher)); $response->setEntity(new FileEntity(new \SplFileInfo($file))); } else { $response->setEntity((string) $pipeline->dump($this->publisher)); } return $response; }
public function execute(InputInterface $input, OutputInterface $output) { $file = $input->getArgument('file'); if (!preg_match("'^/|(?:[^:\\\\/]+://)|(?:[a-z]:[\\\\/])'i", $file)) { $file = $this->directory . '/resource/' . $file . '.html.xml'; } $file = Filesystem::normalizePath($file); $questionHelper = $this->getHelper('question'); $question = new ConfirmationQuestion(sprintf('Create view <info>%s</info>? [n] ', $file), false); if (!$questionHelper->ask($input, $output, $question)) { return; } $xml = new \DOMDocument('1.0', 'UTF-8'); $xml->formatOutput = true; $root = $xml->appendChild($xml->createElementNS(ExpressViewParser::NS_EXPRESS, 'k:composition')); $root->appendChild($xml->createAttribute('extends')); $root->appendChild($xml->createAttribute('xmlns'))->appendChild($xml->createTextNode(ExpressViewParser::NS_XHTML)); $root->appendChild($xml->createTextNode("\n\n ")); $block = $root->appendChild($xml->createElementNS(ExpressViewParser::NS_EXPRESS, 'k:block')); $block->appendChild($xml->createAttribute('name'))->appendChild($xml->createTextNode('main')); $block->appendChild($xml->createTextNode("\n TODO: Create composition contents...\n ")); $root->appendChild($xml->createTextNode("\n\n")); Filesystem::writeFile($file, $xml->saveXML()); $output->writeln(''); $output->writeln(sprintf('CREATED: <info>%s</info>', $file)); }
public function write($id, $data) { $file = $this->directory . DIRECTORY_SEPARATOR . $id . '.dat'; if ($this->compressionLevel) { Filesystem::writeFile($file, gzcompress($data, $this->compressionLevel)); } else { Filesystem::writeFile($file, (string) $data); } return true; }
public function loadType($typeName) { if (empty($this->typeMap[$typeName])) { return false; } $meta = $this->typeMap[$typeName]; $file = $this->cachePath . md5($meta[0]) . '.php'; if (!is_file($file) || filemtime($file) < $meta[1]) { Filesystem::writeFile($file, $this->instrumentFile($meta[0])); } require_once $file; return true; }
protected function loadRouter(ResourceMountHandler $mount) { $ref = new \ReflectionClass($mount->getTypeName()); $cacheKey = md5($ref->name); $cacheFile = $this->cachePath . '/' . $cacheKey . '.dat'; if ($this->cached) { $mtime = filemtime($ref->getFileName()); // TODO: Cache check needs to consider class inheritance! if (is_file($cacheFile) && filemtime($cacheFile) > $mtime) { return new Router(@unserialize(file_get_contents($cacheFile))); } } $collector = new RouteCollector(); foreach ($ref->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { if ($method->isAbstract() || $method->isStatic()) { continue; } if (false === ($comment = $method->getDocComment())) { continue; } $match = NULL; if (!preg_match("'@route\\(\\s*([^\\)]*)\\s*\\)'iu", $comment, $match)) { continue; } $anno = $match[1]; if (!preg_match("'(?:^|,)(?:\\s*value\\s*=\\s*)?\\s*\"(?P<pattern>[^\"]+)\"'iu", $anno, $match)) { throw new \RuntimeException(sprintf('Invalid route pattern in: %s', $anno)); } $pattern = $match['pattern']; $name = NULL; if (preg_match("'(?:^|,)\\s*name\\s*=\\s*\"(?P<name>[^\"]*)\"'iu", $anno, $match)) { $name = trim($match['name']); } if ($name === NULL) { $name = ltrim(preg_replace_callback("'[A-Z]+'", function (array $match) { return '-' . strtolower($match[0]); }, $method->name), '-'); } $collector->addRoute($name, $pattern, $ref->name, $method->name); } if ($this->cached) { Filesystem::writeFile($cacheFile, serialize($collector)); } return new Router($collector); }
/** * Create the DI container instance. * * @param ScopeLoader $scopes * @return ContainerInterface */ protected function createContainer(ContainerModuleLoader $loader, ScopeLoader $scopes) { $contextCachePath = $this->cacheDirectory . DIRECTORY_SEPARATOR . $this->contextName; $cacheFile = $contextCachePath . DIRECTORY_SEPARATOR . 'container.php'; $containerTypeName = __NAMESPACE__ . '\\CompiledContainer'; $proxyPath = Filesystem::createDirectory($contextCachePath . DIRECTORY_SEPARATOR . 'scoped'); $scopedProxies = []; foreach ($scopes as $scope) { foreach ($scope->getProxyTypeNames() as $typeName) { $scopedProxies[] = $typeName; } } if (!is_file($cacheFile) || $this->cache->isModified()) { $builder = $this->createContainerBuilder(); foreach ($this->komponents as $komponent) { $komponent->build($builder); } foreach ($loader as $module) { $module->build($builder); } $this->build($builder); if ($this->isInstrumentationEnabled()) { $manager = $this->getManifest(); } else { $manager = new ReflectionTypeInfoManager(); } $compiler = new ContainerCompiler($manager, $containerTypeName); $code = $compiler->compile($builder, $proxyPath, $scopedProxies); Filesystem::writeFile($cacheFile, $code); } require_once $cacheFile; return new $containerTypeName($this->getContainerParams()); }
public function syncInstrumentation() { if (!$this->needsCheck && array_key_exists('instrumentor.hash', $this->cached) && array_key_exists('instrumentor.mtime', $this->cached)) { $this->dump['instrumentor.hash'] = $this->cached['instrumentor.hash']; $this->dump['instrumentor.mtime'] = $this->cached['instrumentor.mtime']; return; } $loader = $this->kernel->getInstrumentors(); $hash = $loader->getHash(); $min = $loader->getLastModified(); $this->dump['instrumentor.hash'] = $hash; $this->dump['instrumentor.mtime'] = $min; if (array_key_exists('instrumentor.hash', $this->cached) && $hash === $this->cached['instrumentor.hash']) { if (array_key_exists('instrumentor.mtime', $this->cached) && $min === $this->cached['instrumentor.mtime']) { return; } } $this->instrumentationModified = true; $nameBlacklistRegex = $loader->getBlacklistedPatternsRegex(); $manifest = $this->getManifest(); $manifest->beginTransaction(); try { $result = []; // Supertype-based blacklist filtering. $blackTypes = []; foreach ($loader->getBlacklistedTypes() as $type) { $blackTypes[strtolower($type)] = true; } foreach ($manifest->findSubtypes(array_keys($blackTypes)) as $type) { $blackTypes[$type] = true; } foreach ($loader as $instrumentor) { foreach ($instrumentor->getSelectors($manifest) as $query) { $result = array_merge($result, $manifest->executeQuery($query, $min)); } } foreach (array_keys($result) as $k) { if (isset($blackTypes[strtolower($k)]) || preg_match($nameBlacklistRegex, $k)) { unset($result[$k]); } } $ifile = $this->kernel->getCacheDirectory() . '/' . $this->contextName . '/instrument.php'; Filesystem::writeFile($ifile, '<?php return ' . var_export($result, true) . ';'); } catch (\Exception $e) { $manifest->rollBack(); throw $e; } $manifest->commit(); }
public function execute(InputInterface $input, OutputInterface $output) { $renderers = $this->view->getRenderers(function ($renderer) { return $renderer instanceof ExpressViewRenderer; }); if (empty($renderers)) { throw new \RuntimeException(sprintf('Express view renderer not found')); } $dir = $input->getOption('dir'); if ($dir === NULL) { $dir = 'resource/schema'; } if (!preg_match("'^/|(?:[^:\\\\/]+://)|(?:[a-z]:[\\\\/])'i", $dir)) { $dir = $this->directory . '/' . $dir; } $dir = Filesystem::normalizePath($dir); if (!is_dir($dir)) { $questionHelper = $this->getHelper('question'); $question = new ConfirmationQuestion(sprintf('Schema directory <info>%s</info> does not exist, dou you want to create it? [n] ', $dir), false); if (!$questionHelper->ask($input, $output, $question)) { return; } Filesystem::createDirectory($dir); } $renderer = array_pop($renderers); $namespace = $input->getArgument('namespace'); $catalogFile = $dir . '/catalog.xml'; $xml = new \DOMDocument('1.0', 'UTF-8'); $xml->preserveWhiteSpace = false; $xml->formatOutput = true; if (is_file($catalogFile)) { $xml->load($catalogFile); $catalogElement = $xml->documentElement; } else { $catalogElement = $xml->appendChild($xml->createElementNS(self::NS_CATALOG, 'c:catalog')); $catalogElement->appendChild($xml->createAttribute('prefer'))->appendChild($xml->createTextNode('public')); } $xpath = new \DOMXPath($xml); $xpath->registerNamespace('c', self::NS_CATALOG); $count = 0; $skipped = 0; foreach ($renderer->generateXmlSchemaBuilders() as $builder) { if (!$builder instanceof HelperXmlSchemaBuilder) { continue; } $ns = $builder->getNamespace(); if ($namespace != $ns) { continue; } $code = (string) $builder; $file = sprintf('%s/%s.xsd', $dir, str_replace(':', '-', $ns)); if (!is_file($file) || md5_file($file) !== md5($code)) { $count++; Filesystem::writeFile($file, $code); $output->writeln(''); $output->writeln(sprintf('<info>%s</info>', basename($file))); $output->writeln(sprintf(' Generated XML-Schema for namespace <comment>%s</comment>.', $ns)); } else { $skipped++; } $found = false; foreach ($xpath->query("/c:catalog/c:uri[@name='" . $ns . "']") as $el) { $found = $el ? true : false; } if (!$found) { $uriElement = $catalogElement->appendChild($xml->createElementNS(self::NS_CATALOG, 'c:uri')); $uriElement->appendChild($xml->createAttribute('name'))->appendChild($xml->createTextNode($ns)); $uriElement->appendChild($xml->createAttribute('uri'))->appendChild($xml->createTextNode(str_replace(':', '-', $ns) . '.xsd')); } } $output->writeln(''); $output->writeln(sprintf('Created <info>%u</info> schema files in directory <comment>%s</comment>', $count, $dir)); Filesystem::writeFile($catalogFile, $xml->saveXML()); }
/** * Compiles scoped proxy types and saves them on the filesystem. * * @param ContainerBuilder $builder * @param string $proxyCachePath * @param array<stribg> $additionalProxies * @return string */ protected function compileScopedProxies(ContainerBuilder $builder, $proxyCachePath, array $additionalProxies = []) { $code = "\t\tpublic function loadScopedProxy(\$typeName) {\n"; $code .= "\t\tswitch(\$typeName) {\n"; $proxyTypes = []; foreach ($builder->getProxyBindings() as $binding) { $ref = new \ReflectionClass($binding->getTypeName()); $proxyTypes[$ref->name] = $ref; } foreach ($additionalProxies as $add) { $ref = new \ReflectionClass($add); $proxyTypes[$ref->name] = $ref; } foreach ($proxyTypes as $ref) { $parent = $ref; $mtime = filemtime($ref->getFileName()); while ($parent = $ref->getParentClass()) { $mtime = max($mtime, filemtime($parent->getFileName())); } $file = $proxyCachePath . '/' . md5(strtolower($ref->name)) . '.php'; $create = !is_file($file) || filemtime($file) < $mtime; if ($create) { $proxyCode = '<?php' . "\n\n" . $this->proxyGenerator->generateProxyCode($ref); Filesystem::writeFile($file, $proxyCode); } $code .= "\t\t\tcase " . var_export($ref->name, true) . ":\n"; $code .= "\t\t\t\trequire_once " . var_export($file, true) . ";\n"; $code .= "\t\t\t\treturn \$typeName . '__scoped';\n"; $code .= "\t\t\t\tbreak;\n"; } $code .= "\t\t}\n"; $code .= "\t\treturn parent::loadScopedProxy(\$typeName);\n"; $code .= "\t\t}\n\n"; return $code; }
protected function execute(InputInterface $input, OutputInterface $output) { $file = $this->kernel->getCacheDirectory() . '/k2.optimized.php'; Filesystem::writeFile($file, $this->createCompiler()->compile()); }