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