Completed
Push — master ( 8c67c8...0fdee2 )
by Freek
01:59
created

ObjectTransformer   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A canTransform() 0 4 1
B transform() 0 16 5
1
<?php
2
3
namespace Spatie\BladeJavaScript\Transformers;
4
5
use Exception;
6
use JsonSerializable;
7
use StdClass;
8
9
class ObjectTransformer  implements Transformer
0 ignored issues
show
Coding Style introduced by
Expected 1 space after class name; 2 found
Loading history...
Coding Style introduced by
Expected 1 space before implements keyword; 2 found
Loading history...
10
{
11
    public function canTransform($value): bool
12
    {
13
        return is_object($value);
14
    }
15
16
    /**
17
     * @param $value
18
     *
19
     * @return string
20
     *
21
     * @throws \Exception
22
     */
23
    public function transform($value)
24
    {
25
        if (method_exists($value, 'toJson')) {
26
            return $value->toJson();
27
        }
28
29
        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...
30
            return json_encode($value);
31
        }
32
33
        if (!method_exists($value, '__toString')) {
34
            throw new Exception('Cannot transform this object to JavaScript.');
35
        }
36
37
        return "'{$value}'";
38
    }
39
}
40