Titlecase::check()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 6
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 13
ccs 0
cts 3
cp 0
crap 20
rs 10
1
<?php
2
3
/**
4
 * This file is part of Dimtrovich/Validation.
5
 *
6
 * (c) 2023 Dimitri Sitchet Tomkeu <[email protected]>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace Dimtrovich\Validation\Rules;
13
14
class Titlecase extends AbstractRule
15
{
16
    /**
17
     * Check if the given value must formated in Title case.
18
     *
19
     * @see https://en.wikipedia.org/wiki/Title_case
20
     * @credit <a href="https://github.com/Intervention/validation">Intervention/validation - \Intervention\Validation\Rules\Titlecase</a>
21
     *
22
     * @param mixed $value
23
     */
24
    public function check($value): bool
25
    {
26
        if (! is_string($value)) {
27
            return false;
28
        }
29
30
        foreach ($this->getWords($value) as $word) {
31
            if (! $this->isValidWord($word)) {
32
                return false;
33
            }
34
        }
35
36
        return true;
37
    }
38
39
    /**
40
     * Get array of words from current value
41
     */
42
    private function getWords(string $value): array
43
    {
44
        return explode(' ', $value);
45
    }
46
47
    /**
48
     * Determine if given word starts with upper case letter or number
49
     */
50
    private function isValidWord(string $word): bool
51
    {
52
        return (bool) preg_match('/^[\\p{Lu}0-9]/u', $word);
53
    }
54
}
55