PHP docblock for json_decode-d objects
Asked Answered
C

2

0

I'm getting objects from JSON string in my PHP code. I want my IDE (NetBeans) to know the parameters of the objects without creating special class for them.

Can I do it?

It would look something like:

$obj = json_decode($string);
/** 
 * @var $obj { 
 *     @property int    $id
 *     @property string $label
 * } 
*/
Cronk answered 28/1, 2021 at 22:17 Comment(6)
Does this answer your question? phpdoc - defining return object variables for a methodAspiration
The question you quote is very poorly named and asked and has no accepted answer. The answer looks somewhat relevant, but in my question I specify "without creating special class".Cronk
Well, the most upvoted answer there basically says that you cant (even though its a few years old, grantedly).Aspiration
@Aspiration I just answered my question and the question you quoted. Bottom line is - "yes you actually can".Cronk
As long as you are not counting creating an anonymous class as "creating a special class for them".Aspiration
@Aspiration , At least I don't need to create an extra file for it to follow PSR4 spec . Anonymous class is a fine quick patch.Cronk
C
0

As I'm using PHP 7 I can define anonymous class.

So, my solution was:

        $obj = (new class {

                /**
                 * @property int $id 
                 */
                public /** @var string */ $label;

                public function load(string $string): self
                {
                    $data = json_decode($string, true);
                    foreach ($data as $key => $value) {
                        $this->{$key} = $value;
                    }                        
                    
                    return $this;
                }
            })->load($string);


        echo $obj->id;
        echo $obj->label;

I think it is an amazing spaghetti dish.

Cronk answered 28/1, 2021 at 23:43 Comment(0)
C
0

Here is a structured version for it

first, you make a class somewhere in your helpers folder

<?php

namespace App\Helpers;

use function json_decode;

class JsonDecoder
{


    public function loadString(string $string): self
    {
        $array = json_decode($string, true);

        return $this->loadArray($array);
    }


    public function loadArray(array $array): self
    {
        foreach ($array as $key => $value) {
            $this->{$key} = $value;
        }

        return $this;
    }


}

then, you use it with care

        $obj= (new class() extends JsonDecoder {
                public /** @var int     */ $id;
                public /** @var string  */ $label;
            });
        $obj->loadString($string);

        echo $obj->id;
        echo $obj->label;
Cronk answered 29/1, 2021 at 0:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.