1
|
|
|
<?php declare(strict_types = 1); |
2
|
|
|
|
3
|
|
|
namespace LidskaSila\Prooph\Common; |
4
|
|
|
|
5
|
|
|
use LidskaSila\Prooph\Common\NetteContainerWrapper\ContainerException; |
6
|
|
|
use LidskaSila\Prooph\Common\NetteContainerWrapper\NotFoundException; |
7
|
|
|
use Nette\DI\Container; |
8
|
|
|
use Nette\DI\MissingServiceException; |
9
|
|
|
use Psr\Container\ContainerInterface; |
10
|
|
|
use Throwable; |
11
|
|
|
|
12
|
|
|
class NetteContainerWrapper implements ContainerInterface |
13
|
|
|
{ |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @var Container |
17
|
|
|
*/ |
18
|
|
|
private $container; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var array |
22
|
|
|
*/ |
23
|
|
|
private $config; |
24
|
|
|
|
25
|
|
|
public function __construct(array $extensionConfig, Container $container) |
26
|
|
|
{ |
27
|
|
|
$this->config = $extensionConfig; |
28
|
|
|
$this->container = $container; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* {@inheritdoc} |
33
|
|
|
*/ |
34
|
|
|
public function get($key) |
35
|
|
|
{ |
36
|
|
|
try { |
37
|
|
|
return $this->tryToGetByKey($key); |
38
|
|
|
} catch (MissingServiceException $e) { |
39
|
|
|
throw new NotFoundException($e->getMessage()); |
40
|
|
|
} catch (Throwable $e) { |
41
|
|
|
throw new ContainerException($e->getMessage()); |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* {@inheritdoc} |
47
|
|
|
*/ |
48
|
|
View Code Duplication |
public function has($key) |
|
|
|
|
49
|
|
|
{ |
50
|
|
|
if ($this->isKeyConfig($key)) { |
51
|
|
|
return (bool) $this->config; |
52
|
|
|
} |
53
|
|
|
if ($this->isServiceId($key)) { |
54
|
|
|
return $this->container->hasService($this->extractServiceId($key)); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
return (bool) $this->container->getByType($key); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
View Code Duplication |
private function tryToGetByKey($key) |
|
|
|
|
61
|
|
|
{ |
62
|
|
|
if ($this->isKeyConfig($key)) { |
63
|
|
|
return $this->config; |
64
|
|
|
} |
65
|
|
|
if ($this->isServiceId($key)) { |
66
|
|
|
return $this->container->getService($this->extractServiceId($key)); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return $this->container->getByType($key); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
private function isKeyConfig(string $key): bool |
73
|
|
|
{ |
74
|
|
|
return $key === 'config'; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
private function isServiceId(string $key): bool |
78
|
|
|
{ |
79
|
|
|
return strpos($key, '@') === 0; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
private function extractServiceId(string $key): string |
83
|
|
|
{ |
84
|
|
|
return ltrim($key, '@'); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.