Skip to content

Commit 267a072

Browse files
[12.x] Adds fromJson() to Collection (#55310)
1 parent 9800c50 commit 267a072

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/Illuminate/Collections/Traits/EnumeratesValues.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,19 @@ public static function times($number, ?callable $callback = null)
179179
->map($callback);
180180
}
181181

182+
/**
183+
* Create a new collection by decoding a JSON string.
184+
*
185+
* @param string $json
186+
* @param int $depth
187+
* @param int $flags
188+
* @return static<TKey, TValue>
189+
*/
190+
public static function fromJson($json, $depth = 512, $flags = 0)
191+
{
192+
return new static(json_decode($json, true, $depth, $flags));
193+
}
194+
182195
/**
183196
* Get the average value of a given key.
184197
*

tests/Support/SupportCollectionTest.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2814,6 +2814,35 @@ public function testRangeMethod($collection)
28142814
);
28152815
}
28162816

2817+
#[DataProvider('collectionClassProvider')]
2818+
public function testFromJson($collection)
2819+
{
2820+
$json = json_encode($array = ['foo' => 'bar', 'baz' => 'quz']);
2821+
2822+
$instance = $collection::fromJson($json);
2823+
2824+
$this->assertSame($array, $instance->toArray());
2825+
}
2826+
2827+
#[DataProvider('collectionClassProvider')]
2828+
public function testFromJsonWithDepth($collection)
2829+
{
2830+
$json = json_encode(['foo' => ['baz' => ['quz']], 'bar' => 'baz']);
2831+
2832+
$instance = $collection::fromJson($json, 1);
2833+
2834+
$this->assertEmpty($instance->toArray());
2835+
$this->assertSame(JSON_ERROR_DEPTH, json_last_error());
2836+
}
2837+
2838+
#[DataProvider('collectionClassProvider')]
2839+
public function testFromJsonWithFlags($collection)
2840+
{
2841+
$instance = $collection::fromJson('{"int":99999999999999999999999}', 512, JSON_BIGINT_AS_STRING);
2842+
2843+
$this->assertSame(['int' => '99999999999999999999999'], $instance->toArray());
2844+
}
2845+
28172846
#[DataProvider('collectionClassProvider')]
28182847
public function testConstructMakeFromObject($collection)
28192848
{

0 commit comments

Comments
 (0)