@@ -12,26 +12,28 @@ final class Router implements RouterInterface
1212 private const NO_ROUTE = 404 ;
1313
1414 /**
15- * @var array <Route>
15+ * @var \ArrayIterator <Route>
1616 */
17- private $ routes = [];
17+ private $ routes ;
18+
19+ /**
20+ * @var UrlGenerator
21+ */
22+ private $ urlGenerator ;
1823
1924 /**
2025 * Router constructor.
2126 * @param $routes array<Route>
2227 */
2328 public function __construct (array $ routes = [])
2429 {
25- foreach ($ routes as $ route ) {
26- $ this ->add ($ route );
27- }
30+ $ this ->routes = new \ArrayIterator (array_unique ($ routes ));
31+ $ this ->urlGenerator = new UrlGenerator ($ this ->routes );
2832 }
2933
3034 public function add (Route $ route ): self
3135 {
32- if (in_array ($ route , $ this ->routes ) === false ) {
33- $ this ->routes [$ route ->getName ()] = $ route ;
34- }
36+ $ this ->routes ->offsetSet ($ route ->getName (), $ route );
3537 return $ this ;
3638 }
3739
@@ -57,32 +59,6 @@ public function matchFromPath(string $path, string $method): Route
5759
5860 public function generateUri (string $ name , array $ parameters = []): string
5961 {
60- if (array_key_exists ($ name , $ this ->routes ) === false ) {
61- throw new \InvalidArgumentException (
62- sprintf ('Unknown %s name route ' , $ name )
63- );
64- }
65- $ route = $ this ->routes [$ name ];
66- if ($ route ->hasVars () && $ parameters === []) {
67- throw new \InvalidArgumentException (
68- sprintf ('%s route need parameters: %s ' , $ name , implode (', ' , $ route ->getVarsNames ()))
69- );
70- }
71- return self ::resolveUri ($ route , $ parameters );
72- }
73-
74- private static function resolveUri (Route $ route , array $ parameters ): string
75- {
76- $ uri = $ route ->getPath ();
77- foreach ($ route ->getVarsNames () as $ variable ) {
78- $ varName = trim ($ variable , '{\} ' );
79- if (array_key_exists ($ varName , $ parameters ) === false ) {
80- throw new \InvalidArgumentException (
81- sprintf ('%s not found in parameters to generate url ' , $ varName )
82- );
83- }
84- $ uri = str_replace ($ variable , $ parameters [$ varName ], $ uri );
85- }
86- return $ uri ;
62+ return $ this ->urlGenerator ->generate ($ name , $ parameters );
8763 }
8864}
0 commit comments