Issues (33)

src/Traits/WatcherTrait.php (2 issues)

1
<?php
2
declare(strict_types=1);
3
4
namespace Utilities\Router\Traits;
5
6
use Utilities\Common\Common;
7
use Utilities\Common\Connection;
8
use Utilities\Common\Loop;
9
10
/**
11
 * WatcherTrait class
12
 *
13
 * @link    https://github.com/utilities-php/router
14
 * @author  Shahrad Elahi (https://github.com/shahradelahi)
15
 * @license https://github.com/utilities-php/router/blob/master/LICENSE (MIT License)
16
 */
17
trait WatcherTrait
18
{
19
20
    /**
21
     * Add a watcher.
22
     *
23
     * @param array $watchers [['key', 'class', 'interval'], ...]
24
     * @return void
25
     */
26
    public function addWatcher(array $watchers): void
27
    {
28
        foreach ($watchers as $watcher) {
29
            if (!is_array($watcher) || !is_string($watcher['class']) || !is_numeric($watcher['interval'])) {
30
                throw new \RuntimeException(sprintf(
31
                    'The watcher `%s` is not valid.',
32
                    $watcher
33
                ));
34
            }
35
36
            if (!method_exists($watcher['class'], '__run')) {
37
                throw new \RuntimeException(sprintf(
38
                    'The watcher `%s` does not have a __run method.',
39
                    $watcher['class']
40
                ));
41
            }
42
43
            $this->watchers[] = $watcher;
0 ignored issues
show
Bug Best Practice introduced by
The property watchers does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
44
        }
45
    }
46
47
    /**
48
     * execute the watchers
49
     *
50
     * @return void
51
     */
52
    private function runWatchers(): void
53
    {
54
        header('Content-Type: application/json');
55
56
        Connection::closeConnection(Common::prettyJson([
57
            'ok' => true,
58
            'message' => 'Services are running...'
59
        ]));
60
61
        $last_runs = [];
62
        $startTime = time();
63
        Loop::run(function () use (&$last_runs, $startTime) {
64
            if (time() - $startTime > 60) {
65
                Loop::stop();
66
            }
67
68
            foreach ($this->watchers as $watcher) {
69
                if (time() - $last_runs[$watcher['key']] >= $watcher['interval']) {
70
                    (new $watcher['class']())->__run();
71
                    $last_runs[$watcher['key']] = time();
72
                }
73
            }
74
        });
75
76
        die(200);
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
77
    }
78
79
}