Issues (19)

src/Hook.php (1 issue)

Severity
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cycle\ORM\Entity\Behavior;
6
7
use Cycle\ORM\Entity\Behavior\Schema\BaseModifier;
8
use Cycle\ORM\Entity\Behavior\Listener\Hook as Listener;
9
use Doctrine\Common\Annotations\Annotation\NamedArgumentConstructor;
10
use Doctrine\Common\Annotations\Annotation\Target;
11
use JetBrains\PhpStorm\ArrayShape;
12
13
/**
14
 * Hook allows easy listening for any event using callable.
15
 * The callback function can be a static function in the entity itself or in any other class.
16
 * As the first parameter, the callback function accepts an event in which
17
 * you can get the entity class and work with him.
18
 * The behavior has two parameters:
19
 *    - callable - callback function
20
 *    - events - string or array. One or several events during which callable will be called
21
 *
22
 * @Annotation
23
 * @NamedArgumentConstructor()
24
 * @Target({"CLASS"})
25
 */
26
#[\Attribute(\Attribute::TARGET_CLASS), NamedArgumentConstructor]
27
final class Hook extends BaseModifier
28
{
29
    /** @var callable */
30
    private $callable;
31
32
    /**
33
     * @psalm-param callable $callable Callable
34
     * @psalm-param class-string|non-empty-array<class-string> $events Listen events
35
     */
36 8
    public function __construct(
37
        callable $callable,
38
        private array|string $events,
39
    ) {
40 8
        $this->callable = $callable;
41
42 8
        if (\is_string($events)) {
0 ignored issues
show
The condition is_string($events) is always false.
Loading history...
43 8
            $this->events = [$events];
44
        }
45
    }
46
47 8
    protected function getListenerClass(): string
48
    {
49 8
        return Listener::class;
50
    }
51
52 8
    #[ArrayShape(['callable' => 'callable', 'events' => 'array'])]
53
    protected function getListenerArgs(): array
54
    {
55
        return [
56 8
            'callable' => $this->callable,
57 8
            'events' => $this->events,
58
        ];
59
    }
60
}
61