Extension::loadConfiguration()   A
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 64
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 38
nc 8
nop 0
dl 0
loc 64
rs 9.312
c 0
b 0
f 0

How to fix   Long Method   

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 declare(strict_types=1);
2
3
namespace Rostenkowski\Doctrine;
4
5
6
use Doctrine;
7
use Doctrine\Common\Cache\ApcuCache;
8
use Doctrine\Common\Cache\ArrayCache;
9
use Doctrine\Common\EventManager;
10
use Doctrine\DBAL\Logging\LoggerChain;
11
use Doctrine\DBAL\Tools\Console\Command\ImportCommand;
12
use Doctrine\DBAL\Tools\Console\Command\RunSqlCommand;
13
use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper;
14
use Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand;
15
use Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand;
16
use Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand;
17
use Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand;
18
use Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand;
19
use Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand;
20
use Doctrine\ORM\Tools\Console\Command\InfoCommand;
21
use Doctrine\ORM\Tools\Console\Command\RunDqlCommand;
22
use Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand;
23
use Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand;
24
use Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand;
25
use Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand;
26
use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper;
27
use Nette\DI\CompilerExtension;
28
use Nette\DI\Helpers;
29
use Nette\DI\Statement;
30
use Rostenkowski\Doctrine\Debugger\TracyBar;
31
use Rostenkowski\Doctrine\Logger\FileLogger;
32
use Rostenkowski\Doctrine\Repository\Repository;
33
use Symfony\Component\Console\Application;
34
use Symfony\Component\Console\Helper\DebugFormatterHelper;
35
use Symfony\Component\Console\Helper\FormatterHelper;
36
use Symfony\Component\Console\Helper\HelperSet;
37
use Symfony\Component\Console\Helper\ProcessHelper;
38
use Symfony\Component\Console\Helper\QuestionHelper;
39
40
class Extension extends CompilerExtension
41
{
42
43
	/**
44
	 * cache driver name to class map
45
	 *
46
	 * @var array
47
	 */
48
	protected $cacheDrivers = array(
49
		'none'      => 'Doctrine\Common\Cache\ArrayCache',
50
		'apc'       => 'Doctrine\Common\Cache\ApcCache',
51
		'redis'     => 'Doctrine\Common\Cache\RedisCache',
52
		'fs'        => 'Doctrine\Common\Cache\FilesystemCache',
53
		'default'   => 'Doctrine\Common\Cache\FilesystemCache',
54
		'phpfile'   => 'Doctrine\Common\Cache\PhpFileCache',
55
		'zend'      => 'Doctrine\Common\Cache\ZendDataCache',
56
		'wincache'  => 'Doctrine\Common\Cache\WinCache',
57
		'xcache'    => 'Doctrine\Common\Cache\XCache',
58
		'memcache'  => 'Doctrine\Common\Cache\MemcacheCache',
59
		'memcached' => 'Doctrine\Common\Cache\MemcachedCache',
60
	);
61
62
	/**
63
	 * @var array
64
	 */
65
	private $defaults = [
66
		'connection' => [
67
			'driver'   => NULL,
68
			'path'     => NULL,
69
			'host'     => NULL,
70
			'dbname'   => NULL,
71
			'user'     => NULL,
72
			'password' => NULL,
73
		],
74
		'entities'   => [
75
			'%appDir%/entities'
76
		],
77
		'repository' => Repository::class,
78
		'debugger'   => [
79
			'enabled' => '%debugMode%',
80
			'width'   => '960px',
81
			'height'  => '720px',
82
			'sources' => [
83
				'%appDir%',
84
				'%tempDir%',
85
			],
86
		],
87
		'logger'     => [
88
			'enabled' => true,
89
			'factory' => FileLogger::class,
90
			'args'    => ['%logDir%/query.log']
91
		],
92
		'cache'      => [
93
			'enabled' => true,
94
			'factory' => ApcuCache::class,
95
			'args'    => []
96
		],
97
		'proxy'      => [
98
			'dir' => '%tempDir%/doctrine/proxies',
99
		],
100
		'function'   => [],
101
		'type'       => [],
102
		'console'    => [
103
			'commands' => [
104
				'doctrine:info'           => InfoCommand::class,
105
				'doctrine:production'     => EnsureProductionSettingsCommand::class,
106
				'doctrine:repositories'   => GenerateRepositoriesCommand::class,
107
				'doctrine:proxies'        => GenerateProxiesCommand::class,
108
				'doctrine:schema-check'   => ValidateSchemaCommand::class,
109
				'doctrine:schema-update'  => UpdateCommand::class,
110
				'doctrine:schema-create'  => CreateCommand::class,
111
				'doctrine:schema-drop'    => DropCommand::class,
112
				'doctrine:cache-metadata' => MetadataCommand::class,
113
				'doctrine:cache-query'    => QueryCommand::class,
114
				'doctrine:cache-result'   => ResultCommand::class,
115
				'doctrine:query'          => RunDqlCommand::class,
116
				'doctrine:exec'           => RunSqlCommand::class,
117
				'doctrine:import'         => ImportCommand::class,
118
			],
119
		],
120
	];
121
122
123
	public function loadConfiguration()
124
	{
125
		$builder = $this->getContainerBuilder();
126
127
		$this->config = $config = Helpers::expand($this->validateConfig($this->defaults), $builder->parameters);
128
129
		// create configuration
130
		$configuration = $builder->addDefinition($this->prefix('configuration'))
131
			->setFactory('Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration', [
132
				$config['entities'],
133
				$config['debugger']['enabled'],
134
				$config['proxy']['dir'],
135
				$this->prefix('@cache'),
136
			]);
137
138
		// create cache
139
		$cache = $builder->addDefinition($this->prefix('cache'));
140
		if ($config['cache']['enabled']) {
141
			$cache->setFactory($config['cache']['factory'], $config['cache']['args']);
142
		} else {
143
			$cache->setFactory(ArrayCache::class);
144
		}
145
146
		// create event manager
147
		$evm = $builder->addDefinition($this->prefix('eventManager'));
148
		$evm->setFactory(EventManager::class);
149
150
		// create connection
151
		$connection = $builder->addDefinition($this->prefix('connection'));
152
		$connection->setFactory('Doctrine\DBAL\DriverManager::getConnection', [
153
			$config['connection'],
154
			$this->prefix('@configuration'),
155
			$this->prefix('@eventManager'),
156
		]);
157
158
		// create logger
159
		$log = $builder->addDefinition($this->prefix('log'))
160
			->setFactory(LoggerChain::class);
161
		if ($config['logger']['enabled']) {
162
			$builder->addDefinition($this->prefix('logger'))
163
				->setFactory($config['logger']['factory'], $config['logger']['args']);
164
			$log->addSetup('addLogger', [$this->prefix('@logger')]);
165
		}
166
167
		// create debugger
168
		if ($config['debugger']['enabled']) {
169
			$builder->addDefinition($this->prefix('debugger'))
170
				->setFactory(TracyBar::class, $config['debugger']['sources'])
171
				->addSetup('Tracy\Debugger::getBar()->addPanel(?);', ['@self'])
172
				->addSetup('setWidth', [$config['debugger']['width']])
173
				->addSetup('setHeight', [$config['debugger']['height']]);
174
			$log->addSetup('addLogger', [$this->prefix('@debugger')]);
175
		}
176
177
		// set repository class
178
		$configuration->addSetup('setDefaultRepositoryClassName', [$config['repository']]);
179
180
		// set logger chain as logger
181
		$configuration->addSetup('setSQLLogger', [$this->prefix('@log')]);
182
183
		// create entity manager
184
		$builder->addDefinition($this->prefix('entityManager'))
185
			->setFactory('Doctrine\ORM\EntityManager::create', [$this->prefix('@connection'), $this->prefix('@configuration')])
186
			->setAutowired(true);
187
	}
188
189
190
	public function beforeCompile()
191
	{
192
		$config = $this->getConfig();
193
		$builder = $this->getContainerBuilder();
194
195
		// add console if none defined
196
		if ($builder->findByType(Application::class)) {
197
			$console = $builder->getDefinition($builder->getByType(Application::class));
198
		} else {
199
			$console = $builder->addDefinition($this->prefix('console'));
200
			$console->setFactory(Application::class, ['doctrine console']);
201
		}
202
203
		// create entity manager helper for orm commands
204
		$em = $builder->addDefinition($this->prefix('em'));
205
		$em->setFactory(EntityManagerHelper::class);
206
207
		// create connection helper for dbal commands
208
		$db = $builder->addDefinition($this->prefix('db'));
209
		$db->setFactory(ConnectionHelper::class, [$this->prefix('@connection')]);
210
211
		// create helper set
212
		if ($builder->findByType(HelperSet::class)) {
213
			$helpers = $builder->getDefinition($builder->getByType(HelperSet::class));
214
		} else {
215
			// default helper set
216
			$helpers = $builder->addDefinition($this->prefix('helpers'));
217
			$helpers->setFactory(HelperSet::class, [[
218
				new Statement(FormatterHelper::class),
219
				new Statement(DebugFormatterHelper::class),
220
				new Statement(ProcessHelper::class),
221
				new Statement(QuestionHelper::class),
222
			]]);
223
		}
224
225
		// add helpers to helper set
226
		$helpers->addSetup('set', [$this->prefix('@em'), 'em']);
227
		$helpers->addSetup('set', [$this->prefix('@db'), 'db']);
228
229
		// set helper set as application helper set
230
		$console->addSetup('setHelperSet');
231
232
		// add doctrine commands
233
		foreach ($config['console']['commands'] as $commandName => $class) {
234
			$commandServiceName = 'command_' . preg_replace('/[^a-z]/i', '_', $commandName);
235
			$command = $builder->addDefinition($this->prefix($commandServiceName));
236
			$command->setFactory($class);
237
			$command->addSetup('setName', [$commandName]);
238
			$console->addSetup('add', [$this->prefix("@$commandServiceName")]);
239
			$console->addTag('console', true);
240
		}
241
	}
242
}
243