ObjectTransformer   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 6
c 0
b 0
f 0
lcom 0
cbo 1
dl 0
loc 36
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A canTransform() 0 4 1
A transform() 0 16 5
1
<?php
2
3
namespace Spatie\BladeJavaScript\Transformers;
4
5
use JsonSerializable;
6
use Spatie\BladeJavaScript\Exceptions\Untransformable;
7
use StdClass;
8
9
class ObjectTransformer implements Transformer
10
{
11
    /**
12
     * @param mixed $value
13
     *
14
     * @return bool
15
     */
16
    public function canTransform($value): bool
17
    {
18
        return is_object($value);
19
    }
20
21
    /**
22
     * @param mixed $value
23
     *
24
     * @return string
25
     *
26
     * @throws \Spatie\BladeJavaScript\Exceptions\Untransformable
27
     */
28
    public function transform($value): string
29
    {
30
        if (method_exists($value, 'toJson')) {
31
            return $value->toJson();
32
        }
33
34
        if ($value instanceof JsonSerializable || $value instanceof StdClass) {
0 ignored issues
show
Bug introduced by
The class JsonSerializable does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
35
            return json_encode($value);
36
        }
37
38
        if (! method_exists($value, '__toString')) {
39
            throw Untransformable::cannotTransformObject($value);
40
        }
41
42
        return "'{$value}'";
43
    }
44
}
45