Giter Site home page Giter Site logo

jsonmapper's People

Contributors

carusogabriel avatar cweiske avatar cybottm avatar darkgaro avatar dermanomann avatar deyv avatar frostiede avatar fruit avatar itscaro avatar jalle19 avatar jaredchu avatar jonaswouters avatar jorrit avatar kirtixs avatar loco8878 avatar lukascernydis avatar m1ke avatar maikschneider avatar mateusrevoredo avatar olegmelnik avatar patrickallaert avatar philsturgeon avatar reinfi avatar remicollet avatar samnela avatar sonicgd avatar svenrtbg avatar tysonandre avatar vinkla avatar wundii avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsonmapper's Issues

Stable version?

Hello good sir,

Could you please provide a stable version like v1.0.0?
We always want stable dependencies in our project but I really like your json mapper.
That way we (and I bet many others) can use it. :)

Thanks in advance :)

Nested classes with list in them

I have an User class that has a list of assigned Groups, I can't figure out how to make the mapper create the list of Groups for that User class.

User.php

class User {
    /** @var string **/
    public $name;

    /** @[IDK WHAT TO PUT HERE SINCE THIS IS A LIST of GROUP.php] **/
    public $groups;
}

Group.php

class Group {
    /** @var string **/
    public $name;
}

Decoded json strings should be treated equally.

I think these two line should work the same way:

$jsonMapper->map(json_decode($jsonString), new MyObject);
$jsonMapper->map(json_decode($jsonString, true), new MyObject);

With release 0.8, I cannot use the second form anymore, and I don't see a good explanation why. The test suite would run, with the exception of places where typehinting intentionally does not enforce a type, so the native value shines through, i.e. either a stdClass object or an array.

Fill arrays via add method?

Hi,

thanks for your work! For Arrays/ArrayCollections we sometimes only have add methods, no setter, in our entities available. Is it possible to call the add function for each Array/ArrayCollection element instead of the setter? The name of the function should then include a singularized form of the entity, e.g. for "translations" "addTranslation()" (e.g. with the help of https://github.com/doctrine/inflector/blob/master/lib/Doctrine/Common/Inflector/Inflector.php#L369)

Thank you!
Wolfram

Stable

If I target version ^1.1 with composer, it shows me an error about the version not being stable. Would it be possible to release a stable version with the updates since version 0.10.*, as that's marked as the last stable version?

Thanks in advance

Feature requests: use clauses and multidimensional arrays

Hello,
We are using your solution in one of our projects, but we needed it to have support for:

1) "use" clauses: jsonmapper would add the wrong namespace for classes belonging to a namespace declared with "use", as in the following example:

<php
namespace MyNamespace;

use OtherNamespace\Class1;
use Class2;

class ClassToBeMapped
{
   /** @var Class1 **/
   public $oObject1;
   /** @var Class2 **/
   public $oObject2;
}

2. Multidimensional arrays: jsonmapper would fail to map the following example:

<php
namespace MyNamespace;

class ClassToBeMapped
{
   /** @var int[][] **/
   public $arrIntMatrix;
   /** @var Class1[][][][] **/
   public $arrMultiverseOfClass1;
}

I have created a fork to fix these two issues, which I am adding as a pull request ok? (I apologize for my previous pull requests, I forgot to add an issue first - mea culpa).

Hope this can help other users! :)

See #82.

Q: Use extended ArrayObject for deserialization?

I wanted to ask whether it is possible to use an extended version of ArrayObject to deserialize json to classes. Will it still work for PHP annotation, e.g. \My\Namespace\ArrayObject[User]?

Question - setting property when value is object

Hello,

We're using JsonMapper a little bit different then it was intended to.
TL;DR - JsonMapper helps us to convert Eloquent models to plain entities.

We're making array from model, and then JsonMapper tries to set the values to entity.

We've found one problem.
Let's say we have this entity:

<?php

class Job
{
    public function setPrice(\Money\Money $price) {}
}

The array which we want to map looks like:

[
    'price' => \Money\Money::EUR(100),
]

JsonMapper::map() tries to invoke new instance of Money and then map values from $jvalue to it. This creates fatal error since this class doesn't allow to create instance without constructor arguments.

Now the question part - since price is already instance of Money maybe JsonMapper could simply set the property (similar to simple types https://github.com/netresearch/jsonmapper/blob/master/src/JsonMapper.php#L128)?
I know that in real world example (mapping plain JSON) this won't happen yet this is a thing we really like to have :)

If this makes sense to you let me know, we can provide a sample PR.

Thank you,

Choose class depending on object property

I have a json source that has a type property on which depends the existence of several more properties.
I wanted to have a parent class for the common properties and some child classes for the multiple values of type with their own special properties.
I thought of using a Factory to create my classes depending on this parameter but I don't know how to make this work with jsonmapper.

Can you give me a hint or tell me if it isn't possible ? Thanks

Custom casting to type

I have some 3rd party API which has some (at least one) unusual things:

  • Booleans are 1 letter instead of true/false (J=true, N=no)

Is it possible to reverse the order, or to force some kind of custom mapping? Because when I have a public property $active and a method setActive($val), the public property is always used instead of the setter, right?

Or should I just run a pre-map filter on my data?

New release

Could you make a new release with the latest changes ? I need those changes in the stable release.

Thanks

DateTime not working

I think you have missed copying the following code snippet that yeroon contributed:

if($type == '\\DateTime'){
    $child = new \DateTime($jvalue);
    $this->setProperty($object, $key, $child);
    continue;
}

I added it now manually and it works like expected.

subtype null with parent that extends ArrayObject

Hi.

Thanks for this library.

I'm trying to map items into an object that extends ArrayObject.

From the documentation this appears to be supported, but the mapper never assigns a value to subtype when it enters the else case on line 245:

See JsonMapper.php#L243-L260:

            $array = null;
            $subtype = null; // never assigned for 'is_subclass_of($type, 'ArrayObject')' branch
            if (substr($type, -2) == '[]') {
                //array
                $array = array();
                $subtype = substr($type, 0, -2);
            } else if (substr($type, -1) == ']') {
                list($proptype, $subtype) = explode('[', substr($type, 0, -1));
                if (!$this->isSimpleType($proptype)) {
                    $proptype = $this->getFullNamespace($proptype, $strNs);
                }
                if ($proptype == 'array') {
                    $array = array();
                } else {
                    $array = $this->createInstance($proptype);
                }
            } else if ($type == 'ArrayObject'
                || is_subclass_of($type, 'ArrayObject')
            ) {
                // $subtype left as null
                $array = $this->createInstance($type);
            }

This then throws an error on line 260 when the subtype is cleaned and only the namespace remains, and php attempts to new up that namespace as a class:

            if ($array !== null) {
                if (!is_array($jvalue) && $this->isFlatType(gettype($jvalue))) {
                    throw new JsonMapper_Exception(
                        'JSON property "' . $key . '" must be an array, '
                        . gettype($jvalue) . ' given'
                    );
                }

                $cleanSubtype = $this->removeNullable($subtype);
                if (!$this->isSimpleType($cleanSubtype)) {
                    $subtype = $this->getFullNamespace($cleanSubtype, $strNs);
                }
                $child = $this->mapArray($jvalue, $array, $subtype); // $subtype is the namespace here

Is this a bug, or am I missing something?

Thanks,
Jim.

Mapper can't read phpdoc on server

I've got a problem, that locally everything works fine, but on server the phpdoc is not read.

Left side is local version, right side is on an actual server:
image

You can see the phpdoc is missing.

What could be the cause of this? Reflection class don't exist on server? If so, why does the code still work, but when parsing the json file it just throws out an error, because a field is null (in phpdoc it is mentioned as null).

DateTime doesn't parse correctly from json

I've got a class with a DateTime property

/**
 * @var DateTime
 */
public $activeAt;

When mapping to the class from a json object which has a serialized DateTime object

stdClass Object
(
    [date] => 2015-05-01 00:00:00.000000
    [timezone_type] => 3
    [timezone] => UTC
)

An exception is thrown

DateTime::setDate() expects exactly 3 parameters, 1 given

In setProperty() in JsonMapper.php (line 381)


I see under Supported Type names that DateTime is not listed, but immediately after that in simple type mapping there is an example given using DateTime.

Do I need to enforce the DateTime on the serializing object be output as date in order for jsonmapper to correctly parse it?

Dependancy Injection support

Is it possible to provide an instance of an object to be injected in to the models that JsonMapper automatically creates from comment hints?

Calling mapArray when null

I have a case where mapArray is being called even when json element is null. This ends up creating an empty object when property should be set to null.

So on line 144 in JsonMapper.php in my use case $jvalue is NULL. I believe there should be a check for NULL and in that case just assign the null instead of calling mapArray.

            if ($array !== null) {
                if (!$this->isSimpleType($subtype)) {
                    $subtype = $this->getFullNamespace($subtype, $strNs);
                }
144:         $child = $this->mapArray($jvalue, $array, $subtype);
            }

[Proposal] Model/Class Generator

So the other day I had the need for like 20 Models and was to lazy write them all from hand so I wrote a little "Generator" which creates the model class from an array/object and is simple to use.

$model = new JsonMapperModel([
    'userId' => 1,
    'id' => 1,
    'title' => 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
    'body' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nesciunt nemo earum, blanditiis harum aliquam minus id repellendus quia libero expedita itaque beatae et voluptate pariatur eos, voluptatem, saepe inventore tempora!',
    'created' => '2015-08-01 18:34:01',
], 'Vendor\Package', 'ClassName');

echo($model->raw());
<?php

namespace Vendor\Package;

class ClassName
{
    /**
     * @var integer
     */
    public $userId;

    /**
     * @var integer
     */
    public $id;

    /**
     * @var string
     */
    public $title;

    /**
     * @var string
     */
    public $body;

    /**
     * @var \DateTime
     */
    public $created;
}

Since JsonMapper does not rely on any schema information (e.g. from json-schema), model classes cannot be generated automatically.

Does this mean you're against a Generator in this package and this should be done external or would you accept a PR with a Generator?

Support for PHP 7.1 nullable types

Currently, type definitions are only considered nullable if the docblock provides a |null declaration in the @param tag or a default null value like Object $obj = null. With PHP 7.1 it should also be possible to declare a property as nullable using ?Object.

However, this will throw an exception, as it is not detected as a nullable type:
JSON property "obj" in class "Foo\Bar" must not be NULL

See pull request #68 for a possible fix.

Support public getters

It would be very convenient if the jsonmapper would have support for public getters as well. The requirement of making fields public would become obsolete. Also, it would help to maintain a constant (JSON) API while being able to change the class. Example:

<?php
class Address
{
    private $street;
    // ...

    /**
     * @var string
     */
    public function getStreet()
    {
        return $this->street;
    }

    // ...
}
?>

How to map Map types?

How is it possible to map Map types, eg the JSON looks like this:

{
  "changes": {
    "file:///user/felix/my_file.php": {
      "range": {
        "start": { "line": 1, "character": 1 },
        "end": { "line": 1, "character": 2 }
      },
      "newText": "whatever"
    },
    "file:///user/felix/my_file2.php": {
      "range": {
        "start": { "line": 1, "character": 1 },
        "end": { "line": 1, "character": 2 }
      },
      "newText": "someNewText"
    }
  }
}

The classes look like this:

class WorkspaceEdit
{
  /**
    * Maps URIs to TextEdits.
    *
    * @var ?
    */
  public $changes;
}

/**
 * A textual edit applicable to a text document.
 */
class TextEdit
{
    /**
     * The range of the text document to be manipulated. To insert
     * text into a document create a range where start === end.
     *
     * @var Range
     */
    public $range;

    /**
     * The string to be inserted. For delete operations use an
     * empty string.
     *
     * @var string
     */
    public $newText;
}

class Range
{
     /**
     * The range's start position.
     *
     * @var Position
     */
    public $start;

    /**
     * The range's end position.
     *
     * @var Position
     */
    public $end;
}

class Position
{
    /**
     * Line position in a document (zero-based).
     *
     * @var int
     */
    public $line;

    /**
     * Character offset on a line in a document (zero-based).
     *
     * @var int
     */
    public $character;
}

Now, I see two possibilities for typing the $changes property:

  • type it as an associative array TextEdit[] - JsonMapper would have to convert the stdClass object to an associative array with get_object_vars() or by casting.
  • type it as a Map type (supports array syntax)
  • type it as mixed
    it will be an stdClass object and all the properties two, so not really a viable solution.
    Which of these ways is supported by JsonMapper?

My usecase is implementing the Language Server Protocol in PHP to build a PHP Language Server. It builds on the JSONRPC protocol and I would like to use JsonMapper to map the requests recursively to the right classes because the JSON is heavily structured. But in the definition of WorkspaceEdit they use this map type: https://github.com/Microsoft/language-server-protocol/blob/master/protocol.md#workspaceedit, which I don't know how to type.

Map json which have array of products.

I have a json which have array of products i want to map that array of products to the cart class object which have an array of products types. How can i do that.
I get the error like:

Warning: Invalid argument supplied for foreach() in src/JsonMapper.php on line 73

mapProperty / mapArrayIndex methods

Use case:
Having a class instance or array of such and wanting to map a JSON value at a specific property, or an array and wanting to map a JSON value at a specific index.
Instead of providing one object/array to the function, you provide an object/array and the property/index.
The JsonMapper would figure out the type of the property at the object.
The existing map and mapArray functions would call these internally, so it's just refactoring logic and making it available as public functions.

Example:

class A {
  /** @var B */
  public $b;
}
class B {
  /** @var int */
  public $number;
}

// For properties:
$a = new A;
$mapper->mapProperty(json_decode('{"number": 123}'), $a, 'b');
assert($a->b instanceof B);
assert($a->b->number === 123);

// For arrays:
$bs = [];
$bs = $mapper->mapArrayIndex(json_decode('{"number": 123}'), $bs, 0, B::class);
assert($bs[0] instanceof B);
assert($bs[0]->number === 123);

The use case is for mapping not a complete JSON result, but mapping a JSON value that is only part of a whole. This is needed when wanting to map JSON Patches, because all you have is a target and a property path to the property/index you want to modify.

WDYT?

Jsonmapper not works if the object property have the '_' underscore within it.

I am facing issue with jsomapper. Jsonmapper fail to map json property to custom class property if json property and class property both have underscore within it. Or i am doing it wrong.

class property:

    /**
     *  This value is array.
     * @var array
     */protected $templates_json = array();

json property:

"templates_json": "<LARGE_JSON_STRING_HERE>",

Mapper cant handle null values

Hey,
I just tried this nice lib and I had to replace my null strings with "", could you add the possibility to use null values. I just searched a bit and found out, null is a valid JSON value (even if some languages dont support it, they replace it with an empty array)

PHP Fatal error: Uncaught JsonMapper_Exception: JSON property "url" in class "UploadData
" must not be NULL in /vendor/netresearch/jsonmapper/src/Jso
nMapper.php(376): JsonMapper->map(Object(stdClass), Object(UploadData))\n#1 : JsonMapper->mapArray(Array, Array, 'UploadData')\n#2 {main}\n

Support for 64bit ints on 32 bit systems.

Not sure if the title explains this as well as i'd hope, but basically, i'm getting data back from an API that contains a 64bit integer. This works fine and dandy on 64bit PHP installs, but part of my userbase uses 32bit installs, and id like to still be able to support them.

Is there an easy way to do this?

An option to throw an Exception when a flat type is found instead on an object

The variable $bExceptionOnMissingData gives an option to let JsonMapper throw an exception if there are missing required properties. But this does not let it throw an exception when a flat type is detected and the class has not constructor (or maybe it has, but it's not expecting to get that value).

Take the following JSON data as an example

{
    "id": 1,
    "text": "Some text",
    "user": "Some user"    <-- This one
}

The mapper should throw an exception if user was a type of some class and a flat type is given.

For now, I've just extended the class and give it an option to allow throwing an exception when detecting a flat type.

class JsonMapper extends \JsonMapper {

    protected $bExceptionOnFlatType = true;

    protected function isFlatType($type) {
        if ( $this->bExceptionOnFlatType && parent::isFlatType($type) ) {
            throw new \JsonMapper_Exception(
                'Invalid data type for some properties'
            );
        }

        return false;
    }

}

Is it possible to add a variable similar to $bExceptionOnFlatType?

ReflectionClass

Hello, can you tell me why I have to shield ReflectionClass, that everything would work? \ReflectionClass in 141 line

Exception raised when @param type is "mixed"

When trying to map an object with the param "mixed", an exception is raised by JsonMapper saying the class cannot be found.

I was able to fix this by changing line 172 to

if ($jvalue === null || $type === 'mixed') {

I'm not certain this is the best way to approach the problem (feels too quick and dirty to me) tho so that's why I'm not submitting a pull request. I hope this helps :). Keep up the good work!

Set protected array of object

Hi,
I would like to set a protected Comment[] array inside a Post class. Il looks like this :
Post.php :

<?php
namespace Test\Model;

class Post
{
    /**
     * Post comments
     * @var \Test\Model\Comment[]
     */
    protected $comments;
    public function setComments($comments) { $this->comments = $comments; }

}

Comment.php :

<?php
namespace Test\Model;

class Comment
{
    //properties
}

According to the doc, it seems that jsonMapper does not recognize \Test\Model\Comment[], so every comment I've set are stdClass, not \Test\Model\Comment. When I set Post::$comments scope to public, the type of every Comment is correctly set.
Is there a way to manage it through protected properties ?

Mapper wrong map nested objects.

Model

<?php

namespace Stom\Api\Model;

use Stom\Api\Util\DocumentSerializer;


class Account {

    use DocumentSerializer;

    public function __construct() {
        $this->setIgnoredFields(array('password'));
    }

    /**
     * @int
     */
    public $id;

    /**
     * @var string
     */
    public $email;

    /**
     * @var string
     */
    public $password;

    /**
     * @var Session[]
     */
    public $sessions = [];

    /**
     * @var int
     */
    public $type;

    /**
     * @var boolean
     */
    public $pending;

    public function getSessions() {
        return $this->sessions;
    }

    public function addSession() {
        $session = new Session();
        $session->token = bin2hex(openssl_random_pseudo_bytes(32));
        $session->expiresAt = \date('Y-m-d H:i:s', \strtotime('+1 days', \time()));
        $this->sessions = [$session];
    }

    public function getPending() {
        return $this->pending;
    }

    public function setPending($isPending) {
        $this->pending = $isPending;
    }
    public function getPassword() {
        return $this->password;
    }

    public function setPassword($password) {
        $this->password = $password;
    }


}

class Session {

    /**
     * @var string
     */
    public $token;

    /**
     * @var \DateTime
     */
    public $expiresAt;

}

Json:

{
    "id": 1,
    "email": "[email protected]",
    "type": 0,
    "pending": false,
    "password": "123qwe",
    "sessions": [
        {
            "token": "f6a34f8d884e2ea28f6321977d9df25b320614924ee07d224d7d5c2279dfe715",
            "expiresAt": {
                "date": "2015-08-09 04:33:23",
                "timezone": "Asia\/Novosibirsk",
                "timezone_type": 3
            }
        }
    ]
}

And exception:

The application could not run because of the following error:

Details

Type: ErrorException
Code: 2
Message: DateTime::setDate() expects exactly 3 parameters, 1 given
File: /home/sidochenko/projects/csm/api/src/Stom/Api/Util/JsonMapper/JsonMapper.php
Line: 375
Trace

#0 [internal function]: Slim\Slim::handleErrors(2, 'DateTime::setDa...', '/home/sidochenk...', 375, Array)
#1 /home/sidochenko/projects/csm/api/src/Stom/Api/Util/JsonMapper/JsonMapper.php(375): DateTime->setDate('2015-08-09 04:3...')
#2 /home/sidochenko/projects/csm/api/src/Stom/Api/Util/JsonMapper/JsonMapper.php(139): Stom\Api\Util\JsonMapper\JsonMapper->setProperty(Object(DateTime), 'date', '2015-08-09 04:3...', Object(ReflectionMethod))
#3 /home/sidochenko/projects/csm/api/src/Stom/Api/Util/JsonMapper/JsonMapper.php(196): Stom\Api\Util\JsonMapper\JsonMapper->map(Object(stdClass), Object(DateTime))
#4 /home/sidochenko/projects/csm/api/src/Stom/Api/Util/JsonMapper/JsonMapper.php(282): Stom\Api\Util\JsonMapper\JsonMapper->map(Object(stdClass), Object(Stom\Api\Model\Session))
#5 /home/sidochenko/projects/csm/api/src/Stom/Api/Util/JsonMapper/JsonMapper.php(182): Stom\Api\Util\JsonMapper\JsonMapper->mapArray(Array, Array, '\Stom\Api\Model...')
#6 /home/sidochenko/projects/csm/api/src/Stom/Api/Util/DBALext/Statement.php(264): Stom\Api\Util\JsonMapper\JsonMapper->map(Array, Object(Stom\Api\Model\Account))
#7 /home/sidochenko/projects/csm/api/src/Stom/Api/Services/AccountService.php(45): Stom\Api\Util\DBALext\Statement->fetch(Object(Stom\Api\Model\Account))
#8 /home/sidochenko/projects/csm/api/src/Stom/Api/Services/AccountService.php(89): Stom\Api\Services\AccountService->get('1')
#9 /home/sidochenko/projects/csm/api/src/Stom/Api/Route/AccountRoute.php(47): Stom\Api\Services\AccountService->generateToken('1')

I have little changed class (added some use statements), so here it is (to match string number in exception): https://gist.github.com/clicman/960e685c450d6442024f

Somehow it starts iterate over DateTime object. Ive tried two previous releases - same error appears.

As workaround I can implement

class Account {
        .....
         setSessions($session) {
                $this->sessions[]=$session;
         }
         ....

But it`s dirty because this method should be called addSession instead. :)

Map from ID

I have an API that returns references to other resources rather than embedding some of the data:

{
  "id": 1,
  "items": [
    "http://example.com/api/items/1",
    "http://example.com/api/items/4"
  ]
}

What do you think about creating a partial object, in a way like this?

class A {
    /**
     * @var int
     * @required
     */
    public $id;

    /**
     * @var B[]
     */
    public $items;
}

class B {
    /**
     * @var string
     * @key
     */
    public $url;

    /**
     * @var string
     * @required
     */
    public $name;
}
  • One @key (or @primary, @id, etc.) would be allowed per object,
  • The @required property on B would not be set (even with bExceptionOnMissingData = true, this would be okay),
  • There might also need to be some way of marking an object as partial, although this could be left up to the user.

Thoughts?

Handling multiple types for one field

I am currently working with an API that returns one field in two possible formats.

/**
 * @var \Models\Field[]
 */
public $field;

For a single entity the field gets returned as an object with data

"field" : {
    "id" : "123",
    "name" : "John"
}

And for lists/all the same field gets returned as a list of IDs.

"field" : {
    "123",
    "123",
    "123",
    "123",
    "123",
}

The issue I am having is that I still need to map the IDs from the lists JSON to Models as $model->id. So I would need some way to check if the data is a string or an object once it went to the model to manually assign the $model->id if it is a string.

Is there any way to do this easily at the moment or would I need to write a workaround?

Manage abstract classes

Hi,
Is there a way to fill an arrayObject with classes which inherits from an abstract class usin jsonMapper ?
It seems that when an abstract class is given to the mapper, he tries to instanciate it, where i would use a child class.

Feature Request: Create exception if the value that a setter gives to a property be null

What I mean with this Feature Request, it's the following.:

A setter can do a check if the data passed as parameter it's real valid, not by the argument variable type.

As example.: I have a property called "uniqueIdentifier" and when it's set by the setter (setUniqueIdentifier), will check if this uniqueIdentifier exists on the database.

So when it does not exists, I set the property uniqueIdentifier to NULL. So jSON Mapper could have a feature that (like $mapper->bCheckSetterValue) will check if the value of the property after being set by a seeter results in a NULL value, and if does, throw an exception.

I think it's a really interesting functioanlity and if you want I can create a PR for it.

autoloaders

There is a problem with autoloaders. Breaks here in this place || is_subclass_of ($ type, 'ArrayObject').
Ideally, it would be like this remake || is_subclass_of ($ type, 'ArrayObject', false)
The first option is the autoloader. And it does not always work correctly. What can you do?

Namespace is prepended two times

When mapping JSON to a class having objects array as property, the (inferred) full qualified namespace of $subtype is wrong in certain cases. The namespace is prepended two times to the original class name.

Here is an exemple :

<?php

namespace Vendor\MyNamespace {

    class Something
    {
        /**
         * @var string
         */
        public $name;

        /**
         * @var string
         */
        public $value;

        /**
         * @var AnotherThing[]
         */
        public $anotherThing;
    }

    class AnotherThing
    {
        /**
         * @var string
         */
        public $label;
    }

}

namespace {

    require_once 'vendor/netresearch/jsonmapper/src/JsonMapper.php';
    require_once 'vendor/netresearch/jsonmapper/src/JsonMapper/Exception.php';

    use Vendor\MyNamespace\Something;

    class Launcher
    {
        public static function run()
        {
            $json = '
            {
                "name": "Name of the thing",
                "value": "Value of the thing",
                "anotherThing": [
                    { "label" : "yep" },
                    { "label" : "nope" }
                ]
            }';

            $jsonObject = json_decode($json);
            $mapper = new \JsonMapper();
            $something = new Something();
            $result = $mapper->map($jsonObject, $something);

            return $result;
        }
    }

    print_r(\Launcher::run());

}

Execution of this piece of code throws a Fatal error :

Fatal error: Class 'Vendor\MyNamespace\Vendor\MyNamespace\AnotherThing' not found in ...

At line 98 namespace is prepended to an already-namespaced-class.

Online tool

It would be amazing to have that tool available on a webpage somewhere ;-)

Support of Dynamic Class Population

Hello, i'm wondering if this libraries handles the following scenario:

  1. I have a base Model called (MessageModel), this Model extends the MessageInterface that necessary have the following functions: PHP Magic Function: get(), that is used to get a specific Variable.

What i want is that the JsonMapper, populates dynamicly the MessageModel with the fields returned from Database, that means, JsonMapper creates the variables based on the PHP's Anonymous Classes and Closures Typing..

Is that possible?

Remove declare() calls

Why are you using declare() to specify encoding ? This is only supported when zend multibyte is turned on, otherwise it generates a warning.

classMap

Can you add support form mapping into simple type.

public function createInstance(
        $class, $useParameter = false, $parameter = null
    ) {
        if (isset($this->classMap[$class])) {
            $class = $this->classMap[$class];
        }
        // Check if mapping to simple type
        if ($this->isSimpleType($class)) return $class;

        if ($useParameter) {
            return new $class($parameter);
        } else {
            return new $class();
        }
    }

Performance

This library looks great and I was looking forward to using it on a project, but I ran into some issues with performance. Deserializing 150 or so entities took around 6 seconds, whereas coding it manually the same collection takes 60ms.

Is there anything which can be done to improve performance? Or is it a constraint of PHP docblock parsing?

Class not found?

Hello there, ive been using this for a while without any issue, nevertheless this was appearing recently in one of the requests i have done, im not sure if its my fault.

  $responseObject = $mapper->map($response[1], $obj);

Where $obj is the class, and $response[1] the JSON. Both vars are okay, but its throwing me this error:

PHP Fatal error: Class '\InstagramAPI\Explore|string' not found in /Users/mgp25/Desktop/Instagram-API/vendor/netresearch/jsonmapper/src/JsonMapper.php on line 541

Note that is looking for Explore|string and i don't even know what is that

Regards

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.