/** * {@inheritdoc} */ public function execute(callable $method, $arguments = []) { foreach ($arguments as $key => $value) { unset($arguments[$key]); $arguments[':' . $key] = $value; } try { return $this->auryn->execute($method, $arguments); } catch (InjectionException $e) { throw new DependencyInjectionException('Dependency injection failed while trying to execute ' . \var_export($method, true) . ', ' . $e->getMessage(), $e->getCode(), $e); } catch (ReflectionException $e) { throw new DependencyInjectionException('Dependency injection failed while trying to execute ' . \var_export($method, true) . ', ' . $e->getMessage(), $e->getCode(), $e); } }
public function testStageRunning() { $functionsCalled = []; $tiersByStage = new ExecutableListByTier(); $fn2 = function () use(&$functionsCalled) { $functionsCalled[2] = true; }; $fn0 = function () use(&$functionsCalled, $tiersByStage, $fn2) { $functionsCalled[0] = true; $tiersByStage->addExecutableToTier(4, $fn2); }; $fn1 = function () use(&$functionsCalled) { $functionsCalled[1] = true; }; $tiersByStage->addExecutableToTier(2, $fn0); $tiersByStage->addExecutableToTier(2, $fn1); $injector = new Injector(); foreach ($tiersByStage as $appStage => $executablesForTier) { foreach ($executablesForTier as $executable) { $injector->execute($executable->getCallable()); } } $this->assertArrayHasKey(0, $functionsCalled); $this->assertArrayHasKey(1, $functionsCalled); $this->assertArrayHasKey(2, $functionsCalled); }
public function makeClient(Injector $injector) { if (empty($this->env['chamber_api_secret'])) { throw new \DomainException('Bad API configuration'); } $handler = $injector->execute([$this, 'makeStack']); return new Client(compact('handler')); }
/** * @group blah */ public function testInclude() { $templateName = 'includeFile/includeTest'; $className = $this->jigDispatcher->getFQCNFromTemplateName($templateName); $this->jigDispatcher->compile($templateName); $contents = $this->injector->execute([$className, 'render']); $this->assertContains("Included start", $contents); $this->assertContains("Included end", $contents); $this->assertContains("This is an include test.", $contents); $this->assertContains("This is a foo", $contents); }
function generateCompare(\Auryn\Injector $injector, $functionFullname, $filename) { global $imageType; echo "Function " . $functionFullname . "\n"; ob_start(); $injector->execute($functionFullname); $image = ob_get_contents(); ob_end_clean(); $fullFilename = $filename . "." . strtolower($imageType); @mkdir(dirname($filename), 0755, true); file_put_contents($fullFilename, $image); }
public function testRouting405() { $request = new CLIRequest("/introduction", 'example.com', 'POST'); $this->injector->alias('Psr\\Http\\Message\\ServerRequestInterface', get_class($request)); $this->injector->share($request); $renderCallable = $this->injector->execute('Tier\\Bridge\\JigFastRouter::routeRequest'); $body = TierApp::executeExecutable($renderCallable, $this->injector); $this->assertInstanceOf('Room11\\HTTP\\Body\\TextBody', $body); /** @var $body \Room11\HTTP\Body\HtmlBody */ $html = $body->getData(); $this->assertContains("Method not allowed for route.", $html); $this->assertEquals(405, $body->getStatusCode()); }
function directImageCallable(CategoryNav $categoryNav, \Auryn\Injector $injector, $params) { $imageFunction = $categoryNav->getImageFunctionName(); $filename = getImageCacheFilename($categoryNav->getPageInfo(), $params); global $imageType; ob_start(); $injector->execute($imageFunction); if ($imageType == null) { ob_end_clean(); throw new \Exception("imageType not set, can't cache image correctly."); } $imageData = ob_get_contents(); ob_end_clean(); return new \ImagickDemo\Response\ImageResponse($filename, "image/" . $imageType, $imageData); }
public function directCustomImageCallable(PageInfo $pageInfo, RouteParams $routeInfo, \Auryn\Injector $injector, $params) { App::setupCategoryExample($routeInfo); $imageFunction = CategoryInfo::getCustomImageFunctionName($pageInfo); global $imageType; ob_start(); $injector->execute($imageFunction); if ($imageType == null) { ob_end_clean(); throw new \Exception("imageType not set, can't cache image correctly."); } $imageData = ob_get_contents(); ob_end_clean(); $simpleNameWithExtension = $pageInfo->getSimpleName($params) . '.' . $imageType; return new BlobBody($simpleNameWithExtension, $imageData, "image/" . $imageType); }
/** * @param $imageFunction * @param \Auryn\Injector $injector * @return \ImagickDemo\Response\ImageResponse * @throws \Exception */ function directImageFunction($filename, $imageFunction, \Auryn\Injector $injector) { $imageCallable = function () use($imageFunction, $injector) { try { return $injector->execute($imageFunction); } catch (\Exception $e) { echo "Exception: " . $e->getMessage(); exit(0); } }; return createImageResponse($filename, $imageCallable); }
function directCustomImageCallable(PageInfo $pageInfo, \Auryn\Injector $injector, $params) { $imageFunction = CategoryInfo::getCustomImageFunctionName($pageInfo); $filename = getImageCacheFilename($pageInfo, $params); global $imageType; ob_start(); $injector->execute($imageFunction); if ($imageType == null) { ob_end_clean(); throw new \Exception("imageType not set, can't cache image correctly."); } $imageData = ob_get_contents(); ob_end_clean(); return new DataBody($filename, $imageData, "image/" . $imageType); }
public function execute(ControllerEvent $event) { try { $params = $event->getParams(true) ?? []; $ajaxReq = $params['_contentType'] === 'ajax'; if ($params['_method'] === 'GET' && ($parents = $params['_parents'] ?? null)) { $alias = $ajaxReq ? $params['alias'] : null; if ($models = $this->modelLoader->loadModels($parents, $alias)) { $event->setParam('_models', $models); foreach ($models as $key => $value) { $event->setParam($key, $value); } } foreach ($parents as $key => $value) { $event->setParam("_{$key}", $models[$key] ?? []); } } $args = array_merge([':event' => $event], $event->getParams() ?? []); $action = $this->getController($event->getController()); $final = true; $response = $output = $this->injector->execute($action, $args); if ($response instanceof Redirection) { $this->dispatcher->fire(RedirectEvent::REDIRECT, new RedirectEvent($response)); //chance to do something with redirection $response->redirect(); //exists } else { if ($response instanceof HttpResponseEx) { $event->setResponse($this->response); } else { if ($response instanceof View) { if ($ajaxReq && !empty($alias) && !empty($models)) { $output = '{}'; /** @var CollectionEx $model */ foreach ($models as $tlp => $model) { if ($array = $model->toArray()) { if ($child = $tlp === $alias ? $array : $this->findChildByAlias($array, $alias)) { $output = json_encode($child, JSON_PRETTY_PRINT); } } } } else { /** @var View $view */ $view = $response; $final = $response->isFinal(); $this->viewParser->setHelpers($view->getHelpers()); $this->viewParser->setLayout($view->getLayout()); $this->viewParser->setAdditionalLayoutFiles($view->getAdditionalLayoutFiles()); $this->viewParser->setVars(array_merge($event->getParams(true) ?? [], $view->getVars() ?? [])); if ($content = $view->getContent()) { if (!empty($view->getViewFile())) { trigger_error('You should only specify either content or view file'); } $this->viewParser->setContent($content); } elseif ($templatePath = $view->getViewFile()) { $this->viewParser->loadViewFile($templatePath, $view->isPathLayouts()); } elseif (empty($view->getViewFile())) { if (is_string($event->getController())) { @(list($class) = explode('@', $event->getController(), 2)); $this->viewParser->loadViewFile($class, $view->isPathLayouts()); } else { throw new ControllerError("View must be explicitly set (when Controller is not a string)"); } } $output = $this->viewParser->render(); } } $this->response->setStatusCode(200); $this->response->setContent(is_string($output) ? $output : ''); $this->response->setFinal($final); $event->setResponse($this->response); } } } catch (InjectionException $e) { throw new ControllerError(sprintf("Unable to run controller: %s [%s]", $e->getMessage(), var_export($event->getController(), true))); } }
public function testAbstractExecute() { $injector = new Injector(); $fn = function () { return new \Auryn\Test\ConcreteExexcuteTest(); }; $injector->delegate('Auryn\\Test\\AbstractExecuteTest', $fn); $result = $injector->execute(array('Auryn\\Test\\AbstractExecuteTest', 'process')); $this->assertEquals('Concrete', $result); }
<?php use Auryn\Injector; use Jig\JigConfig; use Jig\Jig; // Register some directories in the autoloader - we don't do this in composer.json // to avoid any confusion with users of the library. $autoloader = (require_once realpath(__DIR__) . '/../vendor/autoload.php'); $autoloader->add('JigDemo', [realpath(__DIR__) . '/']); $autoloader->add('Jig', [realpath(__DIR__) . '/compile/']); $injector = new Injector(); // Setting the Jig config $jigConfig = new JigConfig(__DIR__ . "/templates/", __DIR__ . "/compile/", Jig::COMPILE_ALWAYS, "php.tpl"); // Tell the DIC that every class that needs an instance of JigConfig // should use this one. $injector->share($jigConfig); // Alias an interface to a concrete class so that it can be found in // the template. $injector->alias('JigDemo\\Model\\ColorScheme', '\\JigDemo\\Model\\PrimaryColorscheme'); // This is the template we will be compiling. $templateName = 'onePageExample'; // Create the Jig renderer $jig = new Jig($jigConfig); // Tell Jig to make sure the template is compiled. $jig->compile($templateName); // Get the classname that the template will be called $className = $jig->getFQCNFromTemplateName($templateName); // Call the template $contents = $injector->execute([$className, 'render']); echo $contents;
/** * */ public function execute() { //Figure out what Command was requested. try { $parsedCommand = $this->console->parseCommandLine(); } catch (ConfiguratorException $ce) { echo "Problem running configuration: " . $ce->getMessage(); exit(-1); } catch (\Exception $e) { //@TODO change to just catch parseException when that's implemented $output = new BufferedOutput(); $this->console->renderException($e, $output); echo $output->fetch(); exit(-1); } //Run the command requested, or the help callable if no command was input try { $output = $parsedCommand->getOutput(); $formatter = $output->getFormatter(); $formatter->setStyle('question', new OutputFormatterStyle('blue')); $formatter->setStyle('info', new OutputFormatterStyle('blue')); $questionHelper = new QuestionHelper(); $questionHelper->setHelperSet($this->console->getHelperSet()); // We currently have no config, so fine to create this directly. $injector = new Injector(); $injector->alias('Configurator\\Writer', 'Configurator\\Writer\\FileWriter'); $injector->defineParam('originalArgs', $this->originalArgs); foreach ($parsedCommand->getParams() as $key => $value) { $injector->defineParam($key, $value); } $injector->execute($parsedCommand->getCallable()); } catch (ConfiguratorException $ce) { echo "Error running task: \n"; echo $ce->getMessage(); exit(-1); } catch (\Exception $e) { echo "Unexpected exception of type " . get_class($e) . " running configurator`: " . $e->getMessage() . PHP_EOL; echo $e->getTraceAsString(); exit(-2); } }
function __invoke(Injector $injector) { return $injector->execute($this->callable); }
/** * Renders * @param $templateString string The template to compile. * @param $objectID string An identifying string to name the generated class and so the * generated PHP file. It must be a valid class name i.e. may not start with a digit. * @return string * @throws \Exception */ public function renderTemplateFromString($templateString, $objectID) { $className = $this->getParsedTemplateFromString($templateString, $objectID); $contents = $this->injector->execute([$className, 'render']); return $contents; }
/** * @param \Auryn\Injector $injector * @param $imageCallable * @param $filename * @return FileResponse * @throws \Exception */ public static function renderImageAsFileResponse($imageFunction, $filename, \Auryn\Injector $injector, $params) { global $imageType; try { ob_start(); $injector->execute($imageFunction, $params); if ($imageType == null) { ob_end_clean(); throw new \Exception("imageType not set, can't cache image correctly."); } $image = ob_get_contents(); ob_end_clean(); @mkdir(dirname($filename), 0755, true); $fullFilename = $filename . "." . strtolower($imageType); if (!strlen($image)) { throw new \Exception("Image generated was empty for {$imageFunction}."); } $fileWritten = @file_put_contents($fullFilename, $image); if ($fileWritten === false) { throw new \Exception("Failed to write file {$fullFilename}"); } if ($fileWritten === 0) { throw new \Exception("Image was empty when written to {$fullFilename} ."); } return [$fullFilename, $imageType]; } finally { while (ob_get_level() > 0) { ob_end_flush(); } } }