summaryrefslogtreecommitdiffstats
path: root/library/Icinga/Application/Hook/ApplicationStateHook.php
blob: be973feaaeb71d2d4239409a25778e63cc53f9fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
/* Icinga Web 2 | (c) 2018 Icinga Development Team | GPLv2+ */

namespace Icinga\Application\Hook;

use Icinga\Application\Hook;
use Icinga\Application\Logger;

/**
 * Application state hook base class
 */
abstract class ApplicationStateHook
{
    const ERROR = 'error';

    private $messages = [];

    final public function hasMessages()
    {
        return ! empty($this->messages);
    }

    final public function getMessages()
    {
        return $this->messages;
    }

    /**
     * Add an error message
     *
     * The timestamp of the message is used for deduplication and thus must refer to the time when the error first
     * occurred. Don't use {@link time()} here!
     *
     * @param   string  $id         ID of the message. The ID must be prefixed with the module name
     * @param   int     $timestamp  Timestamp when the error first occurred
     * @param   string  $message    Error message
     *
     * @return  $this
     */
    final public function addError($id, $timestamp, $message)
    {
        $id = trim($id);
        $timestamp = (int) $timestamp;

        if (! strlen($id)) {
            throw new \InvalidArgumentException('ID expected.');
        }

        if (! $timestamp) {
            throw new \InvalidArgumentException('Timestamp expected.');
        }

        $this->messages[sha1($id . $timestamp)] = [self::ERROR, $timestamp, $message];

        return $this;
    }

    /**
     * Override this method in order to provide application state messages
     */
    abstract public function collectMessages();

    final public static function getAllMessages()
    {
        $messages = [];

        if (! Hook::has('ApplicationState')) {
            return $messages;
        }

        foreach (Hook::all('ApplicationState') as $hook) {
            /** @var self $hook */
            try {
                $hook->collectMessages();
            } catch (\Exception $e) {
                Logger::error(
                    "Failed to collect messages from hook '%s'. An error occurred: %s",
                    get_class($hook),
                    $e
                );
            }

            if ($hook->hasMessages()) {
                $messages += $hook->getMessages();
            }
        }

        return $messages;
    }
}