Skip to content

Commit 1b00097

Browse files
author
Ilya Sakovich
committed
wip
1 parent 212bb66 commit 1b00097

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

src/SharedData.php

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,25 @@
22

33
namespace Coderello\SharedData;
44

5+
use Illuminate\Contracts\Support\Arrayable;
56
use Illuminate\Support\Arr;
67
use InvalidArgumentException;
78
use Illuminate\Contracts\Support\Jsonable;
89
use Illuminate\Contracts\Support\Renderable;
10+
use JsonSerializable;
911

1012
class SharedData implements Renderable, Jsonable
1113
{
12-
protected $data = [];
14+
private $data = [];
1315

1416
private $jsNamespace = 'sharedData';
1517

1618
public function __construct(array $config = [])
19+
{
20+
$this->hydrateConfig($config);
21+
}
22+
23+
private function hydrateConfig(array $config)
1724
{
1825
if (isset($config['js_namespace'])) {
1926
$this->setJsNamespace($config['js_namespace']);
@@ -28,10 +35,14 @@ public function put($key, $value = null)
2835
foreach ($key as $nestedKey => $nestedValue) {
2936
$this->put($nestedKey, $nestedValue);
3037
}
38+
} elseif ($key instanceof JsonSerializable) {
39+
$this->put($key->jsonSerialize());
40+
} elseif ($key instanceof Arrayable) {
41+
$this->put($key->toArray());
3142
} elseif (is_object($key)) {
3243
$this->put(get_object_vars($key));
3344
} else {
34-
throw new InvalidArgumentException('Unsupported data key type: '.gettype($key));
45+
throw new InvalidArgumentException('Key type ['.gettype($key).'] is not supported.');
3546
}
3647

3748
return $this;

tests/SharedDataTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
namespace Coderello\SharedData\Tests;
44

55
use Coderello\SharedData\SharedData;
6+
use Illuminate\Contracts\Support\Arrayable;
7+
use JsonSerializable;
68

79
class SharedDataTest extends AbstractTestCase
810
{
@@ -39,6 +41,28 @@ public function testSetupData()
3941
$this->sharedData->put($object);
4042
$this->assertSame('object-scalar', $this->sharedData->get('objectScalar'));
4143
$this->assertSame(['nested' => 'object-scalar'], $this->sharedData->get('objectArray'));
44+
45+
$arrayable = new class implements Arrayable {
46+
public function toArray()
47+
{
48+
return [
49+
'arrayable-key' => 'arrayable-value',
50+
];
51+
}
52+
};
53+
$this->sharedData->put($arrayable);
54+
$this->assertSame('arrayable-value', $this->sharedData->get('arrayable-key'));
55+
56+
$jsonSerializable = new class implements JsonSerializable {
57+
public function jsonSerialize()
58+
{
59+
return [
60+
'json-serializable-key' => 'json-serializable-value',
61+
];
62+
}
63+
};
64+
$this->sharedData->put($jsonSerializable);
65+
$this->assertSame('json-serializable-value', $this->sharedData->get('json-serializable-key'));
4266
}
4367

4468
/**

0 commit comments

Comments
 (0)