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