Completed
Push — master ( 21db3c...6ad8e7 )
by Maxime
03:06
created

Caster::fromJson()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 14
ccs 7
cts 7
cp 1
crap 3
rs 9.7998
c 0
b 0
f 0
1
<?php
2
3
namespace Distilleries\Contentful\Helpers;
4
5
use Distilleries\Contentful\Models\Location;
6
use Parsedown;
7
use Illuminate\Support\Carbon;
8
9
class Caster
10
{
11
    /**
12
     * Cast value to a string.
13
     *
14
     * @param  mixed  $str
15
     * @return string
16
     */
17 2
    public static function string($str): string
18
    {
19 2
        return (string) $str;
20
    }
21
22
    /**
23
     * Cast value to a string.
24
     *
25
     * @param  mixed  $str
26
     * @param  mixed  $default
27
     * @return \Illuminate\Support\Carbon|null
28
     */
29
    public static function datetime($str, $default = null): ?Carbon
30
    {
31
        if (empty($str)) {
32
            return $default;
33
        }
34
35
        try {
36
            $carbon = new Carbon($str);
37
        } catch (\Exception $e) {
38
            $carbon = null;
39
        }
40
41
        return $carbon;
42
    }
43
44
    /**
45
     * Transform data to its JSON representation.
46
     *
47
     * @param  mixed  $data
48
     * @param  mixed  $default
49
     * @return string
50
     */
51 2
    public static function toJson($data, $default = null): string
52
    {
53 2
        return ! empty($data) ? json_encode($data): $default;
54
    }
55
56
    /**
57
     * Transform a JSON string to its associative array representation.
58
     *
59
     * @param  mixed  $json
60
     * @return array|null
61
     */
62 6
    public static function fromJson($json): ?array
63
    {
64 6
        if (empty($json)) {
65 2
            return null;
66
        }
67
68 4
        $data = json_decode($json, true);
69
70 4
        if (json_last_error() !== JSON_ERROR_NONE) {
71 2
            return null;
72
        }
73
74 2
        return $data;
75
    }
76
77
    /**
78
     * Transform markdown content to an HTML string.
79
     *
80
     * @param  mixed  $md
81
     * @param  mixed  $default
82
     * @return string
83
     */
84 4
    public static function markdown($md, $default = null): ?string
85
    {
86 4
        if (empty($md)) {
87 2
            return $default;
88
        }
89
90 2
        return (new Parsedown)->setBreaksEnabled(true)->text($md);
91
    }
92
93
    /**
94
     * Cast an integer to an integer value otherwise to null.
95
     *
96
     * @param  mixed  $int
97
     * @param  mixed  $default
98
     * @return integer|null
99
     */
100 2
    public static function integer($int, $default = null): ?int
101
    {
102 2
        return is_numeric($int) ? (int) $int : $default;
103
    }
104
105
    /**
106
     * Cast an boolean to an boolean value otherwise to null.
107
     *
108
     * @param  mixed  $bool
109
     * @param  mixed  $default
110
     * @return boolean|null
111
     */
112
    public static function boolean($bool, $default = null): ?bool
113
    {
114
        return is_bool($bool) ? (bool) $bool : $default;
115
    }
116
117
    /**
118
     * Cast an float to an float value otherwise to null.
119
     *
120
     * @param  mixed  $float
121
     * @param  mixed  $default
122
     * @return float|null
123
     */
124
    public static function float($float, $default = null): ?float
125
    {
126
        return is_float($float) ? (float) $float : $default;
127
    }
128
129
    /**
130
     * Return entry ID in given "Link" array.
131
     *
132
     * @param  array  $entry
133
     * @param  mixed  $default
134
     * @return string|null
135
     */
136 2
    public static function entryId(array $entry, $default = null): ?string
137
    {
138 2
        return (isset($entry['sys']) and isset($entry['sys']['id'])) ? $entry['sys']['id'] : $default;
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
139
    }
140
141
    /**
142
     * Return a Location object
143
     *
144
     * @param  array  $entry
145
     * @param  Location  $default
146
     * @return Location|null
147
     */
148
    public static function location(array $entry, ?Location $default = null): ?Location
149
    {
150
        return isset($entry['default'])? new Location($entry['default']):$default;
0 ignored issues
show
Unused Code introduced by
The call to Location::__construct() has too many arguments starting with $entry['default'].

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
151
    }
152
}
153