1 | <?php |
||
20 | class ExtReferenceConverter implements ExtReferenceConverterInterface |
||
21 | { |
||
22 | /** |
||
23 | * @var RouterInterface |
||
24 | */ |
||
25 | private $router; |
||
26 | /** |
||
27 | * @var array |
||
28 | */ |
||
29 | private $mapping; |
||
30 | /** |
||
31 | * @var Route[] |
||
32 | */ |
||
33 | private $resolvingCache; |
||
34 | |||
35 | /** |
||
36 | * Constructor |
||
37 | * |
||
38 | * @param RouterInterface $router Router |
||
39 | * @param array $mapping colleciton_name => service_id mapping |
||
40 | */ |
||
41 | 14 | public function __construct(RouterInterface $router, array $mapping) |
|
46 | |||
47 | /** |
||
48 | * return the extref from URL |
||
49 | * |
||
50 | * @param string $url Extref URL |
||
51 | * @return ExtReference |
||
52 | * @throws \InvalidArgumentException |
||
53 | */ |
||
54 | 6 | public function getExtReference($url) |
|
55 | { |
||
56 | 6 | $path = parse_url($url, PHP_URL_PATH); |
|
57 | 6 | if ($path === false) { |
|
58 | throw new \InvalidArgumentException(sprintf('URL %s', $url)); |
||
59 | } |
||
60 | |||
61 | 6 | $id = null; |
|
62 | 6 | $collection = null; |
|
63 | |||
64 | 6 | if (!isset($this->resolvingCache[$path])) { |
|
65 | 6 | foreach ($this->router->getRouteCollection()->all() as $route) { |
|
66 | 6 | list($collection, $id) = $this->getDataFromRoute($route, $path); |
|
67 | 6 | if ($collection !== null && $id !== null) { |
|
68 | 6 | $this->resolvingCache[$path] = $route; |
|
69 | 6 | return ExtReference::create($collection, $id); |
|
70 | } |
||
71 | 2 | } |
|
72 | } else { |
||
73 | list($collection, $id) = $this->getDataFromRoute($this->resolvingCache[$path], $path); |
||
74 | return ExtReference::create($collection, $id); |
||
75 | } |
||
76 | |||
77 | throw new \InvalidArgumentException(sprintf('Could not read URL %s', $url)); |
||
78 | } |
||
79 | |||
80 | /** |
||
81 | * return the URL from extref |
||
82 | * |
||
83 | * @param ExtReference $extReference Extref |
||
84 | * @return string |
||
85 | * @throws \InvalidArgumentException |
||
86 | */ |
||
87 | 4 | public function getUrl(ExtReference $extReference) |
|
88 | { |
||
89 | 4 | if (!isset($this->mapping[$extReference->getRef()])) { |
|
90 | throw new \InvalidArgumentException( |
||
91 | sprintf( |
||
92 | 'Could not create URL from extref "%s"', |
||
93 | json_encode($extReference) |
||
94 | ) |
||
95 | ); |
||
96 | } |
||
97 | |||
98 | 4 | return $this->router->generate( |
|
99 | 4 | $this->mapping[$extReference->getRef()].'.get', |
|
100 | 4 | ['id' => $extReference->getId()], |
|
101 | UrlGeneratorInterface::ABSOLUTE_URL |
||
102 | 4 | ); |
|
103 | } |
||
104 | |||
105 | /** |
||
106 | * get collection and id from route |
||
107 | * |
||
108 | * @param Route $route route to look at |
||
109 | * @param string $value value of reference as URI |
||
110 | * |
||
111 | * @return array |
||
112 | */ |
||
113 | 6 | private function getDataFromRoute(Route $route, $value) |
|
131 | } |
||
132 |