Issues (536)

src/HotReloader/HotReloader.php (1 issue)

1
<?php
2
3
/**
4
 * This file is part of Blitz PHP framework.
5
 *
6
 * (c) 2022 Dimitri Sitchet Tomkeu <[email protected]>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace BlitzPHP\HotReloader;
13
14
/**
15
 * @internal
16
 *
17
 * @credit	<a href="https://codeigniter.com">CodeIgniter 4.6 - CodeIgniter\HotReloader\HotReloader</a>
18
 */
19
final class HotReloader
20
{
21
    public function run(): void
22
    {
23
        if (session_status() === PHP_SESSION_ACTIVE) {
24
            session_write_close();
25
        }
26
27
        ini_set('zlib.output_compression', 'Off');
28
29
        header('Cache-Control: no-store');
30
        header('Content-Type: text/event-stream');
31
        header('Access-Control-Allow-Methods: GET');
32
33
        ob_end_clean();
34
        set_time_limit(0);
35
36
        $hasher  = new DirectoryHasher();
37
        $appHash = $hasher->hash();
38
39
        while (true) {
40
            if (connection_status() !== CONNECTION_NORMAL || connection_aborted() === 1) {
41
                break;
42
            }
43
44
            $currentHash = $hasher->hash();
45
46
            // Si le hachage a changé, demandez au navigateur de se recharger.
47
            if ($currentHash !== $appHash) {
48
                $appHash = $currentHash;
0 ignored issues
show
The assignment to $appHash is dead and can be removed.
Loading history...
49
50
                $this->sendEvent('reload', ['time' => date('Y-m-d H:i:s')]);
51
                break;
52
            }
53
54
            if (mt_rand(1, 10) > 8) {
55
                $this->sendEvent('ping', ['time' => date('Y-m-d H:i:s')]);
56
            }
57
58
            sleep(1);
59
        }
60
    }
61
62
    /**
63
     * Envoyer un événement au navigateur.
64
     */
65
    private function sendEvent(string $event, array $data): void
66
    {
67
        echo "event: {$event}\n";
68
        echo 'data: ' . json_encode($data) . "\n\n";
69
70
        ob_flush();
71
        flush();
72
    }
73
}
74