Completed
Pull Request — master (#1)
by Evgenii
07:26
created

Interactor::appendHandleMethod()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
c 0
b 0
f 0
ccs 5
cts 5
cp 1
rs 9.4285
cc 2
eloc 4
nc 2
nop 2
crap 2
1
<?php
2
3
namespace Nasyrov\Laravel\Interactions;
4
5
use Illuminate\Contracts\Container\Container;
6
use InvalidArgumentException;
7
use Nasyrov\Laravel\Interactions\Contracts\Interaction as InteractionContract;
8
use Nasyrov\Laravel\Interactions\Contracts\Interactor as InteractorContract;
9
10
class Interactor implements InteractorContract
11
{
12
    /**
13
     * The container implementation.
14
     *
15
     * @var Container
16
     */
17
    protected $container;
18
19
    /**
20
     * Create a new interactor instance.
21
     *
22
     * @param Container $container
23
     */
24 9
    public function __construct(Container $container)
25
    {
26 9
        $this->container = $container;
27 9
    }
28
29
    /**
30
     * Dispatch an interaction to its appropriate handler.
31
     *
32
     * @param mixed $interaction
33
     * @param array $parameters
34
     *
35
     * @return mixed
36
     */
37 6
    public function interact($interaction, array $parameters = [])
38
    {
39 6
        $interaction = $this->appendHandleMethod($interaction);
40
41 6
        list($class, $method) = explode('@', $interaction);
42
43 6
        $instance = $this->resolveInstance($class);
44
45 3
        return call_user_func_array([$instance, $method], $parameters);
46
    }
47
48
    /**
49
     * Append the interaction handle method.
50
     *
51
     * @param string $interaction
52
     * @param string $method
53
     *
54
     * @return string
55
     */
56 6
    protected function appendHandleMethod($interaction, $method = 'handle')
57
    {
58 6
        if (!str_contains($interaction, '@')) {
59 6
            $interaction .= '@' . $method;
60 2
        }
61
62 6
        return $interaction;
63
    }
64
65
    /**
66
     * Resolve the interaction instance.
67
     *
68
     * @param string $class
69
     *
70
     * @return InteractionContract
71
     */
72 6
    protected function resolveInstance($class)
73
    {
74 6
        $instance = $this->container->make($class);
75
76 6
        if (!$instance instanceof InteractionContract) {
77 3
            throw new InvalidArgumentException(sprintf(
78 3
                '`%s` is not a valid interaction.',
79 1
                $class
80 1
            ));
81
        }
82
83 3
        return $instance;
84
    }
85
}
86