1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Swis\Laravel\JavaScriptData; |
4
|
|
|
|
5
|
|
|
use Illuminate\Contracts\Support\Arrayable; |
6
|
|
|
use Illuminate\Contracts\Support\Jsonable; |
7
|
|
|
|
8
|
|
|
class Builder |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @param string $name The name for this data using dot notation |
12
|
|
|
* @param mixed $data The data |
13
|
|
|
* @param int $options Extra json_encode options |
14
|
|
|
* |
15
|
|
|
* @throws \InvalidArgumentException |
16
|
|
|
* |
17
|
|
|
* @return string |
18
|
|
|
*/ |
19
|
36 |
|
public function build(string $name, $data, int $options = 0): string |
20
|
|
|
{ |
21
|
|
|
// Check if we need to pretty print the results |
22
|
36 |
|
$prettyPrint = ($options & JSON_PRETTY_PRINT) === JSON_PRETTY_PRINT; |
23
|
|
|
|
24
|
|
|
// Encode to JSON |
25
|
36 |
|
if ($data instanceof Arrayable) { |
26
|
4 |
|
$json = json_encode($data->toArray(), $options); |
27
|
32 |
|
} elseif ($data instanceof Jsonable) { |
28
|
4 |
|
$json = $data->toJson($options); |
29
|
28 |
|
} elseif ($data instanceof \JsonSerializable) { |
30
|
4 |
|
$json = json_encode($data->jsonSerialize(), $options); |
31
|
|
|
} else { |
32
|
24 |
|
$json = json_encode($data, $options); |
33
|
|
|
} |
34
|
|
|
|
35
|
36 |
|
if (JSON_ERROR_NONE !== json_last_error()) { |
36
|
4 |
|
throw new \InvalidArgumentException(json_last_error_msg(), json_last_error()); |
37
|
|
|
} |
38
|
|
|
|
39
|
32 |
|
if ($prettyPrint) { |
40
|
4 |
|
$json = str_replace("\n", "\n ", $json); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
// Make the JavaScript |
44
|
32 |
|
$namespaceParts = explode('.', $name); |
45
|
32 |
|
$namespace = 'window'; |
46
|
32 |
|
$javascriptLines = []; |
47
|
|
|
|
48
|
32 |
|
foreach ($namespaceParts as $key => $namespacePart) { |
49
|
32 |
|
$namespace .= sprintf('["%s"]', $namespacePart); |
50
|
|
|
|
51
|
32 |
|
if ($key === \count($namespaceParts) - 1) { |
52
|
32 |
|
$javascriptLines[] = sprintf($prettyPrint ? '%s = %s;' : '%s=%s;', $namespace, $json); |
53
|
|
|
} else { |
54
|
8 |
|
$javascriptLines[] = sprintf($prettyPrint ? '%s = %s || {};' : '%s=%s||{};', $namespace, $namespace); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
32 |
|
if ($prettyPrint) { |
59
|
4 |
|
$javascript = sprintf("(function(){\n %s\n})();", implode("\n ", $javascriptLines)); |
60
|
|
|
} else { |
61
|
28 |
|
$javascript = sprintf('(function(){%s})();', implode('', $javascriptLines)); |
62
|
|
|
} |
63
|
|
|
|
64
|
32 |
|
return $javascript; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|