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
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
Have you experienced this issue?
Rate the importance of this bug to you:

 [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

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-09-16 19:20 UTC] bukka@php.net
-Package: json +Package: JSON related
 
PHP Copyright © 2001-2018 The PHP Group
All rights reserved.
Last updated: Fri Jun 22 17:01:44 2018 UTC