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_iterable; |
26
|
|
|
use function is_numeric; |
27
|
|
|
use function is_string; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @package Limoncello\Validation |
31
|
|
|
*/ |
32
|
|
|
final class StringArrayToIntArray 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
|
|
|
*/ |
43
|
1 |
|
public static function execute($value, ContextInterface $context): array |
44
|
|
|
{ |
45
|
1 |
|
$reply = null; |
46
|
|
|
|
47
|
1 |
|
$result = []; |
48
|
1 |
|
if (is_iterable($value) === true) { |
49
|
1 |
|
foreach ($value as $key => $mightBeString) { |
50
|
1 |
|
if (is_string($mightBeString) === true || is_numeric($mightBeString) === true) { |
51
|
1 |
|
$result[$key] = (int)$mightBeString; |
52
|
|
|
} else { |
53
|
1 |
|
$reply = static::createErrorReply( |
54
|
1 |
|
$context, |
55
|
1 |
|
$mightBeString, |
56
|
1 |
|
ErrorCodes::IS_STRING, |
57
|
1 |
|
Messages::IS_STRING, |
58
|
1 |
|
[] |
59
|
|
|
); |
60
|
1 |
|
break; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
} else { |
64
|
1 |
|
$reply = static::createErrorReply($context, $value, ErrorCodes::IS_ARRAY, Messages::IS_ARRAY, []); |
65
|
|
|
} |
66
|
|
|
|
67
|
1 |
|
return $reply !== null ? $reply : static::createSuccessReply($result); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|