Completed
Pull Request — develop (#607)
by Tom
03:12 queued 01:40
created

ConfigurationFactory::__invoke()   F

Complexity

Conditions 22
Paths 10576

Size

Total Lines 136

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 66
CRAP Score 23.7608

Importance

Changes 0
Metric Value
dl 0
loc 136
ccs 66
cts 78
cp 0.8462
rs 0
c 0
b 0
f 0
cc 22
nc 10576
nop 3
crap 23.7608

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace DoctrineORMModule\Service;
6
7
use Doctrine\ORM\Cache\CacheConfiguration;
8
use Doctrine\ORM\Cache\DefaultCacheFactory;
9
use Doctrine\ORM\Cache\RegionsConfiguration;
10
use Doctrine\ORM\Configuration;
11
use Doctrine\ORM\Mapping\EntityListenerResolver;
12
use DoctrineORMModule\Options\Configuration as DoctrineORMModuleConfiguration;
13
use DoctrineORMModule\Service\DBALConfigurationFactory as DoctrineConfigurationFactory;
14
use Interop\Container\ContainerInterface;
15
use Laminas\ServiceManager\Exception\InvalidArgumentException;
16
use Laminas\ServiceManager\ServiceLocatorInterface;
17
use function assert;
18
use function is_string;
19
use function sprintf;
20
21
class ConfigurationFactory extends DoctrineConfigurationFactory
22
{
23
    /**
24
     * {@inheritDoc}
25
     *
26
     * @return Configuration
27
     */
28 16
    public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null)
29
    {
30 16
        $options = $this->getOptions($container);
31 16
        assert($options instanceof DoctrineORMModuleConfiguration);
32 16
        $config = new Configuration();
33
34 16
        $config->setAutoGenerateProxyClasses($options->getGenerateProxies());
35 16
        $config->setProxyDir($options->getProxyDir());
36 16
        $config->setProxyNamespace($options->getProxyNamespace());
37
38 16
        $config->setEntityNamespaces($options->getEntityNamespaces());
39
40 16
        $config->setCustomDatetimeFunctions($options->getDatetimeFunctions());
41 16
        $config->setCustomStringFunctions($options->getStringFunctions());
42 16
        $config->setCustomNumericFunctions($options->getNumericFunctions());
43
44 16
        $config->setClassMetadataFactoryName($options->getClassMetadataFactoryName());
45
46 16
        foreach ($options->getNamedQueries() as $name => $query) {
47
            $config->addNamedQuery($name, $query);
48
        }
49
50 16
        foreach ($options->getNamedNativeQueries() as $name => $query) {
51
            $config->addNamedNativeQuery($name, $query['sql'], new $query['rsm']());
52
        }
53
54 16
        foreach ($options->getCustomHydrationModes() as $modeName => $hydrator) {
55
            $config->addCustomHydrationMode($modeName, $hydrator);
56
        }
57
58 16
        foreach ($options->getFilters() as $name => $class) {
59
            $config->addFilter($name, $class);
60
        }
61
62 16
        $config->setMetadataCacheImpl($container->get($options->getMetadataCache()));
63 16
        $config->setQueryCacheImpl($container->get($options->getQueryCache()));
64 16
        $config->setResultCacheImpl($container->get($options->getResultCache()));
65 16
        $config->setHydrationCacheImpl($container->get($options->getHydrationCache()));
66 16
        $config->setMetadataDriverImpl($container->get($options->getDriver()));
67
68 16
        $namingStrategy = $options->getNamingStrategy();
69 16
        if ($namingStrategy) {
70 3
            if (is_string($namingStrategy)) {
71 2
                if (! $container->has($namingStrategy)) {
72 1
                    throw new InvalidArgumentException(sprintf('Naming strategy "%s" not found', $namingStrategy));
73
                }
74
75 1
                $config->setNamingStrategy($container->get($namingStrategy));
76
            } else {
77 1
                $config->setNamingStrategy($namingStrategy);
78
            }
79
        }
80
81 15
        $quoteStrategy = $options->getQuoteStrategy();
82 15
        if ($quoteStrategy) {
83 3
            if (is_string($quoteStrategy)) {
84 2
                if (! $container->has($quoteStrategy)) {
85 1
                    throw new InvalidArgumentException(sprintf('Quote strategy "%s" not found', $quoteStrategy));
86
                }
87
88 1
                $config->setQuoteStrategy($container->get($quoteStrategy));
89
            } else {
90 1
                $config->setQuoteStrategy($quoteStrategy);
91
            }
92
        }
93
94 14
        $repositoryFactory = $options->getRepositoryFactory();
95 14
        if ($repositoryFactory) {
96
            if (is_string($repositoryFactory)) {
97
                if (! $container->has($repositoryFactory)) {
98
                    throw new InvalidArgumentException(
99
                        sprintf('Repository factory "%s" not found', $repositoryFactory)
100
                    );
101
                }
102
103
                $config->setRepositoryFactory($container->get($repositoryFactory));
104
            } else {
105
                $config->setRepositoryFactory($repositoryFactory);
106
            }
107
        }
108
109 14
        $entityListenerResolver = $options->getEntityListenerResolver();
110 14
        if ($entityListenerResolver) {
111 2
            if ($entityListenerResolver instanceof EntityListenerResolver) {
112 1
                $config->setEntityListenerResolver($entityListenerResolver);
113
            } else {
114 1
                $config->setEntityListenerResolver($container->get($entityListenerResolver));
115
            }
116
        }
117
118 14
        $secondLevelCache = $options->getSecondLevelCache();
119
120 14
        if ($secondLevelCache->isEnabled()) {
121 1
            $regionsConfig = new RegionsConfiguration(
122 1
                $secondLevelCache->getDefaultLifetime(),
123 1
                $secondLevelCache->getDefaultLockLifetime()
124
            );
125
126 1
            foreach ($secondLevelCache->getRegions() as $regionName => $regionConfig) {
127 1
                if (isset($regionConfig['lifetime'])) {
128 1
                    $regionsConfig->setLifetime($regionName, $regionConfig['lifetime']);
129
                }
130
131 1
                if (! isset($regionConfig['lock_lifetime'])) {
132
                    continue;
133
                }
134
135 1
                $regionsConfig->setLockLifetime($regionName, $regionConfig['lock_lifetime']);
136
            }
137
138
            // As Second Level Cache caches queries results, we reuse the result cache impl
139 1
            $cacheFactory = new DefaultCacheFactory($regionsConfig, $config->getResultCacheImpl());
0 ignored issues
show
Bug introduced by
It seems like $config->getResultCacheImpl() can be null; however, __construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
140 1
            $cacheFactory->setFileLockRegionDirectory($secondLevelCache->getFileLockRegionDirectory());
141
142 1
            $cacheConfiguration = new CacheConfiguration();
143 1
            $cacheConfiguration->setCacheFactory($cacheFactory);
144 1
            $cacheConfiguration->setRegionsConfiguration($regionsConfig);
145
146 1
            $config->setSecondLevelCacheEnabled();
147 1
            $config->setSecondLevelCacheConfiguration($cacheConfiguration);
148
        }
149
150 14
        $filterSchemaAssetsExpression = $options->getFilterSchemaAssetsExpression();
151 14
        if ($filterSchemaAssetsExpression) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $filterSchemaAssetsExpression of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
152
            $config->setFilterSchemaAssetsExpression($filterSchemaAssetsExpression);
0 ignored issues
show
Deprecated Code introduced by
The method Doctrine\DBAL\Configurat...chemaAssetsExpression() has been deprecated with message: Use Configuration::setSchemaAssetsFilter() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
153
        }
154
155 14
        $className = $options->getDefaultRepositoryClassName();
156 14
        if ($className) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $className of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
157 1
            $config->setDefaultRepositoryClassName($className);
158
        }
159
160 14
        $this->setupDBALConfiguration($container, $config);
161
162 14
        return $config;
163
    }
164
165
    /**
166
     * @return mixed
167
     */
168 16
    public function createService(ServiceLocatorInterface $container)
169
    {
170 16
        return $this($container, Configuration::class);
171
    }
172
173 16
    protected function getOptionsClass() : string
174
    {
175 16
        return DoctrineORMModuleConfiguration::class;
176
    }
177
}
178