1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Knp\RadBundle\Resource\Resolver; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\DependencyInjection\ContainerInterface; |
6
|
|
|
use Symfony\Component\HttpFoundation\Request; |
7
|
|
|
use Symfony\Component\OptionsResolver\OptionsResolver; |
8
|
|
|
use Knp\RadBundle\Resource\Resolver\ResourceResolver; |
9
|
|
|
use Knp\RadBundle\Resource\Resolver\OptionsBased\ArgumentResolver; |
10
|
|
|
|
11
|
|
|
class OptionsBased implements ResourceResolver |
12
|
|
|
{ |
13
|
|
|
private $argumentResolver; |
14
|
|
|
private $optionsResolver; |
15
|
|
|
|
16
|
|
|
public function __construct(ContainerInterface $container, ArgumentResolver $argumentResolver = null) |
17
|
|
|
{ |
18
|
|
|
$this->container = $container; |
|
|
|
|
19
|
|
|
$this->argumentResolver = $argumentResolver ?: new ArgumentResolver; |
20
|
|
|
|
21
|
|
|
$this->optionsResolver = new OptionsResolver; |
22
|
|
|
$this->optionsResolver->setRequired(array('service', 'method')); |
23
|
|
|
$this->optionsResolver->setDefaults(array('arguments' => array())); |
24
|
|
|
$this->optionsResolver->setAllowedTypes(array( |
|
|
|
|
25
|
|
|
'service' => 'string', |
26
|
|
|
'method' => 'string', |
27
|
|
|
'arguments' => 'array', |
28
|
|
|
)); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function resolveResource(Request $request, array $options) |
32
|
|
|
{ |
33
|
|
|
$options = $this->optionsResolver->resolve($options); |
34
|
|
|
|
35
|
|
|
$arguments = array(); |
36
|
|
|
foreach ($options['arguments'] as $i => $argument) { |
37
|
|
|
if (is_string($argument)) { |
38
|
|
|
$arguments[] = $this->argumentResolver->resolveName($request, $argument); |
39
|
|
|
} else { |
40
|
|
|
try { |
41
|
|
|
$arguments[] = $this->argumentResolver->resolveArgument($request, $argument); |
42
|
|
|
} catch (\Exception $e) { |
43
|
|
|
throw new \RuntimeException( |
44
|
|
|
sprintf('Failed to resolve resource argument[%s].', $i), |
45
|
|
|
0, |
46
|
|
|
$e |
47
|
|
|
); |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
$service = $this->container->get($options['service']); |
53
|
|
|
$resolved = call_user_func_array(array($service, $options['method']), $arguments); |
54
|
|
|
|
55
|
|
|
if (null === $resolved) { |
56
|
|
|
throw new ResolutionFailureException('The resolution resulted in a NULL value.'); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return $resolved; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: