Ejemplo n.º 1
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $questionHelper = $this->getHelper('question');
     if (!is_dir($this->directory)) {
         $question = new ConfirmationQuestion(sprintf('Migration directory <info>%s</info> does not exist, dou you want to create it? [n] ', $this->directory), false);
         if (!$questionHelper->ask($input, $output, $question)) {
             return;
         }
         Filesystem::createDirectory($this->directory);
     }
     if (!is_writable($this->directory)) {
         $output->writeln(sprintf('<error>Migration directory %s is not writable</error>', $this->directory));
         return;
     }
     $date = new \DateTime('@' . time());
     $date->setTimezone(new \DateTimeZone('UTC'));
     $class = 'Version' . $date->format('YmdHis');
     $file = $class . '.php';
     $tpl = ['###CLASS###' => $class, '###DATE###' => $date->format('Y-m-d H:i:s') . ' UTC'];
     $code = strtr(file_get_contents(__DIR__ . '/MigrationTemplate.txt'), $tpl);
     $target = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $this->directory . '/' . $file);
     $question = new ConfirmationQuestion(sprintf('Generate migration <info>%s</info>? [y] ', $target), true);
     if (!$questionHelper->ask($input, $output, $question)) {
         return;
     }
     if (false === file_put_contents($target, $code)) {
         $output->writeln(sprintf('<error>Failed to write migration %s to disk.</error>', $target));
         return;
     }
     $output->writeln(sprintf('  Migration <info>%s</info> generated.', $target));
 }
Ejemplo n.º 2
0
 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;
 }
Ejemplo n.º 3
0
 public function getMediaType()
 {
     if ($this->info->isDir()) {
         return new MediaType('httpd/unix-directory');
     }
     return new MediaType(Filesystem::guessMimeTypeFromFilename($this->info->getFilename()));
 }
 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));
 }
Ejemplo n.º 5
0
 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;
 }
Ejemplo n.º 6
0
 /**
  * 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;
 }
Ejemplo n.º 7
0
 /**
  * {@inheritdoc}
  */
 public function processSource($contents, FileSource $source)
 {
     $file = $source->getFileInfo();
     $contents = preg_replace_callback("'(\\Wurl\\s*\\()([^\\)]+)\\)'i", function (array $m) use($file) {
         $url = trim($m[2], '"\'');
         if (preg_match("'^[^:]+://.+'", $url)) {
             return $m[0];
         }
         $base = dirname($file->getPathname());
         $loc = $base . '/' . ltrim($url, '/\\');
         $loc = preg_replace("'[^/]+/\\.\\./'", '', $loc);
         $params = [];
         if (false !== strpos($loc, '?')) {
             list($loc, $tmp) = explode('?', $loc, 2);
             parse_str($tmp, $params);
         }
         if ($this->publisher->isPublic($loc)) {
             return $m[1] . "'" . $this->publisher->getResourceUri($loc, $params) . "')";
         }
         if (!is_file($loc)) {
             throw new \OutOfBoundsException(sprintf('Resource "%s" referenced by "%s" was not found', $loc, $file->getPathname()));
         }
         if (false === ($embed = @file_get_contents($loc))) {
             throw new \OutOfBoundsException(sprintf('Unable to load contents of resource "%s" embedded into "%s"', $loc, $file->getPathname()));
         }
         return sprintf("%s'data:%s;base64,%s')", $m[1], Filesystem::guessMimeTypeFromFilename($loc), base64_encode($embed));
     }, $contents);
     return $contents;
 }
Ejemplo n.º 8
0
 /**
  * {@inheritdoc}
  */
 public function prepareMessage(HttpMessage $message) : HttpMessage
 {
     if (!$message->hasHeader('Content-Type')) {
         $message = $message->withHeader('Content-Type', Filesystem::guessMimeTypeFromFilename($this->file));
     }
     return $message;
 }
Ejemplo n.º 9
0
 /**
  * {@inheritdoc}
  */
 public function generate($name, array $params = [], $style = self::ABSOLUTE_URI)
 {
     if ('/' !== substr($name, 0, 1)) {
         $match = $this->context->getRouteMatch();
         if ($match !== NULL) {
             $name = rtrim('/' . implode('/', explode('/', $match->getRouteName())), '/') . '/' . $name;
         }
     }
     $name = Filesystem::normalizePath('/' . trim($name, '/'));
     if ($name === '/') {
         switch ($style) {
             case self::ABSOLUTE_PATH:
                 return new UriInfo(rtrim('/' . $this->context->getRequest()->getPathBase(), '/') . '/');
             case self::ABSOLUTE_URI:
                 return new UriInfo(rtrim($this->context->getRequest()->getBaseUri(), '/') . '/');
             case self::NETWORK_PATH:
                 return new UriInfo(rtrim($this->context->getRequest()->getBaseUri()->setScheme(NULL), '/') . '/');
         }
         throw new \InvalidArgumentException(sprintf('Invalid URI generation style: "%s"', $style));
     }
     // Iterative route lookup:
     $router = $this->router;
     $info = NULL;
     foreach (explode('/', trim($name, '/')) as $step) {
         if ($info === NULL) {
             $info = $router->getRoute($step);
         } else {
             $info = $info->append($router->getRoute($step));
         }
         $handler = $info->getHandler();
         if ($handler instanceof DispatchableMountHandler) {
             break;
         } elseif ($handler instanceof MountHandler) {
             if (NULL !== ($router = $handler->getRouter())) {
                 continue;
             }
             $router = $this->dispatcher->publishUntil(new LoadMountedRouterEvent($handler), function ($result) {
                 return $result instanceof Router;
             });
             if ($router === NULL) {
                 throw new \RuntimeException(sprintf('No router could be loaded for mount %s', get_class($handler)));
             }
             $handler->setRouter($router);
         }
     }
     $info = $this->resolveParams($info, $params);
     if ($style == self::ABSOLUTE_PATH) {
         return $info->prepend(rtrim('/' . $this->context->getRequest()->getPathBase(), '/'));
     }
     if ($style == self::ABSOLUTE_URI) {
         return $info->prepend(rtrim($this->context->getRequest()->getBaseUri(), '/'));
     }
     if ($style == self::NETWORK_PATH) {
         return $info->prepend(rtrim($this->context->getRequest()->getBaseUri()->setScheme(NULL), '/'));
     }
     throw new \InvalidArgumentException(sprintf('Invalid URI generation style: "%s"', $style));
 }
Ejemplo n.º 10
0
 public function __construct($filename, StreamInterface $stream, $mediaType = NULL)
 {
     if (!$stream->isReadable()) {
         throw new \InvalidArgumentException(sprintf('Input stream of file "%s" must be readable'));
     }
     $this->fileName = new UnicodeString($filename);
     $this->stream = $stream;
     $this->mediaType = $mediaType === NULL ? Filesystem::guessMimeTypeFromFilename($this->fileName) : new MediaType($mediaType);
 }
Ejemplo n.º 11
0
 /**
  * Create HTTP file response.
  * 
  * @param string $file Absolute path of the file to be transfered.
  * @param string $type Media type of the file (will be guessed from extension if not provided).
  * @param string $charset Charset to be supplied when media type is text format.
  */
 public function __construct(string $file, string $type = null, string $charset = null)
 {
     $type = new ContentType($type ?? Filesystem::guessMimeTypeFromFilename($file));
     if ($type->getMediaType()->isText()) {
         $type->setParam('charset', $charset ?? 'utf-8');
     }
     parent::__construct(Http::OK, ['Content-Type' => (string) $type]);
     $this->body = new FileBody($file);
     $this->file = $file;
 }
Ejemplo n.º 12
0
 public function prepare(HttpMessage $message)
 {
     parent::prepare($message);
     if (!$message->hasHeader('Content-Type')) {
         $message->setHeader('Content-Type', Filesystem::guessMimeTypeFromFilename($this->file->getPathname()));
     }
     if ($this->download) {
         $message->setHeader('Content-Disposition', sprintf('attachement; filename="%s"', str_replace(['\'', '"'], '', $this->file->getFilename())));
     }
 }
Ejemplo n.º 13
0
 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;
 }
 public function process(DispatchRequest $dispatch)
 {
     if (!$dispatch->isMaster()) {
         return $dispatch->proceed();
     }
     $request = $dispatch->getHttpRequest();
     $path = $request->getPathInfo();
     $m = NULL;
     if (!preg_match("'^_res/+(.+)\$'i", $path, $m)) {
         return $dispatch->proceed();
     }
     $path = $m[1];
     if ('app/' === substr($path, 0, 4)) {
         $resource = 'k2://app/' . substr($path, 4);
     } else {
         $parts = explode('/', $path, 2);
         if (count($parts) !== 2) {
             return new HttpResponse(Http::CODE_NOT_FOUND);
         }
         $resource = 'k2://' . $parts[0] . '/' . $parts[1];
     }
     if (!is_file($resource)) {
         return new HttpResponse(Http::CODE_NOT_FOUND);
     }
     if (!$this->publisher->isPublic($resource)) {
         return new HttpResponse(Http::CODE_FORBIDDEN);
     }
     $response = new HttpResponse();
     // Conditional caching:
     $etag = sprintf('"%x-%x"', filemtime($resource), filesize($resource));
     $response->setHeader('Access-Control-Allow-Origin', '*');
     $response->setHeader('Cache-Control', 'public, max-age=7200');
     $response->setHeader('ETag', $etag);
     $response->setHeader(new ExpiresHeader(new \DateTimeImmutable('@' . (time() + 7200))));
     if ($etag === $request->getHeader('If-None-Match', '')) {
         $response->setStatus(Http::CODE_NOT_MODIFIED);
         return $response;
     }
     $mediaType = new MediaType(Filesystem::guessMimeTypeFromFilename($resource));
     $response->setHeader('X-Content-Type-Options', 'nosniff');
     if ($mediaType->isType('text')) {
         $response->setHeader('Content-Type', $mediaType . '; charset="utf-8"');
     } else {
         $response->setHeader('Content-Type', (string) $mediaType);
     }
     $response->setEntity(new FileEntity(new \SplFileInfo($resource)));
     return $response;
 }
Ejemplo n.º 15
0
 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);
 }
Ejemplo n.º 16
0
 public function getResource($resource)
 {
     $dir = Filesystem::normalizePath($this->directory);
     if ($resource === NULL || $resource === '') {
         return $dir . '/resource';
     }
     $entry = Filesystem::normalizePath($this->directory . '/resource/' . ltrim($resource, '/\\'));
     if (!file_exists($entry)) {
         throw new \RuntimeException(sprintf('Resource "%s" not found in komponent "%s"', $resource, $this->getKey()));
     }
     if ($entry == $dir) {
         return $entry;
     }
     if (0 !== strpos($entry, $dir . '/')) {
         throw new \RuntimeException(sprintf('Resource "%s" is not accessible by komponent "%s"', $resource, $this->getKey()));
     }
     return $entry;
 }
Ejemplo n.º 17
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if (NULL !== ($file = $input->getOption('file'))) {
         if (is_file($file) && !$input->getOption('overwrite')) {
             $output->writeln(sprintf('File <info>%s</info> already exists, use option <comment>-o</comment> to overwrite it.', $file));
             return;
         }
         $fp = Filesystem::openWriteStream($file);
         foreach (explode("\n", trim($this->config)) as $line) {
             fwrite($fp, $line . "\n");
         }
         fclose($fp);
         $output->writeln(sprintf('Config dumped to <info>%s</info>', $file));
     } else {
         foreach (explode("\n", trim($this->config)) as $line) {
             $output->writeln($line);
         }
     }
 }
 public function create(Configuration $config)
 {
     $cachePath = $config->getString('cachePath', NULL);
     $createFolder = $config->getBoolean('createFolder', false);
     if ($cachePath !== NULL) {
         if (!is_dir($cachePath)) {
             if (!$createFolder) {
                 throw new \RuntimeException(sprintf('Cache directory not found: "%s"', $cachePath));
             }
             $cachePath = Filesystem::createDirectory($cachePath);
         }
         if (!is_readable($cachePath)) {
             throw new \RuntimeException(sprintf('Cache directory not readable: "%s"', $cachePath));
         }
         if (!is_writable($cachePath)) {
             throw new \RuntimeException(sprintf('Cache directory not writable: "%s"', $cachePath));
         }
     }
     return new ExpressViewFactory($cachePath, $this->logger);
 }
Ejemplo n.º 19
0
 /**
  * Check if the HTTP request matches a public file and server it as needed.
  * 
  * @param HttpRequest $request
  * @param NextMiddleware $next
  * @return HttpResponse
  */
 public function __invoke(HttpRequest $request, NextMiddleware $next) : \Generator
 {
     static $methods = [Http::HEAD, Http::GET];
     if (!\in_array($request->getMethod(), $methods, true)) {
         return yield from $next($request);
     }
     $path = '/' . \trim($request->getRequestTarget(), '/');
     if ($this->basePath !== '/') {
         if (0 !== \strpos($path, $this->basePath)) {
             return yield from $next($request);
         }
         $path = \substr($path, \strlen($this->basePath) - 1);
     }
     $file = Filesystem::normalizePath($this->directory . \substr($path, 1));
     if (0 !== \strpos($file, $this->directory)) {
         return yield from $next($request);
     }
     if (!(yield LoopConfig::currentFilesystem()->isFile($file))) {
         return yield from $next($request);
     }
     return $this->createResponse($request, $file);
 }
Ejemplo n.º 20
0
 public function getContainerParams()
 {
     $params = parent::getContainerParams();
     $params['kernel.path.data'] = Filesystem::createDirectory($this->directory . DIRECTORY_SEPARATOR . 'data');
     foreach ($this->testLoader->findRules() as $rule) {
         $params = array_merge($params, (array) $rule->loadContainerParams());
     }
     return array_merge($params, (array) $this->testLoader->loadContainerParams());
 }
Ejemplo n.º 21
0
 /**
  * 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;
 }
Ejemplo n.º 22
0
 /**
  * Create a new unit config.
  * 
  * @param string $file Config file.
  * @param int $priority Loading priority.
  * @param string $unitName Unit name (should be identical to the root namespace of your package).
  */
 public function __construct(string $file, int $priority = 0, string $unitName = '')
 {
     $this->file = Filesystem::normalizePath($file);
     $this->priority = $priority;
     $this->unitName = $unitName;
 }
Ejemplo n.º 23
0
 public function render(ViewModelInterface $model, $onlyEntity = false)
 {
     $m = NULL;
     if (!preg_match("'.+\\.([a-z0-9]+)\\.xml\$'i", $model->getResource(), $m)) {
         throw new \RuntimeException(sprintf('Unable to determine output format of view "%s"', $model->getResource()));
     }
     $typeName = $this->factory->createView($this, $model->getResource());
     $view = new $typeName($this->factory, $this);
     $response = new HttpResponse();
     $format = strtolower($m[1]);
     $out = $view->render(new OutputBuffer(), $model, ['@format' => $format, '@response' => $response]);
     if ($onlyEntity) {
         return (string) $out;
     }
     if (!$response->hasHeader('Content-Type')) {
         $type = new MediaType(Filesystem::guessMimeTypeFromFilename($format));
         if ($type->isText()) {
             $response->setHeader('Content-Type', $type . '; charset="utf-8"');
         } else {
             $response->setHeader('Content-Type', $type);
         }
         if ($type->is('*/xml')) {
             $out = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $out;
         }
     }
     return $response->setEntity(ltrim($out));
 }
Ejemplo n.º 24
0
 protected function buildResource(ContainerBuilder $builder)
 {
     $builder->bind(ResourcePublisherInterface::class)->scoped(new Singleton())->to(function (KernelInterface $kernel) {
         if (PHP_SAPI == 'cli') {
             return new DomainResourcePublisher('//test.me/');
         }
         $env = $kernel->getEnvironment();
         return new DomainResourcePublisher(sprintf('//%s%s/', $env->getHost(), rtrim('/' . $env->getBaseUri()->getPath())));
     })->initialize(function (ResourcePublisherInterface $publisher, KernelInterface $kernel) {
         foreach ($kernel->getConfiguration()->getConfig('KoolKode.Http.Komponent.Resource.blacklist') as $pattern) {
             $publisher->addBlacklistPattern($pattern);
         }
     });
     $builder->bind(ResourceDeliveryMiddleware::class)->marked(new Middleware(PHP_INT_MAX - 1000));
     $builder->bind(PipelineManagerInterface::class)->scoped(new ApplicationScoped())->to(PipelineManager::class);
     $builder->bind(PipelineController::class)->marked(new Dispatchable('/_pipeline/{identifier}-{hash}', '_pipeline'))->initialize(function (PipelineController $controller, Configuration $config) {
         $dir = $config->get('cachePath', NULL);
         if ($dir !== NULL) {
             if (!is_dir($dir)) {
                 Filesystem::createDirectory($dir);
             }
             $controller->setCachePath($dir);
         }
     });
     $builder->bind(ResourceExpressionExtension::class)->marked(new ExpressionExtension());
 }
Ejemplo n.º 25
0
 /**
  * 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());
 }
Ejemplo n.º 26
0
 public static function locateFileSync(string $path, array $paths) : string
 {
     if ('k1://' === \substr($path, 0, 5)) {
         $normalized = \substr($path, 5);
     } else {
         $normalized = $path;
         $path = 'k1://' . $path;
     }
     $normalized = Filesystem::normalizePath($normalized);
     if (0 === \strpos($normalized, 'app/')) {
         $package = 'app';
         $sub = \substr($normalized, 4);
     } else {
         $m = null;
         if (!\preg_match("'^([^/\\.]+/[^/\\.]+)/(.+)\$'", $normalized, $m)) {
             throw new ResourceNotFoundException(\sprintf('Invalid resource location: "%s" (%s)', $path, $normalized));
         }
         $package = $m[1];
         $sub = $m[2];
     }
     if (empty($paths[$package])) {
         throw new ResourceNotFoundException(\sprintf('Provider not loaded: "%s"', $package));
     }
     foreach ($paths[$package] as $base) {
         $file = $base . '/' . $sub;
         if (\is_file($file)) {
             return $file;
         }
     }
     throw new ResourceNotFoundException(\sprintf('Resource not found: "%s"', $path));
 }
Ejemplo n.º 27
0
 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();
 }
Ejemplo n.º 28
0
 public function createResource(ResourceInterface $parent, $name, StreamInterface $stream)
 {
     $id = $this->storeResource($parent, $name);
     $size = 0;
     $md5 = NULL;
     $this->storeResourceContents($id, $stream, $size, $md5);
     $this->conn->insert('#__webdav_file', ['resource_id' => $id, 'size' => $size, 'md5' => new StringStream(hex2bin($md5)), 'media_type' => Filesystem::guessMimeTypeFromFilename($name)]);
     return $this->getByIdentifier($id);
 }
 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());
 }
Ejemplo n.º 30
0
 /**
  * Create a new unit that loads DI container object configuration from the given file.
  * 
  * @param string $file DI container object config file.
  * @param int $priority Loading priority.
  */
 public function __construct(string $file, int $priority = 0)
 {
     $this->file = Filesystem::normalizePath($file);
     $this->priority = $priority;
 }