1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Limoncello\Validation\Rules\Converters; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Copyright 2015-2020 [email protected] |
7
|
|
|
* |
8
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
9
|
|
|
* you may not use this file except in compliance with the License. |
10
|
|
|
* You may obtain a copy of the License at |
11
|
|
|
* |
12
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0 |
13
|
|
|
* |
14
|
|
|
* Unless required by applicable law or agreed to in writing, software |
15
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS, |
16
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
17
|
|
|
* See the License for the specific language governing permissions and |
18
|
|
|
* limitations under the License. |
19
|
|
|
*/ |
20
|
|
|
|
21
|
|
|
use Limoncello\Validation\Contracts\Errors\ErrorCodes; |
22
|
|
|
use Limoncello\Validation\Contracts\Execution\ContextInterface; |
23
|
|
|
use Limoncello\Validation\I18n\Messages; |
24
|
|
|
use Limoncello\Validation\Rules\ExecuteRule; |
25
|
|
|
use function is_bool; |
26
|
|
|
use function is_string; |
27
|
|
|
use function strtolower; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @package Limoncello\Validation |
31
|
|
|
*/ |
32
|
|
|
final class StringToBool extends ExecuteRule |
33
|
|
|
{ |
34
|
|
|
/** |
35
|
|
|
* @param mixed $value |
36
|
|
|
* @param ContextInterface $context |
37
|
|
|
* |
38
|
|
|
* @return array |
39
|
|
|
* |
40
|
|
|
* @SuppressWarnings(PHPMD.StaticAccess) |
41
|
|
|
* @SuppressWarnings(PHPMD.ElseExpression) |
42
|
|
|
* @SuppressWarnings(PHPMD.CyclomaticComplexity) |
43
|
|
|
*/ |
44
|
2 |
|
public static function execute($value, ContextInterface $context): array |
45
|
|
|
{ |
46
|
2 |
|
if (is_string($value) === true) { |
47
|
2 |
|
$lcValue = strtolower($value); |
48
|
2 |
|
if ($lcValue === 'true' || $lcValue === '1' || $lcValue === 'on' || $lcValue === 'yes') { |
49
|
2 |
|
$reply = static::createSuccessReply(true); |
50
|
2 |
|
} elseif ($lcValue === 'false' || $lcValue === '0' || $lcValue === 'off' || $lcValue === 'no') { |
51
|
1 |
|
$reply = static::createSuccessReply(false); |
52
|
|
|
} else { |
53
|
2 |
|
$reply = static::createErrorReply($context, $value, ErrorCodes::IS_BOOL, Messages::IS_BOOL, []); |
54
|
|
|
} |
55
|
1 |
|
} elseif (is_bool($value) === true) { |
56
|
1 |
|
$reply = static::createSuccessReply($value); |
57
|
|
|
} else { |
58
|
1 |
|
$reply = static::createErrorReply($context, $value, ErrorCodes::IS_BOOL, Messages::IS_BOOL, []); |
59
|
|
|
} |
60
|
|
|
|
61
|
2 |
|
return $reply; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|