Completed
Pull Request — master (#15)
by Vytautas
10:02
created

createServiceWithName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 3
Bugs 0 Features 2
Metric Value
c 3
b 0
f 2
dl 0
loc 4
ccs 0
cts 0
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 3
crap 2
1
<?php
2
3
namespace Svycka\Settings\Collection\Factory;
4
5
use Interop\Container\ContainerInterface;
6
use Interop\Container\Exception\ContainerException;
7
use Svycka\Settings\Collection\CollectionsManager;
8
use Svycka\Settings\Collection\SettingsCollection;
9
use Svycka\Settings\Options\CollectionOptions;
10
use Svycka\Settings\Options\ModuleOptions;
11
use Svycka\Settings\Provider\OwnerProviderInterface;
12
use Svycka\Settings\Storage\StorageAdapterInterface;
13
use Svycka\Settings\Type\TypesManager;
14
use Zend\ServiceManager\AbstractFactoryInterface;
15
use Zend\ServiceManager\Exception\ServiceNotCreatedException;
16
use Zend\ServiceManager\Exception\ServiceNotFoundException;
17
use Zend\ServiceManager\ServiceLocatorInterface;
18
19
/**
20
 * @author Vytautas Stankus <[email protected]>
21
 * @license MIT
22
 */
23
class SettingsCollectionAbstractFactory implements AbstractFactoryInterface
24
{
25
    /**
26
     * Can the factory create an instance for the service?
27
     *
28
     * @param  ContainerInterface $container
29
     * @param  string $requestedName
30
     * @return bool
31
     */
32 2
    public function canCreate(ContainerInterface $container, $requestedName)
33
    {
34
        /** @var CollectionsManager $config */
35 2
        $config = $container->get(ModuleOptions::class)->getCollections();
36 2
        if (empty($config)) {
37 1
            return false;
38
        }
39
40 1
        return isset($config[$requestedName]);
41
    }
42
43
    /**
44
     * Create an object
45
     *
46
     * @param  ContainerInterface $container
47
     * @param  string             $requestedName
48
     * @param  null|array         $options
49
     * @return object
50
     * @throws ServiceNotFoundException if unable to resolve the service.
51
     * @throws ServiceNotCreatedException if an exception is raised when
52
     *     creating a service.
53
     * @throws ContainerException if any other error occurs
54
     */
55 1
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
56
    {
57 1
        $collectionsConfig = $container->get(ModuleOptions::class)->getCollections();
58 1
        $config = new CollectionOptions($collectionsConfig[$requestedName]);
59 1
        $config->setName($requestedName);
60
61
        /** @var StorageAdapterInterface $storage */
62 1
        $storage = $container->get($config->getStorageAdapter());
63
        /** @var OwnerProviderInterface $owner_provider */
64 1
        $owner_provider = $container->get($config->getOwnerProvider());
65
        /** @var TypesManager $typesManager */
66 1
        $typesManager = $container->get(TypesManager::class);
67
68 1
        return new SettingsCollection($config, $storage, $owner_provider, $typesManager);
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     *
74
     * @deprecated will be removed after zf2 support drop
75
     */
76
    public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
77
    {
78
        return $this->canCreate($serviceLocator->getServiceLocator(), $requestedName);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\ServiceManager\ServiceLocatorInterface as the method getServiceLocator() does only exist in the following implementations of said interface: Svycka\Settings\Collection\CollectionsManager, Svycka\Settings\Type\TypesManager, Zend\Cache\PatternPluginManager, Zend\Cache\Storage\AdapterPluginManager, Zend\Cache\Storage\PluginManager, Zend\Config\ReaderPluginManager, Zend\Config\WriterPluginManager, Zend\Filter\FilterPluginManager, Zend\Form\FormElementMan...lementManagerV2Polyfill, Zend\Form\FormElementMan...lementManagerV3Polyfill, Zend\Hydrator\HydratorPluginManager, Zend\I18n\Translator\LoaderPluginManager, Zend\InputFilter\InputFilterPluginManager, Zend\Mvc\Controller\ControllerManager, Zend\Mvc\Controller\PluginManager, Zend\Mvc\Router\RoutePluginManager, Zend\Paginator\AdapterPluginManager, Zend\Paginator\ScrollingStylePluginManager, Zend\ServiceManager\AbstractPluginManager, Zend\Stdlib\Hydrator\HydratorPluginManager, Zend\Validator\ValidatorPluginManager, Zend\View\HelperPluginManager, Zend\View\Helper\Navigation\PluginManager.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     *
84
     * @deprecated will be removed after zf2 support drop
85
     */
86
    public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
87
    {
88
        return $this($serviceLocator->getServiceLocator(), $requestedName);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\ServiceManager\ServiceLocatorInterface as the method getServiceLocator() does only exist in the following implementations of said interface: Svycka\Settings\Collection\CollectionsManager, Svycka\Settings\Type\TypesManager, Zend\Cache\PatternPluginManager, Zend\Cache\Storage\AdapterPluginManager, Zend\Cache\Storage\PluginManager, Zend\Config\ReaderPluginManager, Zend\Config\WriterPluginManager, Zend\Filter\FilterPluginManager, Zend\Form\FormElementMan...lementManagerV2Polyfill, Zend\Form\FormElementMan...lementManagerV3Polyfill, Zend\Hydrator\HydratorPluginManager, Zend\I18n\Translator\LoaderPluginManager, Zend\InputFilter\InputFilterPluginManager, Zend\Mvc\Controller\ControllerManager, Zend\Mvc\Controller\PluginManager, Zend\Mvc\Router\RoutePluginManager, Zend\Paginator\AdapterPluginManager, Zend\Paginator\ScrollingStylePluginManager, Zend\ServiceManager\AbstractPluginManager, Zend\Stdlib\Hydrator\HydratorPluginManager, Zend\Validator\ValidatorPluginManager, Zend\View\HelperPluginManager, Zend\View\Helper\Navigation\PluginManager.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
89
    }
90
}
91