Completed
Push — master ( f51b12...f4336a )
by Eric
9s
created

Notifier::httpPingDown()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 14
rs 9.4285
cc 3
eloc 9
nc 2
nop 1
1
<?php
2
3
namespace EricMakesStuff\ServerMonitor\Notifications;
4
5
use EricMakesStuff\ServerMonitor\Monitors\HttpPingMonitor;
6
use Illuminate\Contracts\Logging\Log as LogContract;
7
use EricMakesStuff\ServerMonitor\Monitors\DiskUsageMonitor;
8
use Exception;
9
10
class Notifier
11
{
12
    /** @var array */
13
    protected $config;
14
15
    /** @var \Illuminate\Contracts\Logging\Log */
16
    protected $log;
17
18
    protected $serverName;
19
20
    /**
21
     * @param \Illuminate\Contracts\Logging\Log $log
22
     */
23
    public function __construct(LogContract $log)
24
    {
25
        $this->log = $log;
26
27
        $this->serverName = config('server-monitor.server.name');
28
29
        $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...
30
    }
31
32 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...
33
    {
34
        $this->sendNotification(
35
            'whenDiskUsageHealthy',
36
            "Disk Usage on {$this->serverName} is Healthy at {$diskUsageMonitor->getPercentageUsed()} Used",
37
            "Disk Usage is healthy on {$this->serverName}. Filesystem {$diskUsageMonitor->getPath()} is okay: {$diskUsageMonitor->getPercentageUsed()}",
38
            BaseSender::TYPE_SUCCESS
39
        );
40
    }
41
42
    /**
43
     * @param \EricMakesStuff\ServerMonitor\Monitors\DiskUsageMonitor $diskUsageMonitor
44
     */
45 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...
46
    {
47
        $this->sendNotification(
48
            'whenDiskUsageAlarm',
49
            "Disk Usage on {$this->serverName} High! {$diskUsageMonitor->getPercentageUsed()} Used",
50
            "Disk Usage Alarm on {$this->serverName}! Filesystem {$diskUsageMonitor->getPath()} is above the alarm threshold ({$diskUsageMonitor->getAlarmPercentage()}) at {$diskUsageMonitor->getPercentageUsed()}",
51
            BaseSender::TYPE_ERROR
52
        );
53
    }
54
55
    /**
56
     * @param HttpPingMonitor $httpPingMonitor
57
     */
58
    public function httpPingUp(HttpPingMonitor $httpPingMonitor)
59
    {
60
        $this->sendNotification(
61
            'whenHttpPingUp',
62
            "HTTP Ping Success: {$httpPingMonitor->getUrl()}",
63
            "HTTP Ping Succeeded for {$httpPingMonitor->getUrl()}. Response Code {$httpPingMonitor->getResponseCode()}.",
64
            BaseSender::TYPE_SUCCESS
65
        );
66
    }
67
68
    /**
69
     * @param HttpPingMonitor $httpPingMonitor
70
     */
71
    public function httpPingDown(HttpPingMonitor $httpPingMonitor)
72
    {
73
        $additionalInfo = '';
74
        if ($httpPingMonitor->getCheckPhrase() && ! $httpPingMonitor->getResponseContainsPhrase()) {
75
            $additionalInfo = " Response did not contain \"{$httpPingMonitor->getCheckPhrase()}\"";
76
        }
77
78
        $this->sendNotification(
79
            'whenHttpPingDown',
80
            "HTTP Ping Failed: {$httpPingMonitor->getUrl()}!",
81
            "HTTP Ping Failed for {$httpPingMonitor->getUrl()}! Response Code {$httpPingMonitor->getResponseCode()}.{$additionalInfo}",
82
            BaseSender::TYPE_ERROR
83
        );
84
    }
85
86
    /**
87
     * @param string $eventName
88
     * @param string $subject
89
     * @param string $message
90
     * @param string $type
91
     */
92
    protected function sendNotification($eventName, $subject, $message, $type)
93
    {
94
        $senderNames = config("server-monitor.notifications.events.{$eventName}");
95
96
        collect($senderNames)
97
            ->map(function ($senderName) {
98
                $className = $senderName;
99
100
                if (file_exists(__DIR__.'/Senders/'.ucfirst($senderName).'.php')) {
101
                    $className = '\\EricMakesStuff\\ServerMonitor\\Notifications\\Senders\\'.ucfirst($senderName);
102
                }
103
104
                return app($className);
105
            })
106
            ->each(function (SendsNotifications $sender) use ($subject, $message, $type) {
107
                try {
108
                    $sender
109
                        ->setSubject($subject)
110
                        ->setMessage($message)
111
                        ->setType($type)
112
                        ->send();
113
                } catch (Exception $exception) {
114
                    $errorMessage = "Server Monitor notifier failed because {$exception->getMessage()}"
115
                        .PHP_EOL
116
                        .$exception->getTraceAsString();
117
118
                    $this->log->error($errorMessage);
119
                    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...
120
                }
121
            });
122
    }
123
}
124