Test Failed
Push — master ( 6cb9f0...7deac3 )
by Antonio Carlos
07:23 queued 02:51
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
     * @var bool|null
83
     */
84
    protected $graphEnabled = null;
85
86
    /**
87
     * Resource factory.
88
     *
89
     * @param Collection $data
90
     * @return resource
91
     * @throws \Exception
92
     */
93
    public static function factory(Collection $data)
94
    {
95
        $instance = new static();
96
97
        $instance->id = (string) Uuid::uuid4();
98
99
        $instance->name = $data['name'];
100
101
        $instance->slug = str_slug($data['name']);
102
103
        $instance->graphEnabled = isset($data['graph_enabled'])
104
            ? $data['graph_enabled']
105
            : null;
106
107
        $instance->abbreviation = $data['abbreviation'];
108
109
        $instance->targets = $instance->instantiateTargets(
110
            $data['targets'] ?? collect()
111
        );
112
113
        $instance->notify =
114
            $data['notify'] ?? config('health.notifications.enabled');
115
116
        $instance->style = $instance->keysToCamel(config('health.style'));
0 ignored issues
show
Documentation Bug introduced by
It seems like $instance->keysToCamel(config('health.style')) of type object<Illuminate\Support\Collection> is incompatible with the declared type array of property $style.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
117
118
        $instance->style['columnSize'] =
119
            $data['column_size'] ?? $instance->style['columnSize'];
120
121
        $instance->errorMessage =
122
            $data['error_message'] ?? config('health.errors.message');
123
124
        $instance->isGlobal = $data['is_global'] ?? false;
125
126
        $instance->checker = $instance->instantiateChecker($data['checker']);
127
128
        $instance->importProperties($data);
129
130
        return $instance;
131
    }
132
133
    /**
134
     * Instantiate all checkers for a resource.
135
     *
136
     * @param Collection $targets
137
     * @return Collection|\IlluminateAgnostic\Arr\Support\Collection|\IlluminateAgnostic\Collection\Support\Collection|\IlluminateAgnostic\Str\Support\Collection|mixed|\Tightenco\Collect\Support\Collection|\Vanilla\Support\Collection
138
     */
139
    public function instantiateTargets(Collection $targets)
140
    {
141
        if ($targets->isEmpty()) {
142
            return collect([Target::factory($this, $targets)]);
143
        }
144
145
        $current = collect();
146
147
        $targets = $targets
148
            ->map(function (Collection $targetList) {
149
                return $targetList->map(function ($target, $name) {
150
                    return Target::factory($this, $target, $name);
151
                });
152
            })
153
            ->reduce(function ($current, $targetList) {
154
                foreach ($targetList as $target) {
155
                    $current[] = $target;
156
                }
157
158
                return $current;
159
            }, $current);
160
161
        return $targets;
162
    }
163
164
    /**
165
     * Instantiate one checker.
166
     *
167
     * @param string $checker
168
     * @return object
169
     */
170
    public function instantiateChecker(string $checker)
171
    {
172
        return instantiate($checker);
173
    }
174
175
    /**
176
     * Check all targets for a resource.
177
     *
178
     * @return resource
179
     */
180
    public function check()
181
    {
182
        $this->targets->each(function (Target $target) {
183
            $target->check($target);
184
        });
185
186
        $this->notify();
187
188
        return $this;
189
    }
190
191
    /**
192
     * Check global resources.
193
     *
194
     * @param $resources
195
     * @return resource
196
     */
197
    public function checkGlobal($resources)
198
    {
199
        return $this->setResources($resources)->check();
200
    }
201
202
    /**
203
     * Check if is healthy.
204
     *
205
     * @return mixed
206
     */
207
    public function isHealthy()
208
    {
209
        return $this->targets->reduce(function ($carry, $target) {
210
            return $carry && $target->result->healthy;
211
        }, true);
212
    }
213
214
    protected function keysToCamel($array)
215
    {
216
        return collect($array)->mapWithKeys(function ($item, $key) {
217
            return [camel_case($key) => $item];
218
        });
219
    }
220
221
    /**
222
     * Notify about health problems.
223
     */
224
    protected function notify()
225
    {
226
        if ($this->canNotify()) {
227
            $this->sendNotifications();
228
        }
229
    }
230
231
    /**
232
     * Send notifications.
233
     *
234
     * @return static
235
     */
236
    protected function sendNotifications()
237
    {
238
        return collect(config('health.notifications.channels'))->each(function (
239
            $channel
240
        ) {
241
            try {
242
                event(new RaiseHealthIssue($this, $channel));
243
            } catch (\Exception $exception) {
244
                // Notifications are broken, just report it
245
                report($exception);
246
            }
247
        });
248
    }
249
250
    /**
251
     * Can we notify about errors on this resource?
252
     *
253
     * @return bool
254
     */
255
    protected function canNotify()
256
    {
257
        return (
258
            !$this->notified &&
259
            $this->notificationsAreEnabled() &&
260
            !$this->isHealthy()
261
        );
262
    }
263
264
    /**
265
     * Is notification enabled for this resource?
266
     *
267
     * @return bool
268
     */
269
    protected function notificationsAreEnabled()
270
    {
271
        return (
272
            $this->notify &&
273
            config('health.notifications.enabled') &&
274
            config('health.notifications.notify_on.' . $this->currentAction)
275
        );
276
    }
277
278
    /**
279
     * Resources setter.
280
     *
281
     * @param $resources
282
     * @return resource
283
     */
284
    protected function setResources($resources)
285
    {
286
        $this->resources = $resources;
287
288
        return $this;
289
    }
290
291
    /**
292
     * Object to json.
293
     *
294
     * @return false|string
295
     */
296
    public function __toString()
297
    {
298
        return json_encode($this->__toArray($this, 6));
299
    }
300
301
    /**
302
     * Prepare the resource for JSON serialization.
303
     *
304
     * @return string
305
     */
306
    public function jsonSerialize()
307
    {
308
        return json_decode($this->__toString(), true);
309
    }
310
}
311