@@ -42,17 +42,42 @@ public function __construct(UriInterface $uri)
4242 }
4343
4444 /**
45+ * Adds a prefix in the beginning of the URL's path.
46+ *
47+ * The prefix is not added if that prefix is already on the URL's path. This will fail on the edge
48+ * case of the prefix being repeated, for example if `https://example.com/api/api/foo` is a valid
49+ * URL on the server and the configured prefix is `/api`.
50+ *
51+ * We looked at other solutions, but they are all much more complicated, while still having edge
52+ * cases:
53+ * - Doing an spl_object_hash on `$first` will lead to collisions over time because over time the
54+ * hash can collide.
55+ * - Have the PluginClient provide a magic header to identify the request chain and only apply
56+ * this plugin once.
57+ *
58+ * There are 2 reasons for the AddPathPlugin to be executed twice on the same request:
59+ * - A plugin can restart the chain by calling `$first`, e.g. redirect
60+ * - A plugin can call `$next` more than once, e.g. retry
61+ *
62+ * Depending on the scenario, the path should or should not be added. E.g. `$first` could
63+ * be called after a redirect response from the server. The server likely already has the
64+ * correct path.
65+ *
66+ * No solution fits all use cases. This implementation will work fine for the common use cases.
67+ * If you have a specific situation where this is not the right thing, you can build a custom plugin
68+ * that does exactly what you need.
69+ *
4570 * {@inheritdoc}
4671 */
4772 public function handleRequest (RequestInterface $ request , callable $ next , callable $ first )
4873 {
49- $ identifier = spl_object_hash ((object ) $ first );
74+ $ prepend = $ this ->uri ->getPath ();
75+ $ path = $ request ->getUri ()->getPath ();
5076
51- if (! array_key_exists ( $ identifier , $ this -> alteredRequests ) ) {
77+ if (substr ( $ path , 0 , strlen ( $ prepend )) !== $ prepend ) {
5278 $ request = $ request ->withUri ($ request ->getUri ()
53- ->withPath ($ this ->uri ->getPath ().$ request ->getUri ()->getPath ())
54- );
55- $ this ->alteredRequests [$ identifier ] = $ identifier ;
79+ ->withPath ($ prepend .$ path )
80+ );
5681 }
5782
5883 return $ next ($ request );
0 commit comments