Skip to content

Commit e3c9bc9

Browse files
Fix standalone actions: run sub-module hooks, short Action::$id, opt-in actionNamespace, exact actionMap routes. (#21162)
1 parent d30c39c commit e3c9bc9

11 files changed

Lines changed: 640 additions & 56 deletions

File tree

‎framework/CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ Yii Framework 2 Change Log
158158
- Chg #21059: Delegate `CaptchaValidator::getClientOptions()` to `clientScript`; fix `generateValidationHash()` `@return` to `int` (terabytesoftw)
159159
- Enh #21060: Add PSR-3 logging interoperability with `yii\log\PsrLogger` and `yii\log\PsrTarget` (terabytesoftw)
160160
- Enh #21061: Add precise PHPStan array shapes for logger messages, profiling timings, and target filtering; remove an unreachable dispatcher exception branch (terabytesoftw)
161+
- Bug #21162: Fix standalone actions: run sub-module hooks, short `Action::$id`, opt-in `actionNamespace`, exact `actionMap` routes (terabytesoftw)
161162

162163
2.0.56 under development
163164
------------------------

‎framework/UPGRADE-22.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,21 @@ Yii2 `22.0` adds standalone action discovery through `Module::$actionMap`, `Modu
348348
- `Module::$actionMap` is consulted by the module whose `runAction()` handles the route. It is not recursively resolved
349349
through child modules. Use the child module's `actionNamespace`, or register the action in the dispatching module's
350350
`actionMap`.
351+
- A `Module::$actionMap` key matches only the exact route, trimmed of leading and trailing slashes. A longer route that
352+
starts with a key, such as `health/status` for a `health` key, is not dispatched to the mapped action: it goes through
353+
the controller pipeline and raises `InvalidRouteException` when nothing else resolves it. A key that contains a slash
354+
matches that full route.
355+
- Convention-based discovery is opt-in. `Module::$actionNamespace` has no default: while it is `null` or an empty
356+
string, the module (application or sub-module) resolves no route to a standalone action class, and a sub-module does
357+
not inherit the setting of its parent. Set `'actionNamespace' => 'app\\controllers'` to keep standalone actions next
358+
to controllers. Only the exact spelling of the class name resolves, and abstract classes are never dispatched.
359+
- For an action discovered through `actionNamespace`, `Action::$id` is the last route segment (`delete` for the route
360+
`post/delete`), and `Action::getUniqueId()` returns the full route including the owning module (`admin/post/delete`).
361+
Key `VerbFilter::$actions`, `AccessRule::$actions`, and the `only`/`except` lists of filters attached to the action by
362+
the short ID. Filters attached to a module match the route relative to that module, as for controller actions.
363+
- A discovered action runs through the lifecycle of every module from the application down to the module that owns
364+
it: `beforeAction()` outermost first and `afterAction()` innermost first, including their events and behaviors, so
365+
module-level access control applies to standalone actions as it does to controller actions.
351366

352367
## Database abstraction layer
353368

‎framework/base/Action.php‎

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,10 @@ class Action extends Component
5151
/**
5252
* @var string|null ID of the action; `null` between construction and dispatcher post-assignment for standalone
5353
* actions resolved through {@see Module::$actionMap} or {@see Module::$actionNamespace}.
54+
*
55+
* A standalone action receives its {@see Module::$actionMap} key, or the last route segment when it is discovered
56+
* through {@see Module::$actionNamespace} (for example `delete` for the route `post/delete`). Filters keyed by action
57+
* ID, such as {@see \yii\filters\VerbFilter::$actions}, use this value; {@see getUniqueId()} returns the full route.
5458
*/
5559
public $id;
5660
/**
@@ -65,6 +69,11 @@ class Action extends Component
6569
* @since 22.0
6670
*/
6771
private Module|null $_module = null;
72+
/**
73+
* Route segments between the owning module and the action ID of a standalone action discovered through
74+
* {@see Module::$actionNamespace}, without leading or trailing slashes; empty otherwise.
75+
*/
76+
private string $_routePrefix = '';
6877

6978
/**
7079
* Constructor.
@@ -87,8 +96,9 @@ public function __construct($id = null, $controller = null, $config = [])
8796
*
8897
* When the action is hosted by a controller, the ID is composed of the controller's unique ID and the action ID.
8998
*
90-
* For standalone handlers (no controller), the ID falls back to the owning module's unique ID, or to the action ID
91-
* alone when no module is attached.
99+
* For standalone handlers (no controller), the ID is composed of the owning module's unique ID and the route
100+
* relative to that module (for example `admin/post/delete`), or of that route alone when no module is attached or
101+
* the module is the application.
92102
*
93103
* @return string The unique ID of this action among the whole application.
94104
*/
@@ -101,7 +111,9 @@ public function getUniqueId()
101111
$module = $this->getModule();
102112
$moduleId = $module !== null ? $module->getUniqueId() : '';
103113

104-
return $moduleId === '' ? $this->id : $moduleId . '/' . $this->id;
114+
$route = $this->_routePrefix === '' ? $this->id : "{$this->_routePrefix}/{$this->id}";
115+
116+
return $moduleId === '' ? $route : "{$moduleId}/{$route}";
105117
}
106118

107119
/**
@@ -136,6 +148,22 @@ public function setModule(Module|null $module): void
136148
$this->_module = $module;
137149
}
138150

151+
/**
152+
* Sets the route segments between the owning module and the action ID, so that {@see getUniqueId()} returns the
153+
* full route of a standalone action discovered through {@see Module::$actionNamespace}.
154+
*
155+
* Used by {@see Module::createStandaloneAction()} only; application code does not need to call it.
156+
*
157+
* @param string $prefix The route segments without leading or trailing slashes (for example `post` for the route
158+
* `post/delete`), or an empty string when the action ID is the whole route.
159+
*
160+
* @since 22.0
161+
*/
162+
public function setRoutePrefix(string $prefix): void
163+
{
164+
$this->_routePrefix = $prefix;
165+
}
166+
139167
/**
140168
* Runs this action with the specified parameters.
141169
*

‎framework/base/Module.php‎

Lines changed: 55 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
namespace yii\base;
1212

13+
use ReflectionClass;
1314
use Yii;
1415
use yii\di\ServiceLocator;
1516

@@ -106,8 +107,9 @@ class Module extends ServiceLocator
106107
* configurations. Mapped actions are dispatched by {@see runAction()} without requiring a hosting controller, in
107108
* parallel to {@see $controllerMap}.
108109
*
109-
* Each entry maps an ID (the first route segment) to either a fully qualified class name or an array configuration
110-
* accepted by {@see \Yii::createObject()}. The class must extend {@see Action}.
110+
* Each entry maps a route relative to this module, without leading or trailing slashes, to either a fully qualified
111+
* class name or an array configuration accepted by {@see \Yii::createObject()}. The class must extend
112+
* {@see Action}. The key becomes the action's {@see Action::$id}.
111113
*
112114
* Usage example:
113115
*
@@ -118,14 +120,17 @@ class Module extends ServiceLocator
118120
* ]
119121
* ```
120122
*
121-
* Action IDs in this map take precedence over IDs in {@see $controllerMap} and over module/controller resolution.
123+
* A key takes precedence over {@see $controllerMap} and over module/controller resolution for the exact route only.
122124
*
123-
* Routes whose first segment is not present here fall through to the legacy controller pipeline unchanged.
125+
* Routes that do not equal a key fall through to the legacy controller pipeline unchanged, including longer routes
126+
* that start with a key (for example `health/status` with a `health` key), so a sub-module or controller with the
127+
* same first segment still handles them.
124128
*
125129
* Resolution scope: this map is consulted only by the module whose {@see runAction()} handles the route (typically
126130
* the application). Unlike {@see $controllerMap}, it is NOT resolved recursively across sub-modules during
127-
* nested-route dispatch. To expose a standalone action under a sub-module, rely on {@see $actionNamespace} (which
128-
* IS resolved recursively), or register the action in the dispatching module's {@see $actionMap}.
131+
* nested-route dispatch. To expose a standalone action under a sub-module, set the sub-module's
132+
* {@see $actionNamespace} (which IS resolved recursively), or register the action in the dispatching module's
133+
* {@see $actionMap}.
129134
*
130135
* @since 22.0
131136
*/
@@ -147,9 +152,11 @@ class Module extends ServiceLocator
147152
* The namespace where standalone {@see Action} subclasses are located for convention-based discovery, parallel to
148153
* {@see $controllerNamespace} for controllers.
149154
*
150-
* If not set, defaults to the value of {@see $controllerNamespace} during {@see init()}, so standalone actions can
151-
* live next to controllers under the same root. Set this property to a different namespace to organize standalone
152-
* actions in their own folder (for example, vertical slices under `app\UseCase`):
155+
* Discovery is opt-in: when this property is `null` (the default) or an empty string, the module resolves no route
156+
* to a standalone action by convention, on applications and sub-modules alike, and a sub-module does not inherit
157+
* the setting of its parent. Set it to the value of {@see $controllerNamespace} to keep standalone actions next to
158+
* controllers, or to a different namespace to organize them in their own folder (for example, vertical slices
159+
* under `app\UseCase`):
153160
*
154161
* Usage example:
155162
*
@@ -159,7 +166,9 @@ class Module extends ServiceLocator
159166
*
160167
* With the example above, route `posts/index` resolves to `app\UseCase\posts\IndexAction`, route
161168
* `posts/view-summary` resolves to `app\UseCase\posts\ViewSummaryAction`, and so on. The same hyphen, slash, and
162-
* CamelCase rules apply as for controllers (see {@see createControllerByID()}).
169+
* CamelCase rules apply as for controllers (see {@see createControllerByID()}). Only the exact spelling of the
170+
* class name resolves. The discovered action's {@see Action::$id} is the last route segment (`view-summary`), and
171+
* {@see Action::getUniqueId()} returns the full route.
163172
*
164173
* Resolution order in {@see runAction()}: explicit {@see $controllerMap}/{@see $actionMap} entries are checked
165174
* first, then sub-modules, then controllers by namespace, and finally standalone actions by namespace. When a
@@ -272,10 +281,6 @@ public function init()
272281
$this->controllerNamespace = substr($class, 0, $pos) . '\\controllers';
273282
}
274283
}
275-
276-
if ($this->actionNamespace === null) {
277-
$this->actionNamespace = $this->controllerNamespace;
278-
}
279284
}
280285

281286
/**
@@ -608,12 +613,13 @@ public function setModules($modules)
608613
*
609614
* If the route is empty, the method will use [[defaultRoute]].
610615
*
611-
* Since version 22.0, when the first segment of the route matches a key in [[actionMap]], the action is dispatched
612-
* as a standalone action via [[runMappedAction()]], without resolving a controller. When no controller resolves the
613-
* route either, the method falls back to convention-based standalone action lookup under [[actionNamespace]] via
614-
* [[createStandaloneAction()]]. When a controller method AND a standalone Action class both match the same route,
615-
* the method throws [[InvalidConfigException]] so the developer disambiguates instead of silently shadowing one or
616-
* the other.
616+
* Since version 22.0, when the route, trimmed of leading and trailing slashes, equals a key in [[actionMap]], the
617+
* action is dispatched as a standalone action via [[runMappedAction()]], without resolving a controller. When no
618+
* controller resolves the route either, the method falls back to convention-based standalone action lookup under
619+
* [[actionNamespace]] via [[createStandaloneAction()]]; the resulting action runs through the lifecycle of the
620+
* module that owns it and of every ancestor of that module. When a controller method AND a standalone Action class
621+
* both match the same route, the method throws [[InvalidConfigException]] so the developer disambiguates instead
622+
* of silently shadowing one or the other.
617623
*
618624
* @param string $route The route that specifies the action.
619625
* @param array $params The parameters to be passed to the action.
@@ -627,13 +633,8 @@ public function runAction($route, $params = [])
627633
{
628634
$normalizedRoute = trim((string) $route, '/');
629635

630-
if ($normalizedRoute !== '' && $this->actionMap !== []) {
631-
$separator = strpos($normalizedRoute, '/');
632-
$actionId = $separator === false ? $normalizedRoute : substr($normalizedRoute, 0, $separator);
633-
634-
if (isset($this->actionMap[$actionId])) {
635-
return $this->runMappedAction($actionId, $params);
636-
}
636+
if ($normalizedRoute !== '' && isset($this->actionMap[$normalizedRoute])) {
637+
return $this->runMappedAction($normalizedRoute, $params);
637638
}
638639

639640
$parts = $this->createController($route);
@@ -724,8 +725,13 @@ protected function runMappedAction(string $id, array $params): mixed
724725
* CamelCased class name with an `Action` suffix, the preceding segments form a sub-namespace prefix, and the result
725726
* is looked up under the owning module's [[actionNamespace]].
726727
*
727-
* The resolved class must extend [[Action]] and must NOT extend [[Controller]]; otherwise this method returns
728-
* `null` and the caller falls through to the controller pipeline (or to `InvalidRouteException`).
728+
* The resolved class must be declared with exactly the computed name, so case and hyphen variants of a route do not
729+
* resolve, must extend [[Action]], must NOT extend [[Controller]], and must be instantiable (not abstract, no
730+
* private constructor); otherwise this method returns `null` and the caller falls through to the controller
731+
* pipeline (or to `InvalidRouteException`).
732+
*
733+
* The returned action is owned by the module that resolved it. Its [[Action::$id]] is the last route segment, and
734+
* [[Action::getUniqueId()]] returns the full route including the owning module's unique ID.
729735
*
730736
* @param string $route The route relative to this module.
731737
*
@@ -788,15 +794,26 @@ protected function createStandaloneAction(string $route): Action|null
788794
return null;
789795
}
790796

797+
$reflection = new ReflectionClass($className);
798+
799+
if ($reflection->getName() !== $className) {
800+
return null;
801+
}
802+
791803
if (!is_subclass_of($className, Action::class) || is_subclass_of($className, Controller::class)) {
792804
return null;
793805
}
794806

807+
if (!$reflection->isInstantiable()) {
808+
return null;
809+
}
810+
795811
/** @var Action $action */
796812
$action = Yii::createObject($className);
797813

798-
$action->id = $route;
814+
$action->id = $idPart;
799815

816+
$action->setRoutePrefix(rtrim($prefix, '/'));
800817
$action->setModule($this);
801818

802819
return $action;
@@ -805,8 +822,10 @@ protected function createStandaloneAction(string $route): Action|null
805822
/**
806823
* Runs a standalone {@see Action} instance through the standard module/action event lifecycle.
807824
*
808-
* Module ancestors fire [[EVENT_BEFORE_ACTION]] outer-to-inner before execution and [[EVENT_AFTER_ACTION]]
809-
* inner-to-outer afterwards, mirroring [[Controller::runAction()]]. The action itself also fires
825+
* The module chain starts at the module that owns the action ({@see Action::getModule()}, or this module when the
826+
* action has none) and includes every ancestor up to the application. The chain fires [[EVENT_BEFORE_ACTION]]
827+
* outer-to-inner before execution and [[EVENT_AFTER_ACTION]] inner-to-outer afterwards, mirroring
828+
* [[Controller::runAction()]]. The action itself also fires
810829
* [[Controller::EVENT_BEFORE_ACTION]] and [[Controller::EVENT_AFTER_ACTION]] so behaviors attached via the action's
811830
* [[behaviors()]] (for example [[\yii\filters\AccessControl]] or [[\yii\filters\VerbFilter]]) participate in the
812831
* lifecycle.
@@ -826,8 +845,10 @@ protected function runStandaloneAction(Action $action, array $params): mixed
826845
Yii::$app->requestedAction = $action;
827846
}
828847

829-
$modulesOuterToInner = [$this];
830-
$ancestor = $this->module;
848+
$owner = $action->getModule() ?? $this;
849+
850+
$modulesOuterToInner = [$owner];
851+
$ancestor = $owner->module;
831852

832853
while ($ancestor !== null) {
833854
array_unshift($modulesOuterToInner, $ancestor);

‎framework/web/Action.php‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@
2626
* HTTP-specific scalar filtering and exception mapping. Reserve that base class for non-HTTP contexts (console actions,
2727
* queue jobs, scheduled tasks).
2828
*
29-
* Usage example:
29+
* Usage example, handling the route `health` once the application sets `'actionNamespace' => 'app\\controllers'`
30+
* (discovery is disabled until then) or maps the class in [[\yii\base\Module::$actionMap]]:
3031
*
3132
* ```php
3233
* namespace app\controllers;

‎tests/framework/base/ModuleActionMapTest.php‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,52 @@ public function testActionMapTakesPrecedenceOverControllerMap(): void
7878
);
7979
}
8080

81+
public function testMappedActionMatchesRouteWithSurroundingSlashes(): void
82+
{
83+
$module = new Module('mymod');
84+
85+
$module->actionMap = ['ping' => PingAction::class];
86+
87+
self::assertSame(
88+
'pong-slash',
89+
$module->runAction('/ping/', ['name' => 'slash']),
90+
'Surrounding slashes must be ignored when matching a key.',
91+
);
92+
}
93+
94+
public function testLongerRouteFallsThroughToControllerMapWhenFirstSegmentIsMappedAction(): void
95+
{
96+
$module = new Module('mymod');
97+
98+
$module->controllerMap = ['ping' => PingController::class];
99+
$module->actionMap = ['ping' => PingAction::class];
100+
101+
self::assertSame(
102+
'pong-exact',
103+
$module->runAction('ping', ['name' => 'exact']),
104+
'Exact route must run the mapped action.',
105+
);
106+
self::assertSame(
107+
'legacy:hello',
108+
$module->runAction('ping/echo'),
109+
'Longer route must reach the controller with the same first segment.',
110+
);
111+
}
112+
113+
public function testThrowInvalidRouteExceptionWhenMappedActionRouteHasTrailingSegments(): void
114+
{
115+
$module = new Module('mymod');
116+
117+
$module->actionMap = ['ping' => PingAction::class];
118+
119+
$this->expectException(InvalidRouteException::class);
120+
$this->expectExceptionMessage(
121+
'Unable to resolve the request "mymod/ping/anything/else".',
122+
);
123+
124+
$module->runAction('ping/anything/else', ['name' => 'suffix']);
125+
}
126+
81127
public function testActionNotInMapFallsThroughToControllerPipeline(): void
82128
{
83129
$module = new Module('mymod');

0 commit comments

Comments
 (0)