Completed
Push — master ( f4336a...a269ea )
by Eric
7s
created

Notifier::sslCertificateValid()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 9
rs 9.6666
cc 1
eloc 6
nc 1
nop 1
1
<?php
2
3
namespace EricMakesStuff\ServerMonitor\Notifications;
4
5
use EricMakesStuff\ServerMonitor\Monitors\HttpPingMonitor;
6
use EricMakesStuff\ServerMonitor\Monitors\SSLCertificateMonitor;
7
use Illuminate\Contracts\Logging\Log as LogContract;
8
use EricMakesStuff\ServerMonitor\Monitors\DiskUsageMonitor;
9
use Exception;
10
11
class Notifier
12
{
13
    /** @var array */
14
    protected $config;
15
16
    /** @var \Illuminate\Contracts\Logging\Log */
17
    protected $log;
18
19
    protected $serverName;
20
21
    /**
22
     * @param \Illuminate\Contracts\Logging\Log $log
23
     */
24
    public function __construct(LogContract $log)
25
    {
26
        $this->log = $log;
27
28
        $this->serverName = config('server-monitor.server.name');
29
30
        $this->subject = "{$this->serverName} Server Monitoring";
0 ignored issues
show
Bug introduced by
The property subject does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
31
    }
32
33 View Code Duplication
    public function diskUsageHealthy(DiskUsageMonitor $diskUsageMonitor)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
34
    {
35
        $this->sendNotification(
36
            'whenDiskUsageHealthy',
37
            "Disk Usage on {$this->serverName} is Healthy at {$diskUsageMonitor->getPercentageUsed()} Used",
38
            "Disk Usage is healthy on {$this->serverName}. Filesystem {$diskUsageMonitor->getPath()} is okay: {$diskUsageMonitor->getPercentageUsed()}",
39
            BaseSender::TYPE_SUCCESS
40
        );
41
    }
42
43
    /**
44
     * @param \EricMakesStuff\ServerMonitor\Monitors\DiskUsageMonitor $diskUsageMonitor
45
     */
46 View Code Duplication
    public function diskUsageAlarm(DiskUsageMonitor $diskUsageMonitor)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
47
    {
48
        $this->sendNotification(
49
            'whenDiskUsageAlarm',
50
            "Disk Usage on {$this->serverName} High! {$diskUsageMonitor->getPercentageUsed()} Used",
51
            "Disk Usage Alarm on {$this->serverName}! Filesystem {$diskUsageMonitor->getPath()} is above the alarm threshold ({$diskUsageMonitor->getAlarmPercentage()}) at {$diskUsageMonitor->getPercentageUsed()}",
52
            BaseSender::TYPE_ERROR
53
        );
54
    }
55
56
    /**
57
     * @param HttpPingMonitor $httpPingMonitor
58
     */
59
    public function httpPingUp(HttpPingMonitor $httpPingMonitor)
60
    {
61
        $this->sendNotification(
62
            'whenHttpPingUp',
63
            "HTTP Ping Success: {$httpPingMonitor->getUrl()}",
64
            "HTTP Ping Succeeded for {$httpPingMonitor->getUrl()}. Response Code {$httpPingMonitor->getResponseCode()}.",
65
            BaseSender::TYPE_SUCCESS
66
        );
67
    }
68
69
    /**
70
     * @param HttpPingMonitor $httpPingMonitor
71
     */
72
    public function httpPingDown(HttpPingMonitor $httpPingMonitor)
73
    {
74
        $additionalInfo = '';
75
        if ($httpPingMonitor->getCheckPhrase() && ! $httpPingMonitor->getResponseContainsPhrase()) {
76
            $additionalInfo = " Response did not contain \"{$httpPingMonitor->getCheckPhrase()}\"";
77
        }
78
79
        $this->sendNotification(
80
            'whenHttpPingDown',
81
            "HTTP Ping Failed: {$httpPingMonitor->getUrl()}!",
82
            "HTTP Ping Failed for {$httpPingMonitor->getUrl()}! Response Code {$httpPingMonitor->getResponseCode()}.{$additionalInfo}",
83
            BaseSender::TYPE_ERROR
84
        );
85
    }
86
87
    /**
88
     * @param SSLCertificateMonitor $sslCertificateMonitor
89
     */
90
    public function sslCertificateValid(SSLCertificateMonitor $sslCertificateMonitor)
91
    {
92
        $this->sendNotification(
93
            'whenSSLCertificateValid',
94
            "SSL Certificate Valid: {$sslCertificateMonitor->getUrl()}",
95
            "SSL Certificate is valid for {$sslCertificateMonitor->getUrl()}. Expires in {$sslCertificateMonitor->getCertificateDaysUntilExpiration()} days.",
96
            BaseSender::TYPE_SUCCESS
97
        );
98
    }
99
100
    /**
101
     * @param SSLCertificateMonitor $sslCertificateMonitor
102
     */
103 View Code Duplication
    public function sslCertificateInvalid(SSLCertificateMonitor $sslCertificateMonitor)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
104
    {
105
        $this->sendNotification(
106
            'whenSSLCertificateInvalid',
107
            "SSL Certificate Invalid: {$sslCertificateMonitor->getUrl()}",
108
            "SSL Certificate is invalid for {$sslCertificateMonitor->getUrl()}. Certificate domain is {$sslCertificateMonitor->getCertificateDomain()}. Certificate expiration date is {$sslCertificateMonitor->getCertificateExpiration()} ({$sslCertificateMonitor->getCertificateDaysUntilExpiration()} days).",
109
            BaseSender::TYPE_ERROR
110
        );
111
    }
112
113
    /**
114
     * @param SSLCertificateMonitor $sslCertificateMonitor
115
     */
116 View Code Duplication
    public function sslCertificateExpiring(SSLCertificateMonitor $sslCertificateMonitor)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
117
    {
118
        $this->sendNotification(
119
            'whenSSLCertificateInvalid',
120
            "SSL Certificate Expiring: {$sslCertificateMonitor->getUrl()}",
121
            "SSL Certificate for {$sslCertificateMonitor->getUrl()} is expiring on {$sslCertificateMonitor->getCertificateExpiration()} ({$sslCertificateMonitor->getCertificateDaysUntilExpiration()} days).",
122
            BaseSender::TYPE_ERROR
123
        );
124
    }
125
126
    /**
127
     * @param string $eventName
128
     * @param string $subject
129
     * @param string $message
130
     * @param string $type
131
     */
132
    protected function sendNotification($eventName, $subject, $message, $type)
133
    {
134
        $senderNames = config("server-monitor.notifications.events.{$eventName}");
135
136
        collect($senderNames)
137
            ->map(function ($senderName) {
138
                $className = $senderName;
139
140
                if (file_exists(__DIR__.'/Senders/'.ucfirst($senderName).'.php')) {
141
                    $className = '\\EricMakesStuff\\ServerMonitor\\Notifications\\Senders\\'.ucfirst($senderName);
142
                }
143
144
                return app($className);
145
            })
146
            ->each(function (SendsNotifications $sender) use ($subject, $message, $type) {
147
                try {
148
                    $sender
149
                        ->setSubject($subject)
150
                        ->setMessage($message)
151
                        ->setType($type)
152
                        ->send();
153
                } catch (Exception $exception) {
154
                    $errorMessage = "Server Monitor notifier failed because {$exception->getMessage()}"
155
                        .PHP_EOL
156
                        .$exception->getTraceAsString();
157
158
                    $this->log->error($errorMessage);
159
                    consoleOutput()->error($errorMessage);
0 ignored issues
show
Documentation Bug introduced by
The method error does not exist on object<EricMakesStuff\Se...\Helpers\ConsoleOutput>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
160
                }
161
            });
162
    }
163
}
164