Completed
Push — master ( 88b8c9...f7af16 )
by Michael
02:28
created

ManagesIocTrait   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 196
Duplicated Lines 3.57 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 14
Bugs 3 Features 3
Metric Value
wmc 24
c 14
b 3
f 3
lcom 1
cbo 3
dl 7
loc 196
rs 10

9 Methods

Rating   Name   Duplication   Size   Complexity  
A initDi() 0 5 1
A getIocManifest() 0 6 2
A fetch() 0 20 3
A di() 0 9 2
A share() 0 4 1
A setup() 0 4 1
A getDiItemsName() 0 4 1
A setDiItemsName() 0 5 1
C produceDependency() 7 62 12

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
namespace Michaels\Manager\Traits;
3
4
use Michaels\Manager\Contracts\IocContainerInterface;
5
use Michaels\Manager\Exceptions\ItemNotFoundException;
6
use Michaels\Manager\Messages\NoItemFoundMessage;
7
8
/**
9
 * Manages complex, nested data
10
 *
11
 * @implements Michaels\Manager\Contracts\ManagesItemsInterface
12
 * @package Michaels\Manager
13
 */
14
trait ManagesIocTrait
15
{
16
    use DependsOnManagesItemsTrait;
17
18
    /** @var string Name of the ioc manifest */
19
    protected $nameOfIocManifest = '_diManifest';
20
21
    /**
22
     * Initializes IoC Container
23
     * @param array $components
24
     * @return void
25
     */
26
    public function initDi(array $components = [])
27
    {
28
        $this->initManager();
29
        $this->add($this->nameOfIocManifest, $components);
30
    }
31
32
    /**
33
     * Returns the entire IoC Manifest
34
     * @return array
35
     */
36
    public function getIocManifest()
37
    {
38
        $manifest = $this->getIfExists($this->nameOfIocManifest);
39
40
        return ($manifest instanceof NoItemFoundMessage) ? [] : $manifest;
41
    }
42
43
    /**
44
     * Returns the request object with all dependencies
45
     *
46
     * string      Full class name for a new object each time
47
     * callable    Factory to create new object (passed manager)
48
     * object      The exact object to be returned
49
     *
50
     * @param string $alias
51
     * @param string|mixed $fallback
52
     * @return object
53
     * @throws \Exception
54
     */
55
    public function fetch($alias, $fallback = '_michaels_no_fallback')
56
    {
57
        $shared = $this->getIfExists($this->nameOfIocManifest . "._singletons.$alias");
58
59
        if ($shared instanceof NoItemFoundMessage) {
60
            // This is not a shared item. We want a new one each time
61
            return $this->produceDependency($alias, $fallback);
62
        } else {
63
            // This is shared, and object has already been cached
64
            if (is_object($shared)) {
65
                return $shared;
66
67
                // This is shared, but we must produce and cache it
68
            } else {
69
                $object = $this->produceDependency($alias, $fallback);
70
                $this->set($this->nameOfIocManifest . "._singletons.$alias", $object);
71
                return $object;
72
            }
73
        }
74
    }
75
76
    /**
77
     * Adds a dependency to the manager
78
     *
79
     * $factory can be a:
80
     *      string      Full class name for a new object each time
81
     *      callable    Factory to create new object (passed manager)
82
     *      object      The exact object to be returned
83
     *
84
     * @param string $alias
85
     * @param callable|string|object $factory
86
     * @param array $declared
87
     * @return void
88
     */
89
    public function di($alias, $factory, array $declared = null)
90
    {
91
        $this->set($this->nameOfIocManifest . ".$alias", $factory);
1 ignored issue
show
Documentation introduced by
$factory is of type callable, but the function expects a null.

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...
92
93
        // Setup any declared dependencies
94
        if ($declared) {
95
            $this->set($this->nameOfIocManifest . "._declarations.$alias", $declared);
1 ignored issue
show
Documentation introduced by
$declared is of type array, but the function expects a null.

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...
96
        }
97
    }
98
99
    /**
100
     * Turns a dependency into a singleton.
101
     * @param $alias
102
     * @return mixed
103
     */
104
    public function share($alias)
105
    {
106
        $this->add($this->nameOfIocManifest . "._singletons.$alias", true);
107
    }
108
109
    /**
110
     * Add a pipeline to to the que
111
     * @param $alias
112
     * @param $pipeline
113
     */
114
    public function setup($alias, $pipeline)
115
    {
116
        $this->add($this->nameOfIocManifest . "._pipelines.$alias", $pipeline);
117
    }
118
119
    /**
120
     * Returns the name of the property that holds data items
121
     * @return string
122
     */
123
    public function getDiItemsName()
124
    {
125
        return $this->nameOfIocManifest;
126
    }
127
128
    /**
129
     * Sets the name of the property that holds data items
130
     * @param $nameOfItemsRepository
131
     * @return $this
132
     */
133
    public function setDiItemsName($nameOfItemsRepository)
134
    {
135
        $this->nameOfIocManifest = $nameOfItemsRepository;
136
        return $this;
137
    }
138
139
    /**
140
     * Produces the object from an alias
141
     * @param string $alias
142
     * @param mixed|string $fallback
143
     * @return mixed
144
     * @throws ItemNotFoundException
145
     * @throws \Exception
146
     */
147
    protected function produceDependency($alias, $fallback = '_michaels_no_fallback')
148
    {
149
        /* Get the registered factory (string, closure, object, container, NoItemFoundMessage) */
150
        $factory = $this->getIfExists($this->nameOfIocManifest . ".$alias");
151
152
        /* Manage not founds and fallback */
153 View Code Duplication
        if ($factory instanceof NoItemFoundMessage) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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.

Loading history...
154
            if ($fallback !== '_michaels_no_fallback') {
155
                return $fallback;
156
            } else {
157
                throw new ItemNotFoundException("$alias not found");
158
            }
159
        }
160
161
        /* Get any declared dependencies */
162
        $declared = $this->getIfExists($this->nameOfIocManifest . "._declarations.$alias");
163
        $dependencies = [];
164
165
        // Now setup those dependencies into an array
166
        if (!$declared instanceof NoItemFoundMessage) {
167
            $dependencies = array_map(function(&$value) use ($alias) {
168
                if (is_string($value) && $this->exists($this->nameOfIocManifest . ".$alias")) {
169
                    return $this->fetch($value);
170
                }
171
                return $value;
172
            }, $declared);
173
        }
174
175
        /* Produce the object itself */
176
        if ($factory instanceof IocContainerInterface) {
177
            $object = $factory->fetch($alias);
178
179
        } elseif (is_string($factory)) {
180
            $class = new \ReflectionClass($factory);
181
            $object = $class->newInstanceArgs($dependencies);
182
183
        } elseif (is_callable($factory)) {
184
            array_unshift($dependencies, $this);
185
            $object = call_user_func_array($factory, $dependencies);
186
187
        } elseif (is_object($factory)) {
188
            $object = $factory;
189
190
            if (method_exists($object, "needs")) {
191
                call_user_func_array([$object, 'needs'], $dependencies);
192
            }
193
194
        } else {
195
            throw new \Exception("`fetch()` can only return from strings, callables, or objects");
196
        }
197
198
        /* Run the object through the pipeline, if desired */
199
        $pipeline = $this->getIfExists($this->nameOfIocManifest . "._pipelines.$alias");
200
201
        if (!$pipeline instanceof NoItemFoundMessage) {
202
            /** @var \Closure $pipeline */
203
            $object = $pipeline($object, $this);
204
        }
205
206
        /* Return the final object */
207
        return $object;
208
    }
209
}
210