Test Failed
Push — master ( bfe357...41d8e8 )
by Antonio Carlos
25:24
created

src/Support/Resource.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace PragmaRX\Health\Support;
4
5
use JsonSerializable;
6
use Ramsey\Uuid\Uuid;
7
use Illuminate\Support\Collection;
8
use PragmaRX\Health\Support\Traits\ToArray;
9
use PragmaRX\Health\Events\RaiseHealthIssue;
10
use PragmaRX\Health\Support\Traits\ImportProperties;
11
12
class Resource implements JsonSerializable
13
{
14
    use ToArray, ImportProperties;
15
16
    /**
17
     * @var string
18
     */
19
    public $id;
20
21
    /**
22
     * @var string
23
     */
24
    public $name;
25
26
    /**
27
     * @var string
28
     */
29
    public $slug;
30
31
    /**
32
     * @var string
33
     */
34
    public $abbreviation;
35
36
    /**
37
     * @var bool
38
     */
39
    public $isGlobal;
40
41
    /**
42
     * @var string
43
     */
44
    public $errorMessage;
45
46
    /**
47
     * @var array
48
     */
49
    public $style;
50
51
    /**
52
     * @var bool
53
     */
54
    public $notify;
55
56
    /**
57
     * @var Collection
58
     */
59
    public $targets;
60
61
    /**
62
     * @var ResourceChecker
63
     */
64
    public $checker;
65
66
    /**
67
     * @var Collection
68
     */
69
    public $resources;
70
71
    /**
72
     * @var bool
73
     */
74
    protected $notified;
75
76
    /**
77
     * @var string
78
     */
79
    protected $currentAction;
80
81
    /**
82
     * Resource factory.
83
     *
84
     * @param Collection $data
85
     * @return resource
86
     * @throws \Exception
87
     */
88
    public static function factory(Collection $data)
89
    {
90
        $instance = new static();
91
92
        $instance->id = (string) Uuid::uuid4();
93
94
        $instance->name = $data['name'];
95
96
        $instance->slug = str_slug($data['name']);
97
98
        $instance->abbreviation = $data['abbreviation'];
99
100
        $instance->targets = $instance->instantiateTargets(
101
            $data['targets'] ?? collect()
102
        );
103
104
        $instance->notify =
105
            $data['notify'] ?? config('health.notifications.enabled');
106
107
        $instance->style = $instance->keysToCamel(config('health.style'));
108
109
        $instance->style['columnSize'] =
110
            $data['column_size'] ?? $instance->style['columnSize'];
111
112
        $instance->errorMessage =
113
            $data['error_message'] ?? config('health.errors.message');
114
115
        $instance->isGlobal = $data['is_global'] ?? false;
116
117
        $instance->checker = $instance->instantiateChecker($data['checker']);
118
119
        $instance->importProperties($data);
120
121
        return $instance;
122
    }
123
124
    /**
125
     * Instantiate all checkers for a resource.
126
     *
127
     * @param Collection $targets
128
     * @return Collection|\IlluminateAgnostic\Arr\Support\Collection|\IlluminateAgnostic\Collection\Support\Collection|\IlluminateAgnostic\Str\Support\Collection|mixed|\Tightenco\Collect\Support\Collection|\Vanilla\Support\Collection
129
     */
130
    public function instantiateTargets(Collection $targets)
131
    {
132
        if ($targets->isEmpty()) {
133
            return collect([Target::factory($this, $targets)]);
134
        }
135
136
        $current = collect();
137
138
        $targets = $targets
139
            ->map(function (Collection $targetList) {
140
                return $targetList->map(function ($target, $name) {
141
                    return Target::factory($this, $target, $name);
142
                });
143
            })
144
            ->reduce(function ($current, $targetList) {
145
                foreach ($targetList as $target) {
146
                    $current[] = $target;
147
                }
148
149
                return $current;
150
            }, $current);
151
152
        return $targets;
153
    }
154
155
    /**
156
     * Instantiate one checker.
157
     *
158
     * @param string $checker
159
     * @return object
160
     */
161
    public function instantiateChecker(string $checker)
162
    {
163
        return instantiate($checker);
164
    }
165
166
    /**
167
     * Check all targets for a resource.
168
     *
169
     * @return resource
170
     */
171
    public function check()
172
    {
173
        $this->targets->each(function (Target $target) {
174
            $target->check($target);
0 ignored issues
show
The call to Target::check() has too many arguments starting with $target.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
175
        });
176
177
        $this->notify();
178
179
        return $this;
180
    }
181
182
    /**
183
     * Check global resources.
184
     *
185
     * @param $resources
186
     * @return resource
187
     */
188
    public function checkGlobal($resources)
189
    {
190
        return $this->setResources($resources)->check();
191
    }
192
193
    /**
194
     * Check if is healthy.
195
     *
196
     * @return mixed
197
     */
198
    public function isHealthy()
199
    {
200
        return $this->targets->reduce(function ($carry, $target) {
201
            return $carry && $target->result->healthy;
202
        }, true);
203
    }
204
205
    protected function keysToCamel($array)
206
    {
207
        return collect($array)->mapWithKeys(function ($item, $key) {
208
            return [camel_case($key) => $item];
209
        });
210
    }
211
212
    /**
213
     * Notify about health problems.
214
     */
215
    protected function notify()
216
    {
217
        if ($this->canNotify()) {
218
            $this->sendNotifications();
219
        }
220
    }
221
222
    /**
223
     * Send notifications.
224
     *
225
     * @return static
226
     */
227
    protected function sendNotifications()
228
    {
229
        return collect(config('health.notifications.channels'))->each(function (
230
            $channel
231
        ) {
232
            try {
233
                event(new RaiseHealthIssue($this, $channel));
234
            } catch (\Exception $exception) {
235
                // Notifications are broken, just report it
236
                report($exception);
237
            }
238
        });
239
    }
240
241
    /**
242
     * Can we notify about errors on this resource?
243
     *
244
     * @return bool
245
     */
246
    protected function canNotify()
247
    {
248
        return (
249
            !$this->notified &&
250
            $this->notificationsAreEnabled() &&
251
            !$this->isHealthy()
252
        );
253
    }
254
255
    /**
256
     * Is notification enabled for this resource?
257
     *
258
     * @return bool
259
     */
260
    protected function notificationsAreEnabled()
261
    {
262
        return (
263
            $this->notify &&
264
            config('health.notifications.enabled') &&
265
            config('health.notifications.notify_on.' . $this->currentAction)
266
        );
267
    }
268
269
    /**
270
     * Resources setter.
271
     *
272
     * @param $resources
273
     * @return resource
274
     */
275
    protected function setResources($resources)
276
    {
277
        $this->resources = $resources;
278
279
        return $this;
280
    }
281
282
    /**
283
     * Object to json.
284
     *
285
     * @return false|string
286
     */
287
    public function __toString()
288
    {
289
        return json_encode($this->__toArray($this, 6));
290
    }
291
292
    /**
293
     * Prepare the resource for JSON serialization.
294
     *
295
     * @return string
296
     */
297
    public function jsonSerialize()
298
    {
299
        return json_decode($this->__toString(), true);
300
    }
301
}
302