DoctrineIdentityExtension::loadConfiguration()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SixtyEightPublishers\User\DoctrineIdentity\DI;
6
7
use Nette\Schema\Expect;
8
use Nette\Schema\Schema;
9
use Nette\Security\IUserStorage;
10
use SixtyEightPublishers\User\DI\AbstractCompilerExtensionPass;
11
use SixtyEightPublishers\User\Common\Exception\RuntimeException;
12
use SixtyEightPublishers\User\DoctrineIdentity\UserStorageProxy;
13
14
final class DoctrineIdentityExtension extends AbstractCompilerExtensionPass
15
{
16
	/**
17
	 * {@inheritDoc}
18
	 */
19
	public function startup(): void
20
	{
21
		parent::startup();
22
23
		if (!$this->config->enabled) {
24
			$this->stopPropagation();
25
		}
26
	}
27
28
	/**
29
	 * {@inheritDoc}
30
	 */
31
	public function getConfigSchema(): Schema
32
	{
33
		return Expect::structure([
34
			'enabled' => Expect::bool(FALSE),
35
			'namespace' => Expect::string()->nullable()->dynamic(),
36
		]);
37
	}
38
39
	/**
40
	 * {@inheritDoc}
41
	 */
42
	public function loadConfiguration(): void
43
	{
44
		$this->getContainerBuilder()
45
			->addDefinition($this->prefix('user_storage'))
46
			->setType(IUserStorage::class)
47
			->setFactory(UserStorageProxy::class);
48
	}
49
50
	/**
51
	 * {@inheritdoc}
52
	 */
53
	public function beforeCompile(): void
54
	{
55
		$builder = $this->getContainerBuilder();
56
		$userStorageProxy = $builder->getDefinition($this->prefix('user_storage'));
57
58
		foreach ($builder->findByType(IUserStorage::class) as $name => $userStorage) {
59
			if ($name !== $this->prefix('user_storage') && TRUE === $userStorage->getAutowired()) {
60
				break;
61
			}
62
		}
63
64
		if (!isset($userStorage)) {
65
			throw new RuntimeException(sprintf(
66
				'Autowired service of type %s not found.',
67
				IUserStorage::class
68
			));
69
		}
70
71
		$userStorage->setAutowired(FALSE);
72
73
		$userStorageProxy->setAutowired(TRUE);
74
		$userStorageProxy->setArguments([
75
			'userStorage' => $userStorage,
76
		]);
77
78
		if (NULL !== $this->config->namespace) {
79
			$userStorageProxy->addSetup('$service->setNamespace(?)', [
80
				'namespace' => $this->config->namespace,
81
			]);
82
		}
83
	}
84
}
85