Cast::apply()   C
last analyzed

Complexity

Conditions 15
Paths 28

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 5.9166
c 0
b 0
f 0
cc 15
nc 28
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * File copied from Waavi/Sanitizer https://github.com/waavi/sanitizer
4
 * Sanitization functionality to be customized within this project before a 1.0 release.
5
 */
6
7
namespace PerfectOblivion\Valid\Sanitizer\Filters;
8
9
use InvalidArgumentException;
10
use Illuminate\Support\Collection;
11
use PerfectOblivion\Valid\Sanitizer\Contracts\Filter;
12
13
class Cast implements Filter
14
{
15
    /**
16
     * Cast the value to the given type.
17
     *
18
     * @param  mixed  $value
19
     *
20
     * @return mixed
21
     */
22
    public function apply($value, $options = [])
23
    {
24
        $type = isset($options[0]) ? $options[0] : null;
25
26
        switch ($type) {
27
            case 'int':
28
            case 'integer':
29
                return (int) $value;
30
            case 'real':
31
            case 'float':
32
            case 'double':
33
                return (float) $value;
34
            case 'string':
35
                return (string) $value;
36
            case 'bool':
37
            case 'boolean':
38
                return (bool) $value;
39
            case 'object':
40
                return is_array($value) ? (object) $value : json_decode($value, false);
41
            case 'array':
42
                return json_decode($value, true);
43
            case 'collection':
44
                $array = is_array($value) ? $value : json_decode($value, true);
45
46
                return new Collection($array);
47
            default:
48
                throw new InvalidArgumentException("Wrong Sanitizer casting format: {$type}.");
49
        }
50
    }
51
}
52