public function testHasServiceWithoutConfig() { $this->serviceManager = new ServiceManager\ServiceManager(new ServiceManagerConfig(['abstract_factories' => ['AclMan\\Storage\\StorageFactory']])); $this->assertFalse($this->serviceManager->has('AclStorage')); $this->serviceManager = new ServiceManager\ServiceManager(new ServiceManagerConfig(['abstract_factories' => ['AclMan\\Storage\\StorageFactory']])); $this->serviceManager->setService('Config', []); $this->assertFalse($this->serviceManager->has('AclStorage')); }
public function testMongoAdapterAbstractServiceFactorEmptyConfig() { $this->serviceManager = new ServiceManager\ServiceManager(new ServiceManagerConfig(['abstract_factories' => ['ImgMan\\Storage\\Adapter\\Mongo\\MongoAdapterAbstractServiceFactory', 'ImgMan\\Storage\\Adapter\\Mongo\\MongoDbAbstractServiceFactory']])); $this->assertFalse($this->serviceManager->has('ImgMan\\Storage\\Mongo')); $this->serviceManager = new ServiceManager\ServiceManager(new ServiceManagerConfig(['abstract_factories' => ['ImgMan\\Storage\\Adapter\\Mongo\\MongoAdapterAbstractServiceFactory', 'ImgMan\\Storage\\Adapter\\Mongo\\MongoDbAbstractServiceFactory']])); $this->serviceManager->setService('Config', []); $this->assertFalse($this->serviceManager->has('ImgMan\\Storage\\Mongo')); }
public function testEmptyConfig() { $this->serviceManager = new ServiceManager\ServiceManager(new ServiceManagerConfig(['abstract_factories' => ['ImgMan\\Apigility\\ImgManConnectedResourceAbstractFactory']])); $this->assertFalse($this->serviceManager->has('ImgmanApigility\\ConnectedResource1')); $this->serviceManager = new ServiceManager\ServiceManager(new ServiceManagerConfig(['abstract_factories' => ['ImgMan\\Apigility\\ImgManConnectedResourceAbstractFactory']])); $this->serviceManager->setService('Config', []); $this->assertFalse($this->serviceManager->has('ImgmanApigility\\ConnectedResource1')); }
public function testCreateService() { $config = ['mailman' => ['Mandrill\\Complete' => ['default_sender' => '*****@*****.**', 'additional_info' => ['some' => 'thing'], 'transport' => ['type' => 'mandrill', 'options' => ['api_key' => 'MYSECRETMANDRILLKEY', 'sub_account' => 'my-optional-subaccount-if-any']]]]]; $this->sManager->setService('Config', $config); $this->assertTrue($this->sManager->has('Mandrill\\Complete')); $mailService = $this->sManager->get('Mandrill\\Complete'); $this->assertInstanceOf('MailMan\\Service\\MailService', $mailService); }
/** * Check if all configured services can be created * * @dataProvider provideServicesToCheck */ public function testServiceIntegrity($serviceName) { $this->assertTrue(self::$serviceManager->has($serviceName)); $object = self::$serviceManager->get($serviceName); if (class_exists($serviceName)) { $this->assertInstanceOf($serviceName, $object); } }
public function testMongoDbAbstractServiceFactory() { $this->assertTrue($this->serviceManager->has('MongoDb')); $this->assertInstanceOf('MongoDb', $this->serviceManager->get('MongoDb')); $this->serviceManager = new ServiceManager(new ServiceManagerConfig(['abstract_factories' => ['ImgMan\\Storage\\Adapter\\Mongo\\MongoDbAbstractServiceFactory']])); $this->assertFalse($this->serviceManager->has('MongoDb')); $this->serviceManager = new ServiceManager(new ServiceManagerConfig(['abstract_factories' => ['ImgMan\\Storage\\Adapter\\Mongo\\MongoDbAbstractServiceFactory']])); $this->serviceManager->setService('Config', []); $this->assertFalse($this->serviceManager->has('MongoDb')); }
public function testFileSystemAbstractFactoryService() { $this->assertTrue($this->serviceManager->has('ImgMan\\Storage\\FileSystem')); $this->assertInstanceOf('ImgMan\\Storage\\StorageInterface', $this->serviceManager->get('ImgMan\\Storage\\FileSystem')); $this->serviceManager = new ServiceManager(new ServiceManagerConfig(['abstract_factories' => ['ImgMan\\Storage\\Adapter\\FileSystem\\FileSystemAbstractServiceFactory']])); $this->assertFalse($this->serviceManager->has('ImgMan\\Storage\\FileSystem')); $this->serviceManager = new ServiceManager(new ServiceManagerConfig(['abstract_factories' => ['ImgMan\\Storage\\Adapter\\FileSystem\\FileSystemAbstractServiceFactory']])); $this->serviceManager->setService('Config', []); $this->assertFalse($this->serviceManager->has('ImgMan\\Storage\\FileSystem')); }
public function testServiceFactoryHas() { $serviceLocator = $this->serviceManager; $this->assertFalse($serviceLocator->has('ImgMan\\Service\\Test0')); $this->assertTrue($serviceLocator->has('ImgMan\\Service\\Test1')); $this->assertTrue($serviceLocator->has('ImgMan\\Service\\Test2')); $this->serviceManager = new ServiceManager(new ServiceManagerConfig(['abstract_factories' => ['ImgMan\\Service\\ImageServiceAbstractFactory']])); $this->assertFalse($this->serviceManager->has('ImgMan\\Service\\Test2')); $this->serviceManager = new ServiceManager(new ServiceManagerConfig(['abstract_factories' => ['ImgMan\\Service\\ImageServiceAbstractFactory']])); $this->serviceManager->setService('Config', []); $this->assertFalse($this->serviceManager->has('ImgMan\\Service\\Test2')); }
public function testBootstrapRecognizesServiceLocatorConfig() { $eventPublisher = $this->getMockBuilder(ServiceLocatorAwareEventPublisher::CLASS)->disableOriginalConstructor()->getMock(); $serviceLocator = new ServiceManager(); $domainManager = new DomainManager($eventPublisher, $serviceLocator); $domainManager->registerDomain(new ExampleDomain()); $domainManager->bootstrap(); $this->assertTrue($serviceLocator->has('exampleAlias')); $this->assertEquals('exampleService', call_user_func($serviceLocator->get('exampleAlias'))); $this->assertTrue($serviceLocator->has('exampleFactory')); $this->assertEquals('exampleFactory', $serviceLocator->get('exampleFactory')); $this->assertTrue($serviceLocator->has('exampleService')); $this->assertEquals('exampleService', call_user_func($serviceLocator->get('exampleService'))); }
/** * getObjectManager * * Return the object manager instance. * * @param ServiceManager $serviceManager The service manager. * @param string $objectManagerName The object manager name. * @param string $serviceName The name of the service being created. * * @return ObjectManager */ private function getObjectManager(ServiceManager $serviceManager, $objectManagerName, $serviceName) { if (!$serviceManager->has($objectManagerName)) { throw new ServiceNotFoundException(sprintf('The object manager \'%s\' could not be found while creating \'%s\'.', $objectManagerName, $serviceName)); } return $serviceManager->get($objectManagerName); }
/** * Use merged configuration to configure service manager * * If the merged configuration has a non-empty, array 'service_manager' * key, it will be passed to a ServiceManager Config object, and * used to configure the service manager. * * @param ModuleEvent $e * @throws Exception\RuntimeException * @return void */ public function onLoadModulesPost(ModuleEvent $e) { $configListener = $e->getConfigListener(); $config = $configListener->getMergedConfig(false); foreach ($this->serviceManagers as $key => $sm) { $smConfig = $this->mergeServiceConfiguration($key, $sm, $config); if (!$sm['service_manager'] instanceof ServiceManager) { if (!$this->defaultServiceManager->has($sm['service_manager'])) { throw new Exception\RuntimeException(sprintf('Could not find a valid ServiceManager for %s', $sm['service_manager'])); } $instance = $this->defaultServiceManager->get($sm['service_manager']); if (!$instance instanceof ServiceManager) { throw new Exception\RuntimeException(sprintf('Could not find a valid ServiceManager for %s', $sm['service_manager'])); } $sm['service_manager'] = $instance; } $serviceConfig = new ServiceConfig($smConfig); // The service listener is meant to operate during bootstrap, and, as such, // needs to be able to override existing configuration. $allowOverride = $sm['service_manager']->getAllowOverride(); $sm['service_manager']->setAllowOverride(true); $serviceConfig->configureServiceManager($sm['service_manager']); $sm['service_manager']->setAllowOverride($allowOverride); } }
public function has($name, $checkAbstractFactories = true, $usePeeringServiceManagers = true) { if (is_string($name)) { // internally called with an array [normalizedName, requestedName]. $this->incrementCallCount('has', $name); } return parent::has($name, $checkAbstractFactories, $usePeeringServiceManagers); }
/** * @covers Zend\ServiceManager\ServiceManager::canonicalizeName */ public function testCanonicalizeName() { $this->serviceManager->setService('foo_bar', new \stdClass()); $this->assertEquals(true, $this->serviceManager->has('foo_bar')); $this->assertEquals(true, $this->serviceManager->has('foobar')); $this->assertEquals(true, $this->serviceManager->has('foo-bar')); $this->assertEquals(true, $this->serviceManager->has('foo/bar')); $this->assertEquals(true, $this->serviceManager->has('foo bar')); }
public function has($name) { if (parent::has($name)) { return true; } if (preg_match('/doctrine/i', $name)) { return $this->serviceManager->has($name); } return false; }
public function testDiAbstractServiceFactory() { $di = $this->getMock('Zend\\Di\\Di'); $factory = new DiAbstractServiceFactory($di); $factory->instanceManager()->setConfig('ZendTest\\ServiceManager\\TestAsset\\Bar', array('parameters' => array('foo' => array('a')))); $this->serviceManager->addAbstractFactory($factory); $this->assertTrue($this->serviceManager->has('ZendTest\\ServiceManager\\TestAsset\\Bar', true)); $bar = $this->serviceManager->get('ZendTest\\ServiceManager\\TestAsset\\Bar', true); $this->assertInstanceOf('ZendTest\\ServiceManager\\TestAsset\\Bar', $bar); }
public function testProvidesValidServiceConfig() { $configProvider = new ConfigProvider(); $config = $configProvider(); $serviceManager = new ServiceManager($config['dependencies']); $serviceManager->setService('config', $config); foreach ($config['dependencies']['factories'] as $class => $factory) { $this->assertTrue($serviceManager->has($class)); $this->assertInstanceOf($class, $serviceManager->get($class)); } }
/** * Builds a new service manager * * @return \Zend\ServiceManager\ServiceManager */ public static function getServiceManager() { $serviceManager = new ServiceManager(new ServiceManagerConfig(isset(static::$config['service_manager']) ? static::$config['service_manager'] : array())); $serviceManager->setService('ApplicationConfig', static::$config); if (!$serviceManager->has('ServiceListener')) { $serviceManager->setFactory('ServiceListener', 'Zend\\Mvc\\Service\\ServiceListenerFactory'); } /** @var $moduleManager \Zend\ModuleManager\ModuleManager */ $moduleManager = $serviceManager->get('ModuleManager'); $moduleManager->loadModules(); return $serviceManager; }
/** * Iterates through all services of a service provider, seeding the container. * * For each service it: * * - adds the specified factory, if the service does not already exist. * - adds a delegator factory otherwise. * * @param ServiceProvider $provider * @param ServiceManager $container * @return ServiceManager * @throws RuntimeException if any factory listed is not callable. */ private function marshalServiceProvider(ServiceProvider $provider, ServiceManager $container) { foreach ($provider->getServices() as $service => $factory) { $callable = $this->marshalCallable($provider, $factory, $service); if ($container->has($service)) { $container->addDelegator($service, $this->createDelegator($callable)); continue; } $container->setFactory($service, $this->createFactory($callable)); } return $container; }
/** * Retrieves a new ServiceManager instance * * @param array|null $configuration * @return ServiceManager */ public function getServiceManager(array $configuration = null) { $configuration = $configuration ?: static::getConfiguration(); $serviceManager = new ServiceManager(new ServiceManagerConfig(isset($configuration['service_manager']) ? $configuration['service_manager'] : array())); $serviceManager->setService('ApplicationConfig', $configuration); if (!$serviceManager->has('ServiceListener')) { $serviceManager->setFactory('ServiceListener', 'Zend\\Mvc\\Service\\ServiceListenerFactory'); } /* @var $moduleManager \Zend\ModuleManager\ModuleManagerInterface */ $moduleManager = $serviceManager->get('ModuleManager'); $moduleManager->loadModules(); return $serviceManager; }
/** * dispatch($app) Get produced application object * * @param string $app application object * * @return \WebSockets\Application\ object * @throws Exception\ExceptionStrategy */ public function dispatch($app) { // need to provide dynamic objects creations //Get namespaces for application $config = $this->serviceManager->get('Config'); $namespaces = $config['websockets']['server']['applications_namespace']; foreach ($namespaces as $namespace) { // checking class.. $Client = "{$namespace}\\{$app}"; if (TRUE === class_exists($Client)) { $obj = new $Client(new WebsocketServer($config['websockets']['server'])); //Deprecated if ($obj instanceof ServiceLocatorAwareInterface) { $obj->setServiceLocator($this->serviceManager); } } if ($this->serviceManager->has($Client)) { return $this->serviceManager->get($Client); } } throw new Exception\ExceptionStrategy($app . ' application does not exist'); }
public function __construct(\Zend\ServiceManager\ServiceManager $sm) { $this->config = $sm->get('config')['PpModuleMailer']; if ($sm->has('translator')) { $this->translate = $sm->get('translator'); } $dbAdapter = $sm->get('Zend\\Db\\Adapter\\Adapter'); $resultSetPrototype = new ResultSet(); $resultSetPrototype->setArrayObjectPrototype(new Model\Mailer()); $tableGateway = new TableGateway($this->config['table'], $dbAdapter, null, $resultSetPrototype); //TODO inject config in more proper way? $this->table = new Model\MailerTable($tableGateway, $this->config); }
/** * getCredentialStrategy * * Return the password strategy that should be used. * * @param ServiceManager $serviceManager The service manager instance. * @param string $strategy The name of the password strategy that should be used. * @param string $serviceName The name of the service being created. * * @return PasswordInterface * * @throws ServiceNotFoundException If the password strategy cannot be found. * @throws ServiceNotCreatedException If the strategy is of an invalid type. */ protected function getCredentialStrategy(ServiceManager $serviceManager, $strategy, $serviceName) { if (is_string($strategy)) { if (!$serviceManager->has($strategy)) { throw new ServiceNotFoundException(sprintf('The password strategy \'%s\' could not be found for service \'%s\'.', $strategy, $serviceName)); } $strategy = $serviceManager->get($strategy); } if (!$strategy instanceof PasswordInterface) { throw new ServiceNotCreatedException(sprintf('The credential strategy must be an object of type \'%s\'; \'%s\' provided for service \'%s\'.', 'Zend\\Crypt\\Password\\PasswordInterface', is_object($strategy) ? get_class($strategy) : gettype($strategy), $serviceName)); } return $strategy; }
/** * Authenticates against the supplied adapter * * @param Adapter\AdapterInterface $adapter * @return Result * @throws Exception\RuntimeException */ public function authenticate(Adapter\AdapterInterface $adapter = null) { if (!$adapter) { if (!($adapter = $this->getAdapter())) { throw new Exception\RuntimeException('An adapter must be set or passed prior to calling authenticate()'); } } $result = $adapter->authenticate(); /** * ZF-7546 - prevent multiple successive calls from storing inconsistent results * Ensure storage has clean state */ if ($this->hasIdentity()) { $this->clearIdentity(); } if ($result->isValid()) { $data = (array) $this->getAdapter()->getResultRowObject(null, array('password')); $userEntity = $this->config['user-entity']; $userEntityHydrator = $this->config['user-entity-hydrator']; if ($this->serviceManager->has($userEntity)) { $userEntityInstance = $this->serviceManager->get($userEntity); } elseif (class_exists($userEntity)) { $userEntityInstance = new $userEntity(); } if ($this->serviceManager->has($userEntityHydrator)) { $hydrator = $this->serviceManager->get($userEntityHydrator); } elseif (class_exists($userEntityHydrator)) { $hydrator = new $userEntityHydrator(); } if ($hydrator) { $userEntityInstance = $hydrator->hydrate($data, $userEntityInstance); } $this->getStorage()->write($userEntityInstance); } return $result; }
/** * Check for a registered instance * * @param string|array $name * @return bool */ public function has($name) { if (isset($this->canonicalNames[$name])) { $cName = $this->canonicalNames[$name]; } else { $cName = $this->canonicalizeName($name); } if (array_key_exists($cName, $this->loggers) || array_key_exists($cName, $this->handlers)) { return true; } if (parent::has($name)) { return true; } return false; }
/** * getChainableAdapters * * Return the chainable adapters for the adapter chain. * * @param ServiceManager $serviceManager The service manager instance. * @param array $adapters The collection of authentication adapters. * @param string $serviceName The name of the service being created. * * @return ChainableAdapterInterface[] * * @throws ServiceNotFoundException If the chainable adapter cannot be found. * @throws InvalidArgumentException If the chainable adapter is not of type ChainableAdapterInterface. */ protected function getChainableAdapters(ServiceManager $serviceManager, array $adapters = [], $serviceName) { $chainableAdapters = []; foreach ($adapters as $index => $adapter) { if (is_string($adapter)) { if (!$serviceManager->has($adapter)) { throw new ServiceNotFoundException(sprintf('The chainable adapter \'%s\' could not be found for authentication adapter chain \'%s\' in \'%s\'.', $adapter, $serviceName, __METHOD__)); } $adapter = $serviceManager->get($adapter); } if (!$adapter instanceof ChainableAdapterInterface) { throw new InvalidArgumentException(sprintf('The chainable adapter at index \'%d\' for service \'%s\' must be an object of type \'%s\'; \'%s\' provided in \'%s\'.', $index, $serviceName, 'ArpAuth\\Authentication\\Adapter\\ChainableAdapterInterface', is_object($adapter) ? get_class($adapter) : gettype($adapter), __METHOD__)); } $chainableAdapters[] = $adapter; } return $chainableAdapters; }
/** * attachStrategies * * Attach new event strategies to the authentication service. * * @param ServiceManager $serviceManager The service manager. * @param AuthenticationService $service The authentication service to attach the strategies to. * @param array $strategies The strategies that should be resolved and added. * @param string $serviceName The name of the authentication service being created. * * @throws ServiceNotFoundException If a strategy cannot be found. * @throws ServiceNotCreatedException If the strategy is not a callable object. */ protected function attachStrategies(ServiceManager $serviceManager, AuthenticationService $service, array $strategies, $serviceName) { if (!$service instanceof EventsCapableInterface) { return; } foreach ($strategies as $strategy) { if (is_string($strategy)) { if (!$serviceManager->has($strategy)) { throw new ServiceNotFoundException(sprintf('The authentication strategy \'%s\' could not be found for \'%s\'.', $strategy, $serviceName)); } $strategy = $serviceManager->get($strategy); } if (!$strategy instanceof ListenerAggregateInterface) { throw new ServiceNotCreatedException(sprintf('The authentication strategy must be an object of type \'%s\'; \'%s\' provided for service \'%s\'.', 'Zend\\EventManager\\ListenerAggregateInterface', is_object($strategy) ? get_class($strategy) : gettype($strategy), $serviceName)); } $service->getEventManager()->attach($strategy); } }
/** * Get the default locale. * * @param string $locale */ public function getDefaultLocale() { if (!$this->default) { // Try to fetch the locale from Zend's translator if ($this->serviceManager->has('MvcTranslator')) { $this->setDefaultLocale($this->serviceManager->get('MvcTranslator')->getFallbackLocale()); } elseif ($this->serviceManager->has('Zend\\I18n\\Translator\\TranslatorInterface')) { $this->setDefaultLocale($this->serviceManager->get('Zend\\I18n\\Translator\\TranslatorInterface')->getFallbackLocale()); } elseif ($this->serviceManager->has('Translator')) { $this->setDefaultLocale($this->serviceManager->get('Translator')->getFallbackLocale()); } if (!$this->default) { if (!extension_loaded('intl')) { throw new Exception\ExtensionNotLoadedException(sprintf('%s component requires the intl PHP extension', __NAMESPACE__)); } $this->setDefaultLocale(\Locale::getDefault()); } } return $this->default; }
/** * Generates a list of Action objects based on the given directory structure, handling * each found class as an invokable service * * @deprecated this logic is deprecated and uses per-directory scanning. Instead, please * map your defined service names in the 'services' config * @param array $modules * @return array * @throws InvalidArgumentException */ protected function buildDirectoryApi(array $modules) { $api = array(); foreach ($modules as $moduleName => $module) { if (!isset($module['directory']) || !is_dir($module['directory'])) { throw new InvalidArgumentException('Invalid directory given: "' . $module['directory'] . '"'); } if (!isset($module['namespace']) || !is_string($module['namespace'])) { throw new InvalidArgumentException('Invalid namespace provided for module "' . $moduleName . '"'); } $jsNamespace = rtrim(str_replace('\\', '.', $module['namespace']), '.') . '.'; $directoryScanner = new DirectoryScanner($module['directory']); /* @var $class \Zend\Code\Scanner\DerivedClassScanner */ foreach ($directoryScanner->getClasses(true) as $class) { // now building the service name as exposed client-side $className = $class->getName(); $jsClassName = str_replace('\\', '.', substr($className, strlen($module['namespace']) + 1)); $jsClassNames = explode('.', $jsClassName); $chunks = count($jsClassNames); // lcfirst all chunks except the last one for ($i = 1; $i < $chunks; $i += 1) { $jsClassNames[$i - 1] = lcfirst($jsClassNames[$i - 1]); } $serviceName = $jsNamespace . implode('.', $jsClassNames); if (!$this->serviceManager->has($serviceName)) { $this->serviceManager->setInvokableClass($serviceName, $className); } // invoking to check if nothing went wrong - this avoids setting invalid services $service = $this->serviceManager->get($serviceName); $action = $this->buildAction(get_class($service)); $action->setName($serviceName); $action->setObjectName($className); $api[$serviceName] = $action; } } return $api; }
public function testConsumeSlimContainer() { $anoterContainer = new Set(); $anoterContainer->foo = []; $anoterContainer->bar = new \stdClass(); $anoterContainer->baz = function ($c) { return 'Hello'; }; $anoterContainer->singleton('foobar', function ($c) { return 'Hello'; }); $anoterContainer->barfoo = [$this, 'fakeMethod']; $this->container->consumeSlimContainer($anoterContainer); $this->assertTrue($this->sm->has('foo')); $this->assertTrue($this->container->has('foo')); $this->assertTrue($this->sm->has('bar')); $this->assertTrue($this->container->has('bar')); $this->assertTrue($this->sm->has('baz')); $this->assertTrue($this->container->has('baz')); $this->assertTrue($this->sm->has('foobar')); $this->assertTrue($this->container->has('foobar')); $this->assertTrue($this->sm->has('barfoo')); $this->assertTrue($this->container->has('barfoo')); }
/** * Does this set contain a key? * @param string $key The data key * @return boolean */ public function has($key) { return $this->sm->has($key); }