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
|
8 |
|
public function __construct(Container $container) |
25
|
|
|
{ |
26
|
8 |
|
$this->container = $container; |
27
|
8 |
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Run the interaction. |
31
|
|
|
* |
32
|
|
|
* @param string $interaction |
33
|
|
|
* @param array $parameters |
34
|
|
|
* |
35
|
|
|
* @return mixed |
36
|
|
|
*/ |
37
|
4 |
|
public function interact($interaction, array $parameters = []) |
38
|
|
|
{ |
39
|
4 |
|
$interaction = $this->appendHandleMethod($interaction); |
40
|
|
|
|
41
|
4 |
|
list($class, $method) = explode('@', $interaction); |
42
|
|
|
|
43
|
4 |
|
$instance = $this->resolveInstance($class); |
44
|
|
|
|
45
|
2 |
|
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
|
4 |
|
protected function appendHandleMethod($interaction, $method = 'handle') |
57
|
|
|
{ |
58
|
4 |
|
if (!str_contains($interaction, '@')) { |
59
|
4 |
|
$interaction .= '@' . $method; |
60
|
|
|
} |
61
|
|
|
|
62
|
4 |
|
return $interaction; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Resolve the interaction instance. |
67
|
|
|
* |
68
|
|
|
* @param string $class |
69
|
|
|
* |
70
|
|
|
* @return InteractionContract |
71
|
|
|
*/ |
72
|
4 |
|
protected function resolveInstance($class) |
73
|
|
|
{ |
74
|
4 |
|
$instance = $this->container->make($class); |
75
|
|
|
|
76
|
4 |
|
if (!$instance instanceof InteractionContract) { |
77
|
2 |
|
throw new InvalidArgumentException(sprintf( |
78
|
2 |
|
'`%s` is not a valid interaction.', |
79
|
2 |
|
$class |
80
|
|
|
)); |
81
|
|
|
} |
82
|
|
|
|
83
|
2 |
|
return $instance; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|