Hoa central
ClassMethod.php
Go to the documentation of this file.
1 <?php
2 
37 namespace Hoa\Dispatcher;
38 
39 use Hoa\Router;
40 use Hoa\View;
41 
51 class ClassMethod extends Dispatcher
52 {
62  protected function resolve(
63  Array $rule,
64  Router $router,
65  View\Viewable $view = null
66  ) {
67  $called = null;
68  $variables = &$rule[Router::RULE_VARIABLES];
69  $call = isset($variables['_call'])
70  ? $variables['_call']
71  : $rule[Router::RULE_CALL];
72  $able = isset($variables['_able'])
73  ? $variables['_able']
74  : $rule[Router::RULE_ABLE];
75  $rtv = [$router, $this, $view];
76  $arguments = [];
77  $reflection = null;
78 
79  $async = $router->isAsynchronous();
80  $class = $call;
81  $method = $able;
82 
83  if (false === $async) {
84  $_class = 'synchronous.call';
85  $_method = 'synchronous.able';
86  } else {
87  $_class = 'asynchronous.call';
88  $_method = 'asynchronous.able';
89  }
90 
91  $this->_parameters->setKeyword('call', $class);
92  $this->_parameters->setKeyword('able', $method);
93 
94  $class = $this->_parameters->getFormattedParameter($_class);
95  $method = $this->_parameters->getFormattedParameter($_method);
96 
97  try {
98  $class = dnew($class, $rtv);
99  } catch (\Exception $e) {
100  throw new Exception(
101  'Class %s is not found ' .
102  '(method: %s, asynchronous: %s).',
103  0,
104  [
105  $class,
106  strtoupper($variables['_method']),
107  true === $async
108  ? 'true'
109  : 'false'
110  ],
111  $e
112  );
113  }
114 
115  $kitname = $this->getKitName();
116 
117  if (!empty($kitname) &&
118  !isset($variables['_this']) ||
119  !(isset($variables['_this']) &&
120  ($variables['_this'] instanceof $kitname))) {
121  $variables['_this'] = dnew($kitname, $rtv);
122  $variables['_this']->construct();
123  }
124 
125  if (!method_exists($class, $method)) {
126  throw new Exception(
127  'Method %s does not exist on the class %s ' .
128  '(method: %s, asynchronous: %s).',
129  1,
130  [
131  $method,
132  get_class($class),
133  strtoupper($variables['_method']),
134  true === $async
135  ? 'true'
136  : 'false'
137  ]
138  );
139  }
140 
141  $called = $class;
142  $reflection = new \ReflectionMethod($class, $method);
143 
144  foreach ($reflection->getParameters() as $parameter) {
145  $name = strtolower($parameter->getName());
146 
147  if (true === array_key_exists($name, $variables)) {
148  $arguments[$name] = $variables[$name];
149 
150  continue;
151  }
152 
153  if (false === $parameter->isOptional()) {
154  throw new Exception(
155  'The method %s on the class %s needs a value for ' .
156  'the parameter $%s and this value does not exist.',
157  2,
158  [$method, get_class($class), $name]
159  );
160  }
161  }
162 
163  return $reflection->invokeArgs($called, $arguments);
164  }
165 }
const RULE_VARIABLES
Definition: Router.php:112
const RULE_CALL
Definition: Router.php:98
resolve(Array $rule, Router $router, View\Viewable $view=null)
Definition: ClassMethod.php:62