Skip to content

Commit 3167dc8

Browse files
authored
Initialize property and guard hasMethod() (#320)
1 parent 807f9cb commit 3167dc8

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

src/Concerns/DecorateActions.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
trait DecorateActions
66
{
7-
protected mixed $action;
7+
protected mixed $action = null;
88

99
public function setAction($action): self
1010
{
@@ -30,7 +30,7 @@ protected function getProperty(string $property)
3030

3131
protected function hasMethod(string $method): bool
3232
{
33-
return method_exists($this->action, $method);
33+
return isset($this->action) && method_exists($this->action, $method);
3434
}
3535

3636
protected function callMethod(string $method, array $parameters = [])

tests/DecorateActionsTest.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
use Lorisleiva\Actions\ActionRequest;
4+
5+
beforeEach(function () {
6+
$this->request = new class extends ActionRequest {
7+
public function authorize(): bool { return true; }
8+
public function rules(): array { return []; }
9+
public function handle() { /* no-op */ }
10+
};
11+
12+
$method = new \ReflectionMethod($this->request, 'hasMethod');
13+
$method->setAccessible(true);
14+
$this->hasMethod = $method;
15+
});
16+
17+
it('returns false and does not throw when action is uninitialized', function () {
18+
expect($this->hasMethod->invoke($this->request, 'anything'))
19+
->toBeFalse();
20+
});
21+
22+
it('returns true for an existing method after setAction()', function () {
23+
// A dummy action object declaring customFoo()
24+
$dummyAction = new class {
25+
public function customFoo(): string
26+
{
27+
return 'bar';
28+
}
29+
};
30+
31+
// Initialize the request’s $action
32+
$this->request->setAction($dummyAction);
33+
34+
expect($this->hasMethod->invoke($this->request, 'customFoo'))
35+
->toBeTrue();
36+
});

0 commit comments

Comments
 (0)