BaseCheck::camelToSnake()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 2
1
<?php
2
namespace Health\Checks;
3
4
use Health\Builder\HealthCheckResponseBuilder;
5
6
/**
7
 * Base Abstract Check
8
 */
9
abstract class BaseCheck
10
{
11
12
    /**
13
     *
14
     * @var string
15
     */
16
    protected $name = null;
17
18
    /**
19
     *
20
     * @var array
21
     */
22
    protected $params = [];
23
24
    /**
25
     *
26
     * @param array $params
27
     */
28
    public function __construct(array $params = [])
29
    {
30
        $this->params = $params;
31
    }
32
33
    /**
34
     *
35
     * @return \Health\Builder\HealthCheckResponseBuilder
36
     */
37
    protected function getBuilder()
38
    {
39
        $name = $this->name ?? $this->slug();
40
41
        $builder = new HealthCheckResponseBuilder();
42
        $builder->name($name)->up();
43
44
        return $builder;
45
    }
46
47
    /**
48
     * Get Check Param
49
     *
50
     * @param string $name
51
     * @param mixed|null $default
52
     * @return mixed
53
     */
54
    protected function getParam(string $name, $default = null)
55
    {
56
        return $this->params[$name] ?? $default;
57
    }
58
59
    /**
60
     * Create a slug from check's class name
61
     *
62
     * @return string
63
     */
64
    private function slug()
65
    {
66
        $name = get_called_class();
67
        $name = str_replace('\\', '-', $name);
68
        $name = $this->camelToSnake($name);
69
70
        return $name;
71
    }
72
73
    /**
74
     * Camel case to snake case
75
     *
76
     * @see https://stackoverflow.com/questions/40514051/using-preg-replace-to-convert-camelcase-to-snake-case
77
     *
78
     * @param string $string
79
     * @param string $us
80
     * @return string
81
     */
82
    private function camelToSnake($string, $us = "-")
83
    {
84
        return strtolower(preg_replace('/(?<=\d)(?=[A-Za-z])|(?<=[A-Za-z])(?=\d)|(?<=[a-z])(?=[A-Z])/', $us, $string));
85
    }
86
}
87