useContainer = $useContainer; // Since we are using this in a proxy-fashion, localize state $this->di = $di; $this->definitions = $this->di->definitions; $this->instanceManager = $this->di->instanceManager; } /** * @param array $allowedServiceNames */ public function setAllowedServiceNames(array $allowedServiceNames) { $this->allowedServiceNames = array_flip(array_values($allowedServiceNames)); } /** * @return array */ public function getAllowedServiceNames() { return array_keys($this->allowedServiceNames); } /** * {@inheritDoc} * * Allows creation of services only when in a whitelist */ public function __invoke(ContainerInterface $container, $name, array $options = null) { if (! isset($this->allowedServiceNames[$name])) { throw new Exception\InvalidServiceException(sprintf( 'Service "%s" is not whitelisted', $name )); } $this->container = ($container instanceof AbstractPluginManager) ? $container->getServiceLocator() : $container; return parent::get($name); } /** * {@inheritDoc} * * For use with zend-servicemanager v2; proxies to __invoke(). */ public function createServiceWithName(ServiceLocatorInterface $container, $serviceName, $requestedName) { return $this($container, $requestedName); } /** * Overrides Zend\Di to allow the given container's services to be reused by Di itself * * {@inheritDoc} * * @throws Exception\InvalidServiceNameException */ public function get($name, array $params = []) { if (null === $this->container) { throw new DomainException( 'No ServiceLocator defined, use `createServiceWithName` instead of `get`' ); } if (self::USE_SL_BEFORE_DI === $this->useContainer && $this->container->has($name)) { return $this->container->get($name); } try { return parent::get($name, $params); } catch (ClassNotFoundException $e) { if (self::USE_SL_AFTER_DI === $this->useContainer && $this->container->has($name)) { return $this->container->get($name); } throw new Exception\ServiceNotFoundException( sprintf('Service %s was not found in this DI instance', $name), null, $e ); } } /** * {@inheritDoc} * * Allows creation of services only when in a whitelist. */ public function canCreate(ContainerInterface $container, $requestedName) { // won't check if the service exists, we are trusting the user's whitelist return isset($this->allowedServiceNames[$requestedName]); } /** * {@inheritDoc} * * For use with zend-servicemanager v2; proxies to canCreate(). */ public function canCreateServiceWithName(ServiceLocatorInterface $container, $name, $requestedName) { return $this->canCreate($container, $requestedName); } }