Hooks   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 8
eloc 20
c 2
b 1
f 0
dl 0
loc 47
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A register() 0 11 1
A theHookIsForTheModule() 0 11 3
A happening() 0 12 3
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Contains the Hooks class.
7
 *
8
 * @copyright   Copyright (c) 2021 Attila Fulop
9
 * @author      Attila Fulop
10
 * @license     MIT
11
 * @since       2021-11-19
12
 *
13
 */
14
15
namespace Konekt\Concord\Hooks;
16
17
use Illuminate\Support\Collection;
18
19
final class Hooks
20
{
21
    private Collection $hooks;
22
23
    public function __construct()
24
    {
25
        $this->hooks = collect();
26
    }
27
28
    public function register(HookEvent $event, callable $callback, array|string $filter = null): void
29
    {
30
        /** @var array{event: HookEvent, callback: callable, filter: string|array|null} */
31
        $hook = [
32
            'event' => $event,
33
            'callback' => $callback,
34
            'filter' => $filter,
35
        ];
36
37
        $this->hooks->add($hook);
38
        dump('r', $this->hooks->all());
39
    }
40
41
    public function happening(HookEvent $event, string $moduleId, mixed $hookableArgument): mixed
42
    {
43
        dump('h', $this->hooks->all());
44
        $hooks = $this->hooks->filter(
45
            fn ($hook, $index) => $event->equals($hook['event']) && $this->theHookIsForTheModule($hook['filter'], $moduleId)
0 ignored issues
show
Unused Code introduced by
The parameter $index is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

45
            fn ($hook, /** @scrutinizer ignore-unused */ $index) => $event->equals($hook['event']) && $this->theHookIsForTheModule($hook['filter'], $moduleId)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
46
        );
47
48
        foreach ($hooks as $hook) {
49
            $hookableArgument = call_user_func($hook['callback'], $moduleId, $hookableArgument);
50
        }
51
52
        return $hookableArgument;
53
    }
54
55
    private function theHookIsForTheModule(array|string|null $filter, string $moduleId): bool
56
    {
57
        if (null === $filter) {
0 ignored issues
show
introduced by
The condition null === $filter is always false.
Loading history...
58
            return true;
59
        }
60
61
        if (is_string($filter)) {
0 ignored issues
show
introduced by
The condition is_string($filter) is always false.
Loading history...
62
            return $filter === $moduleId;
63
        }
64
65
        return in_array($moduleId, $filter);
66
    }
67
}
68