Completed
Push — master ( a2c36c...334094 )
by yuuki
01:58
created

ContainerInterceptor::resolveContextualBindings()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 2
1
<?php
2
3
/**
4
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10
 * THE SOFTWARE.
11
 *
12
 * This software consists of voluntary contributions made by many individuals
13
 * and is licensed under the MIT license.
14
 *
15
 * Copyright (c) 2015-2016 Yuuki Takezawa
16
 *
17
 */
18
namespace Ytake\LaravelAspect;
19
20
use Ray\Aop\Bind;
21
use Illuminate\Container\Container;
22
use Ytake\LaravelAspect\Annotation\PostConstruct;
23
24
/**
25
 * Class ContainerInterceptor
26
 */
27
final class ContainerInterceptor
28
{
29
    /** @var Container */
30
    private $container;
31
32
    /**
33
     * ContainerInterceptor constructor.
34
     *
35
     * @param Container $container
36
     */
37
    public function __construct(Container $container)
38
    {
39
        $this->container = $container;
40
    }
41
42
    /**
43
     * @param string $abstract
44
     * @param Bind   $bind
45
     * @param string $className
46
     */
47
    public function intercept($abstract, Bind $bind, $className)
48
    {
49
        if (isset($this->container->contextual[$abstract])) {
50
            $this->resolveContextualBindings($abstract, $className);
51
        }
52
53
        $this->container->bind($abstract, function (Container $app) use ($bind, $className) {
54
            $instance = $app->make($className);
55
            $methods = unserialize($instance->methodAnnotations);
56
            foreach ($methods as $method => $annotations) {
57
                if (array_key_exists(PostConstruct::class, $annotations)) {
58
                    $instance->$method();
59
                }
60
            }
61
            $instance->bindings = $bind->getBindings();
62
63
            return $instance;
64
        });
65
    }
66
67
    /**
68
     * @param string $class
69
     * @param string $compiledClass
70
     */
71
    private function resolveContextualBindings($class, $compiledClass)
72
    {
73
        foreach ($this->container->contextual[$class] as $abstract => $concrete) {
74
            $this->container->when($compiledClass)
75
                ->needs($abstract)
76
                ->give($concrete);
77
        }
78
    }
79
}
80