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

ObjectTransformer::canTransform()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
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