|
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 StringArrayToIntArray 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
|
|
|
*/ |
|
48
|
|
|
public static function execute($value, ContextInterface $context): array |
|
49
|
|
|
{ |
|
50
|
|
|
$reply = null; |
|
51
|
|
|
|
|
52
|
|
|
$result = []; |
|
53
|
|
|
if (is_array($value) === true) { |
|
54
|
|
|
foreach ($value as $key => $mightBeString) { |
|
55
|
|
|
if (is_string($mightBeString) === true || is_numeric($mightBeString) === true) { |
|
56
|
|
|
$result[$key] = (int)$mightBeString; |
|
57
|
|
|
} else { |
|
58
|
|
|
$reply = BlockReplies::createErrorReply($context, $mightBeString, ErrorCodes::IS_STRING); |
|
59
|
|
|
break; |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
} else { |
|
63
|
|
|
$reply = BlockReplies::createErrorReply($context, $value, ErrorCodes::IS_ARRAY); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
return $reply !== null ? $reply : BlockReplies::createSuccessReply($result); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|