getByType() public method

Resolves service by type.
public getByType ( $class, $need = TRUE ) : object
return object service or NULL
Ejemplo n.º 1
0
 /**
  * @return \Nette\Security\User
  */
 private function getUser()
 {
     if (!$this->user) {
         $this->user = $this->container->getByType(User::class);
     }
     return $this->user;
 }
Ejemplo n.º 2
0
 /** @inheritdoc */
 public function createEntity($entityClass, $arg = null)
 {
     if ($factory = $this->container->getByType($this->resolveEntityFactory($entityClass), false)) {
         return $factory->create($arg);
     }
     return new $entityClass($arg);
 }
Ejemplo n.º 3
0
 /**
  * @return Nette\Application\IResponse
  */
 public function run(Application\Request $request)
 {
     $this->request = $request;
     $httpRequest = $this->context->getByType('Nette\\Http\\IRequest');
     if (!$httpRequest->isAjax() && ($request->isMethod('get') || $request->isMethod('head'))) {
         $refUrl = clone $httpRequest->getUrl();
         $url = $this->context->getService('router')->constructUrl($request, $refUrl->setPath($refUrl->getScriptPath()));
         if ($url !== NULL && !$httpRequest->getUrl()->isEqual($url)) {
             return new Responses\RedirectResponse($url, Http\IResponse::S301_MOVED_PERMANENTLY);
         }
     }
     $params = $request->getParameters();
     if (!isset($params['callback'])) {
         throw new Application\BadRequestException("Parameter callback is missing.");
     }
     $params['presenter'] = $this;
     $callback = new Nette\Callback($params['callback']);
     $response = $callback->invokeArgs(Application\UI\PresenterComponentReflection::combineArgs($callback->toReflection(), $params));
     if (is_string($response)) {
         $response = array($response, array());
     }
     if (is_array($response)) {
         if ($response[0] instanceof \SplFileInfo) {
             $response = $this->createTemplate('Nette\\Templating\\FileTemplate')->setParameters($response[1])->setFile($response[0]);
         } else {
             $response = $this->createTemplate('Nette\\Templating\\Template')->setParameters($response[1])->setSource($response[0]);
         }
     }
     if ($response instanceof Nette\Templating\ITemplate) {
         return new Responses\TextResponse($response);
     } else {
         return $response;
     }
 }
Ejemplo n.º 4
0
 /**
  * @param Request $request
  * @return Response
  */
 public function doRequest($request)
 {
     $_COOKIE = $request->getCookies();
     $_SERVER = $request->getServer();
     $_FILES = $request->getFiles();
     $_SERVER['REQUEST_METHOD'] = $method = strtoupper($request->getMethod());
     $_SERVER['REQUEST_URI'] = $uri = str_replace('http://localhost', '', $request->getUri());
     $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
     if ($method === 'HEAD' || $method === 'GET') {
         $_GET = $request->getParameters();
         $_POST = [];
     } else {
         $_POST = $request->getParameters();
         $_GET = [];
     }
     $httpRequest = $this->container->getByType(IRequest::class);
     $httpResponse = $this->container->getByType(IResponse::class);
     if (!$httpRequest instanceof HttpRequest || !$httpResponse instanceof HttpResponse) {
         throw new Exception('Arachne\\Codeception\\DI\\CodeceptionExtension is not used or conflicts with another extension.');
     }
     $httpRequest->reset();
     $httpResponse->reset();
     try {
         ob_start();
         $this->container->getByType(Application::class)->run();
         $content = ob_get_clean();
     } catch (Exception $e) {
         ob_end_clean();
         throw $e;
     }
     $code = $httpResponse->getCode();
     $headers = $httpResponse->getHeaders();
     return new Response($content, $code, $headers);
 }
Ejemplo n.º 5
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $login = $input->getArgument('login');
     $password = $input->getArgument('password');
     $this->container->getByType('App\\Model\\UserManager')->add($login, $password);
     $output->writeln("User {$login} was added.");
 }
Ejemplo n.º 6
0
 public function createNew($arguments = array())
 {
     /** @var BaseFileEntity $entity */
     $entity = parent::createNew($arguments);
     $entity->setUser($this->container->getByType('Nette\\Security\\User'));
     return $entity;
 }
Ejemplo n.º 7
0
 public function configure(Template $template)
 {
     // translator
     if (($translator = $this->container->getByType('Nette\\Localization\\ITranslator', FALSE)) !== NULL) {
         $template->setTranslator($translator);
     }
     $template->registerHelperLoader(array($this->container->venne->helpers, "loader"));
 }
 /**
  * BasePresenterTester constructor.
  * @param string $presenterName  - etc. 'Front:GoodsChange:Goods'
  */
 public function __construct($presenterName)
 {
     $this->presenterName = $presenterName;
     $this->container = (require __DIR__ . '/../../../../app/bootstrap.php');
     $this->linkGenerator = $this->container->getByType('Nette\\Application\\LinkGenerator');
     $this->presenterFactory = $this->container->getByType('Nette\\Application\\IPresenterFactory');
     $this->authenticator = new Authenticator();
 }
Ejemplo n.º 9
0
 public static function createFromContainer(Container $context)
 {
     /** @var EntityManager $em */
     $em = $context->getByType(EntityManager::class);
     /** @var Configuration $conf */
     $conf = $context->getByType(Configuration::class);
     return new self($em, $conf, $context->getParameters()['tempDir']);
 }
Ejemplo n.º 10
0
 public function create() : Broker
 {
     $tagToService = function (array $tags) {
         return array_map(function (string $serviceName) {
             return $this->container->getService($serviceName);
         }, array_keys($tags));
     };
     $phpClassReflectionExtension = $this->container->getByType(PhpClassReflectionExtension::class);
     return new Broker(array_merge([$phpClassReflectionExtension], $tagToService($this->container->findByTag(self::PROPERTIES_CLASS_REFLECTION_EXTENSION_TAG))), array_merge([$phpClassReflectionExtension], $tagToService($this->container->findByTag(self::METHODS_CLASS_REFLECTION_EXTENSION_TAG))), $tagToService($this->container->findByTag(self::DYNAMIC_METHOD_RETURN_TYPE_EXTENSION_TAG)), $this->container->getByType(FunctionReflectionFactory::class));
 }
Ejemplo n.º 11
0
 /**
  * @return array
  */
 public function getServices()
 {
     if ($this->services) {
         return $this->services;
     }
     $services = [];
     foreach ($this->emails as $email) {
         $services[$email] = $this->container->getByType($email);
     }
     return $this->services = $services;
 }
Ejemplo n.º 12
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $db = $this->container->getByType('Nette\\Database\\Connection');
     try {
         $db->query(self::USERS_TABLE_DDL);
         $db->query(self::PACKAGES_TABLE_DDL);
         $output->writeln('App installed');
     } catch (\PDOException $e) {
         $output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
     }
 }
Ejemplo n.º 13
0
 public function getPanel()
 {
     $app = $this->container->getByType('Nette\\Application\\Application');
     $presenter = $app->getPresenter();
     $link = '/sallyx-bridges-stream-wrappers-nette-presenters/redis';
     if ($presenter !== NULL) {
         $link = $presenter->link(':SallyxBridgesStreamWrappersNettePresenters:Redis:');
     }
     $jsScript = file_get_contents(__DIR__ . '/assets/main.js');
     $jsScript = str_replace(array('%redisPresenterLink%', '%scheme%'), array($link, $this->scheme), $jsScript);
     return '<h1>Redis stream wrapper ' . $this->scheme . '://</h1>' . '<div class="nette-inner tracy-inner">' . '<style type="text/css">' . file_get_contents(__DIR__ . '/assets/style.css') . '</style>' . '<div class="sallyx-streamWrappers-fileBrowser ' . $this->scheme . '"></div>' . '<script type="text/javascript">' . $jsScript . '</script>' . '</div>';
 }
Ejemplo n.º 14
0
 /**
  * @param Builder $hateoasBuilder
  */
 private function addUrlGenerators(Builder &$hateoasBuilder)
 {
     if (!empty($this->config['urlGenerators'])) {
         $hasDefault = false;
         foreach ($this->config['urlGenerators'] as $name => $generator) {
             if (is_numeric($name) && !$hasDefault) {
                 $name = null;
                 $hasDefault = true;
             }
             $hateoasBuilder->setUrlGenerator($name, $this->container->getByType($generator));
         }
     }
 }
Ejemplo n.º 15
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output->writeln('building package.json...');
     $packages = explode(' ', $input->getArgument('packages'));
     $builder = $this->container->getByType('App\\Model\\Builder');
     $builder->build($packages, function ($type, $buffer) use($output) {
         if ($type === Process::ERR) {
             $output->writeln(sprintf('<error>%s</error>', $buffer));
         } else {
             $output->writeln(sprintf('<info>%s</info>', $buffer));
         }
     });
     $output->writeln('built package.json');
 }
Ejemplo n.º 16
0
 public function execute(\Closure $callback)
 {
     $this->sl = $this->createContainer($this->configs);
     try {
         call_user_func($callback, $this->sl, $this->logger);
     } finally {
         /** @var Nette\Http\Session $session */
         $session = $this->sl->getByType('Nette\\Http\\Session');
         if ($session->isStarted()) {
             $session->destroy();
         }
         $this->logger->outputFilter = NULL;
     }
 }
Ejemplo n.º 17
0
 /**
  * @param $destination
  * @param array $args
  * @return BrowserSession|Nette\Application\Request
  */
 public function presenter($destination = NULL, $args = array())
 {
     if ($destination !== NULL) {
         if (preg_match('~^\\:?([a-z0-9_]+)(:[a-z0-9_]+)*\\:?$~i', $destination)) {
             $args = array(0 => '//' . ltrim($destination, '/')) + func_get_args();
             $url = new Nette\Http\UrlScript(call_user_func_array(array($this->linkGenerator, 'link'), $args));
         } elseif (Nette\Utils\Validators::isUrl($destination)) {
             $url = new Nette\Http\UrlScript($destination);
         } else {
             $url = clone $this->httpServerUrl;
             $url->setPath($destination);
         }
         $this->url((string) $url);
         return $this;
     }
     $appRequest = NULL;
     $currentUrl = new Nette\Http\UrlScript($this->url());
     parse_str($currentUrl->query, $query);
     $router = $this->serviceLocator->getByType('Nette\\Application\\IRouter');
     /** @var Nette\Application\IRouter[]|Nette\Application\IRouter $router */
     if (!class_exists('Kdyby\\Console\\CliRouter')) {
         $appRequest = $router->match(new Nette\Http\Request($currentUrl, $query, array(), array(), array(), array(), 'GET'));
     } else {
         foreach ($router as $route) {
             if ($route instanceof Kdyby\Console\CliRouter || $route instanceof Nette\Application\Routers\CliRouter) {
                 continue;
             }
             if ($appRequest = $route->match(new Nette\Http\Request($currentUrl, $query, array(), array(), array(), array(), 'GET'))) {
                 break;
             }
         }
     }
     return $appRequest;
 }
Ejemplo n.º 18
0
 /**
  * @return User
  */
 protected function getUser()
 {
     if (!$this->_user) {
         $this->_user = $this->container->getByType('Nette\\Security\\User');
     }
     return $this->_user;
 }
Ejemplo n.º 19
0
 public function getPresenterFactory()
 {
     if ($this->presenterFactory === NULL) {
         $this->presenterFactory = $this->context->getByType('Nette\\Application\\IPresenterFactory');
     }
     return $this->presenterFactory;
 }
Ejemplo n.º 20
0
 /**
  * @param \Nette\DI\Container $dic
  * @throws MemberAccessException
  * @internal
  */
 public function injectComponentFactories(Nette\DI\Container $dic)
 {
     if (!$this instanceof Nette\Application\UI\PresenterComponent && !$this instanceof Nette\Application\UI\Component) {
         throw new MemberAccessException('Trait ' . __TRAIT__ . ' can be used only in descendants of PresenterComponent.');
     }
     $this->autowireComponentFactoriesLocator = $dic;
     $storage = $dic->hasService('autowired.cacheStorage') ? $dic->getService('autowired.cacheStorage') : $dic->getByType('Nette\\Caching\\IStorage');
     $cache = new Nette\Caching\Cache($storage, 'Kdyby.Autowired.AutowireComponentFactories');
     if ($cache->load($presenterClass = get_class($this)) !== NULL) {
         return;
     }
     $ignore = class_parents('Nette\\Application\\UI\\Presenter') + ['ui' => 'Nette\\Application\\UI\\Presenter'];
     $rc = new ClassType($this);
     foreach ($rc->getMethods() as $method) {
         if (in_array($method->getDeclaringClass()->getName(), $ignore, TRUE) || !Strings::startsWith($method->getName(), 'createComponent')) {
             continue;
         }
         foreach ($method->getParameters() as $parameter) {
             if (!($class = $parameter->getClassName())) {
                 // has object type hint
                 continue;
             }
             if (!$this->findByTypeForFactory($class) && !$parameter->allowsNull()) {
                 throw new MissingServiceException("No service of type {$class} found. Make sure the type hint in {$method} is written correctly and service of this type is registered.");
             }
         }
     }
     $files = array_map(function ($class) {
         return ClassType::from($class)->getFileName();
     }, array_diff(array_values(class_parents($presenterClass) + ['me' => $presenterClass]), $ignore));
     $files[] = ClassType::from($this->autowireComponentFactoriesLocator)->getFileName();
     $cache->save($presenterClass, TRUE, [$cache::FILES => $files]);
 }
Ejemplo n.º 21
0
 /**
  * Registers 'addPaymentButtons' & 'addPaymentButton' methods to form using DI container
  *
  * @param Container $container
  */
 public static function registerAddPaymentButtonsUsingDependencyContainer(Container $container)
 {
     $binder = $container->getByType(Binder::class);
     $services = $container->findByType(AbstractPaymentService::class);
     foreach ($services as $service) {
         self::registerAddPaymentButtons($binder, $container->getService($service));
     }
 }
Ejemplo n.º 22
0
 /**
  * @return \Nette\Http\SessionSection
  */
 private function getSession()
 {
     if (is_null($this->session)) {
         /** @var \Nette\Http\Session $session */
         $session = $this->container->getByType("\\Nette\\Http\\Session");
         $this->session = $session->getSection($this->name);
     }
     return $this->session;
 }
Ejemplo n.º 23
0
 public function prepareDatabaseTest()
 {
     $this->lock();
     $this->em->clear();
     $migrationConfig = $this->context->getByType(Configuration::class);
     /** @var Configuration $migrationConfig */
     $migration = new Migration($migrationConfig);
     try {
         $migration->migrate();
     } catch (MigrationException $ex) {
         if ($ex->getCode() !== 4) {
             // no migrations found; this should not break tests in early stages of development,
             // the tests will fail when they require a model anyway
             throw $ex;
         }
     }
     $this->clearDatabase();
 }
Ejemplo n.º 24
0
 public function createPresenter($name)
 {
     $class = $this->getPresenterClass($name);
     if (($service = $this->container->getByType($class, false)) !== NULL) {
         $presenter = $service;
     } else {
         $presenter = $this->container->createInstance($class);
     }
     foreach (array_reverse(get_class_methods($presenter)) as $method) {
         if (substr($method, 0, 6) === 'inject') {
             $this->container->callMethod([$presenter, $method]);
         }
     }
     if ($presenter instanceof UI\Presenter && $presenter->invalidLinkMode === NULL) {
         $presenter->invalidLinkMode = $this->container->parameters['debugMode'] ? UI\Presenter::INVALID_LINK_WARNING : UI\Presenter::INVALID_LINK_SILENT;
     }
     return $presenter;
 }
Ejemplo n.º 25
0
 public function __construct($appDir, Nette\DI\Container $container, Nette\Localization\ITranslator $translator, Nette\Http\Response $httpResponse, Nette\Http\Request $httpRequest, Nette\Caching\IStorage $netteCacheStorage)
 {
     $this->container = $container;
     $this->latteFactory = $container->getByType('Nette\\Bridges\\ApplicationLatte\\ILatteFactory');
     $this->translator = $translator;
     $this->appDir = $appDir;
     $this->httpResponse = $httpResponse;
     $this->httpRequest = $httpRequest;
     $this->netteCacheStorage = $netteCacheStorage;
 }
Ejemplo n.º 26
0
 public function _after(TestInterface $test)
 {
     if ($this->container) {
         try {
             $this->container->getByType(Session::class)->close();
         } catch (MissingServiceException $e) {
         }
         try {
             $journal = $this->container->getByType(IJournal::class);
             if ($journal instanceof SQLiteJournal) {
                 $property = new ReflectionProperty(SQLiteJournal::class, 'pdo');
                 $property->setAccessible(true);
                 $property->setValue($journal, null);
             }
         } catch (MissingServiceException $e) {
         }
         FileSystem::delete(realpath($this->container->getParameters()['tempDir']));
     }
 }
Ejemplo n.º 27
0
 /**
  * @return Nette\Application\IResponse
  */
 public function run(Application\Request $request)
 {
     $this->request = $request;
     if ($this->httpRequest && $this->router && !$this->httpRequest->isAjax() && ($request->isMethod('get') || $request->isMethod('head'))) {
         $refUrl = clone $this->httpRequest->getUrl();
         $url = $this->router->constructUrl($request, $refUrl->setPath($refUrl->getScriptPath()));
         if ($url !== NULL && !$this->httpRequest->getUrl()->isEqual($url)) {
             return new Responses\RedirectResponse($url, Http\IResponse::S301_MOVED_PERMANENTLY);
         }
     }
     $params = $request->getParameters();
     if (!isset($params['callback'])) {
         throw new Application\BadRequestException('Parameter callback is missing.');
     }
     $callback = $params['callback'];
     $reflection = Nette\Utils\Callback::toReflection(Nette\Utils\Callback::check($callback));
     if ($this->context) {
         foreach ($reflection->getParameters() as $param) {
             if ($param->getClass()) {
                 $params[$param->getName()] = $this->context->getByType($param->getClass()->getName(), FALSE);
             }
         }
     }
     $params['presenter'] = $this;
     $params = Application\UI\ComponentReflection::combineArgs($reflection, $params);
     $response = call_user_func_array($callback, $params);
     if (is_string($response)) {
         $response = [$response, []];
     }
     if (is_array($response)) {
         list($templateSource, $templateParams) = $response;
         $response = $this->createTemplate()->setParameters($templateParams);
         if (!$templateSource instanceof \SplFileInfo) {
             $response->getLatte()->setLoader(new Latte\Loaders\StringLoader());
         }
         $response->setFile($templateSource);
     }
     if ($response instanceof Application\UI\ITemplate) {
         return new Responses\TextResponse($response);
     } else {
         return $response;
     }
 }
Ejemplo n.º 28
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $tempDir = $this->context->parameters['tempDir'];
     //$downloader	 = $this->context->getByType(Downloader::class);
     $zip = $this->downloader->download();
     $tempFile = $tempDir . '/translations.zip';
     file_put_contents($tempFile, $zip);
     $unzip = new Unzip();
     try {
         $unzip->extract($tempFile, $this->outputFolder);
         $catalogueCompiler = $this->context->getByType(CatalogueCompiler::class);
         $catalogueCompiler->invalidateCache();
         $output->writeln('<info>Downloaded</info>');
     } catch (\Exception $e) {
         $output->writeln('<error>' . $e->getMessage() . '</error>');
     } finally {
         unlink($tempFile);
     }
 }
Ejemplo n.º 29
0
 /**
  * @return Nette\Application\IResponse
  */
 public function run(Application\Request $request)
 {
     $this->request = $request;
     $httpRequest = $this->context->getByType('Nette\\Http\\IRequest');
     if (!$httpRequest->isAjax() && ($request->isMethod('get') || $request->isMethod('head'))) {
         $refUrl = clone $httpRequest->getUrl();
         $url = $this->context->getByType('Nette\\Application\\IRouter')->constructUrl($request, $refUrl->setPath($refUrl->getScriptPath()));
         if ($url !== NULL && !$httpRequest->getUrl()->isEqual($url)) {
             return new Responses\RedirectResponse($url, Http\IResponse::S301_MOVED_PERMANENTLY);
         }
     }
     $params = $request->getParameters();
     if (!isset($params['callback'])) {
         throw new Application\BadRequestException('Parameter callback is missing.');
     }
     $params['presenter'] = $this;
     $callback = $params['callback'];
     $reflection = Nette\Utils\Callback::toReflection(Nette\Utils\Callback::check($callback));
     $params = Application\UI\PresenterComponentReflection::combineArgs($reflection, $params);
     foreach ($reflection->getParameters() as $param) {
         if ($param->getClassName()) {
             unset($params[$param->getPosition()]);
         }
     }
     $params = Nette\DI\Helpers::autowireArguments($reflection, $params, $this->context);
     $response = call_user_func_array($callback, $params);
     if (is_string($response)) {
         $response = array($response, array());
     }
     if (is_array($response)) {
         if ($response[0] instanceof \SplFileInfo) {
             $response = $this->createTemplate('Nette\\Templating\\FileTemplate')->setParameters($response[1])->setFile($response[0]);
         } else {
             $response = $this->createTemplate('Nette\\Templating\\Template')->setParameters($response[1])->setSource($response[0]);
         }
     }
     if ($response instanceof Nette\Templating\ITemplate) {
         return new Responses\TextResponse($response);
     } else {
         return $response;
     }
 }
Ejemplo n.º 30
0
 public function indexEntities(ClassMetadata $searchMeta)
 {
     foreach ($this->searchManager->getMetadataFactory()->getAllMetadata() as $otherMeta) {
         if ($searchMeta->className === $otherMeta->className) {
             continue;
         }
         if (is_subclass_of($searchMeta->className, $otherMeta->className)) {
             $this->onChildSkipped($this, $searchMeta, $otherMeta);
             return;
         }
     }
     if ($searchMeta->riverImplementation) {
         $river = $this->serviceLocator->getByType($searchMeta->riverImplementation);
     } else {
         /** @var River\DefaultEntityRiver $river */
         $river = $this->serviceLocator->createInstance('Kdyby\\DoctrineSearch\\River\\DefaultEntityRiver');
     }
     if (!$river instanceof EntityRiver) {
         throw new UnexpectedValueException('The river must implement Doctrine\\Search\\EntityRiver.');
     }
     if (property_exists($river, 'onIndexStart')) {
         $river->onIndexStart[] = function (EntityRiver $river, $paginator, ORMMetadata $class) {
             $this->onIndexStart($this, $paginator, $river, $class);
         };
     }
     if (property_exists($river, 'onItemsIndexed')) {
         $river->onItemsIndexed[] = function ($self, $entities) {
             $this->onItemsIndexed($this, $entities);
         };
     }
     if (property_exists($river, 'onIndexStats')) {
         $river->onIndexStats[] = function ($self, ORMMetadata $class, $timeToIndex, $timeToRead) {
             $this->onIndexStats($this, $class, $timeToIndex, $timeToRead);
         };
     }
     // disable logger
     $config = $this->entityManager->getConfiguration();
     $oldLogger = $config->getSQLLogger();
     $config->setSQLLogger(NULL);
     $river->transfuse($searchMeta);
     $config->setSQLLogger($oldLogger);
 }