php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #72238 Make Generator class serialisable in JSON
Submitted: 2016-05-18 19:59 UTC Modified: 2016-09-16 19:20 UTC
Votes:3
Avg. Score:5.0 ± 0.0
Reproduced:3 of 3 (100.0%)
Same Version:2 (66.7%)
Same OS:2 (66.7%)
From: gregory at luni dot fr Assigned:
Status: Open Package: JSON related
PHP Version: 7.0.6 OS: All
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: gregory at luni dot fr
New email:
PHP Version: OS:

 

 [2016-05-18 19:59 UTC] gregory at luni dot fr
Description:
------------
json_encode() function does not accept Generator objects.

This is I think a interesting optimization in the source code in userland, as it wouldn't be necessary anymore to transform what is yielded by the generator into a temporary array.

From the userland point of view, it could be done via JsonSerializable interface implementation.

Test script:
---------------
<?php

// Example 1 : minimal POC

$callback = function(){
    yield ['a', 'b', 'c', 'd'];
    yield ['e', 'f', 'g', 'h'];
    yield ['i', 'j', 'k', 'l'];
    yield ['m', 'n', 'o', 'p'];
};

echo json_encode($callback(), JSON_PRETTY_PRINT) . PHP_EOL;

// Example 2 : real-life example

class Item
{
    public $label;
    
    public function __consctruct($label)
    {
        $this->label = $label;
    }
}

class Collection
{
    private $items = [];
    
    public function add(Item $item)
    {
        $this->items[] = $item;
    }

    public function walkItemLabels()
    {
        foreach ($this->items as $item) {
            yield $item->label;
        }
    }
}

$collection = new Collection();
$collection->add(new Item('Lorem'));
$collection->add(new Item('Ipsum'));
$collection->add(new Item('Dolor'));
$collection->add(new Item('Sit'));
$collection->add(new Item('Amet'));

echo json_encode($collection->walkItemLabels(), JSON_PRETTY_PRINT) . PHP_EOL;

Expected result:
----------------
// Example 1

[['a', 'b', 'c', 'd'],['e', 'f', 'g', 'h'],['i', 'j', 'k', 'l'],['m', 'n', 'o', 'p']]

// Example 2

['Lorem','Ipsum','Dolor,'Sit','Amet']

Actual result:
--------------
// Example 1

{}

// Example 2

{}

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-09-16 19:20 UTC] bukka@php.net
-Package: json +Package: JSON related
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Nov 21 20:01:29 2024 UTC