Completed
Push — master ( 38df09...7a08de )
by Daniel
08:33
created

Commander::createCache()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
ccs 0
cts 5
cp 0
rs 9.6666
cc 2
eloc 5
nc 2
nop 0
crap 6
1
<?php
2
/**
3
 * This file is part of the Commander project.
4
 *
5
 * @author Daniel Schröder <[email protected]>
6
 */
7
8
namespace GravityMedia\Commander;
9
10
use Doctrine\Common\Annotations\AnnotationReader;
11
use Doctrine\Common\Annotations\AnnotationRegistry;
12
use Doctrine\Common\Annotations\CachedReader;
13
use Doctrine\Common\Cache\ArrayCache;
14
use Doctrine\Common\Cache\Cache;
15
use Doctrine\Common\Cache\FilesystemCache;
16
use Doctrine\Common\EventManager;
17
use Doctrine\Common\Persistence\Mapping\Driver\MappingDriver;
18
use Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain;
19
use Doctrine\ORM\Configuration;
20
use Doctrine\ORM\EntityManager;
21
use Doctrine\ORM\EntityManagerInterface;
22
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
23
use Doctrine\ORM\Tools\SchemaTool;
24
use Doctrine\ORM\Tools\SchemaValidator;
25
use Gedmo\DoctrineExtensions;
26
use Gedmo\Timestampable\TimestampableListener;
27
use GravityMedia\Commander\Config\CommanderConfig;
28
use Monolog\Handler\StreamHandler;
29
use Monolog\Logger;
30
use Psr\Log\LoggerInterface;
31
32
/**
33
 * Commander class.
34
 *
35
 * @package GravityMedia\Commander
36
 */
37
class Commander
38
{
39
    /**
40
     * The entity namespace.
41
     */
42
    const ENTITY_NAMESPACE = 'GravityMedia\Commander\Entity';
43
44
    /**
45
     * @var CommanderConfig
46
     */
47
    protected $config;
48
49
    /**
50
     * The mapping driver.
51
     *
52
     * @var MappingDriver
53
     */
54
    protected $mappingDriver;
55
56
    /**
57
     * The entity manager config.
58
     *
59
     * @var Configuration
60
     */
61
    protected $entityManagerConfig;
62
63
    /**
64
     * The entity manager.
65
     *
66
     * @var EntityManagerInterface
67
     */
68
    protected $entityManager;
69
70
    /**
71
     * The schema validator.
72
     *
73
     * @var SchemaValidator
74
     */
75
    protected $schemaValidator;
76
77
    /**
78
     * The schema tool.
79
     *
80
     * @var SchemaTool
81
     */
82
    protected $schemaTool;
83
84
    /**
85
     * The logger.
86
     *
87
     * @var LoggerInterface
88
     */
89
    protected $logger;
90
91
    /**
92
     * Create commander object.
93
     *
94
     * @param CommanderConfig $config
95
     */
96
    public function __construct(CommanderConfig $config)
97
    {
98
        $this->config = $config;
99
    }
100
101
    /**
102
     * Create cache object.
103
     *
104
     * @return Cache
105
     */
106
    protected function createCache()
107
    {
108
        $directory = $this->config->getDatabaseCacheDirectory();
109
        if (null === $directory) {
110
            return new ArrayCache();
111
        }
112
113
        return new FilesystemCache($directory);
114
    }
115
116
    /**
117
     * Get mapping driver.
118
     *
119
     * @return MappingDriver
120
     */
121
    public function getMappingDriver()
122
    {
123
        if (null === $this->mappingDriver) {
124
            AnnotationRegistry::registerFile(
125
                __DIR__ . '/../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php'
126
            );
127
128
            $driverChain = new MappingDriverChain();
129
            $reader = new CachedReader(new AnnotationReader(), $this->createCache());
130
131
            DoctrineExtensions::registerAbstractMappingIntoDriverChainORM($driverChain, $reader);
132
133
            $annotationDriver = new AnnotationDriver($reader, [__DIR__ . '/Entity']);
0 ignored issues
show
Documentation introduced by
$reader is of type object<Doctrine\Common\Annotations\CachedReader>, but the function expects a object<Doctrine\Common\A...tions\AnnotationReader>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
134
            $driverChain->addDriver($annotationDriver, static::ENTITY_NAMESPACE);
135
136
            $this->mappingDriver = $driverChain;
137
        }
138
139
        return $this->mappingDriver;
140
    }
141
142
    /**
143
     * Get entity manager config.
144
     *
145
     * @return Configuration
146
     */
147
    public function getEntityManagerConfig()
148
    {
149
        if (null === $this->entityManagerConfig) {
150
            $proxyDirectory = $this->config->getDatabaseCacheDirectory();
151
            if (null === $proxyDirectory) {
152
                $proxyDirectory = sys_get_temp_dir();
153
            }
154
155
            $config = new Configuration();
156
            $config->setAutoGenerateProxyClasses(true);
157
            $config->setProxyDir($proxyDirectory);
158
            $config->setProxyNamespace(static::ENTITY_NAMESPACE);
159
            $config->setMetadataDriverImpl($this->getMappingDriver());
160
            $config->setMetadataCacheImpl($this->createCache());
161
            $config->setQueryCacheImpl($this->createCache());
162
            $config->setResultCacheImpl($this->createCache());
163
            $config->setHydrationCacheImpl($this->createCache());
164
165
            $this->entityManagerConfig = $config;
166
        }
167
168
        return $this->entityManagerConfig;
169
    }
170
171
    /**
172
     * Get entity manager.
173
     *
174
     * @return EntityManagerInterface
175
     */
176
    public function getEntityManager()
177
    {
178
        if (null === $this->entityManager) {
179
            $connection = [
180
                'driver' => 'pdo_sqlite',
181
                'path' => $this->config->getDatabaseFilePath()
182
            ];
183
184
            $configuration = $this->getEntityManagerConfig();
185
            $metadataDriver = $configuration->getMetadataDriverImpl();
186
187
            $timestampableListener = new TimestampableListener();
188
            if ($metadataDriver instanceof AnnotationDriver) {
189
                $timestampableListener->setAnnotationReader($metadataDriver->getReader());
190
            }
191
192
            $eventManager = new EventManager();
193
            $eventManager->addEventSubscriber($timestampableListener);
194
195
            $this->entityManager = EntityManager::create($connection, $configuration, $eventManager);
196
        }
197
198
        return $this->entityManager;
199
    }
200
201
    /**
202
     * Get schema validator.
203
     *
204
     * @return SchemaValidator
205
     */
206
    public function getSchemaValidator()
207
    {
208
        if (null === $this->schemaValidator) {
209
            $entityManager = $this->getEntityManager();
210
211
            $this->schemaValidator = new SchemaValidator($entityManager);
212
        }
213
214
        return $this->schemaValidator;
215
    }
216
217
    /**
218
     * Get schema tool.
219
     *
220
     * @return SchemaTool
221
     */
222
    public function getSchemaTool()
223
    {
224
        if (null === $this->schemaTool) {
225
            $entityManager = $this->getEntityManager();
226
227
            $this->schemaTool = new SchemaTool($entityManager);
228
        }
229
230
        return $this->schemaTool;
231
    }
232
233
    /**
234
     * Get logger.
235
     *
236
     * @return LoggerInterface
237
     */
238
    public function getLogger()
239
    {
240
        if (null === $this->logger) {
241
            $logger = new Logger('COMMANDER');
242
243
            $path = $this->config->getLogFilePath();
244
            if (null !== $path) {
245
                $logger->pushHandler(new StreamHandler($path));
246
            }
247
248
            $this->logger = $logger;
249
        }
250
251
        return $this->logger;
252
    }
253
254
    /**
255
     * Return whether or not the schema is valid.
256
     *
257
     * @return bool
258
     */
259
    public function isSchemaValid()
260
    {
261
        return $this->getSchemaValidator()->schemaInSyncWithMetadata();
262
    }
263
264
    /**
265
     * Update schema.
266
     *
267
     * @return $this
268
     */
269
    public function updateSchema()
270
    {
271
        $classes = $this->getEntityManager()->getMetadataFactory()->getAllMetadata();
272
        $this->getSchemaTool()->updateSchema($classes);
273
274
        return $this;
275
    }
276
}
277