example
4 years ago
src
2 months ago
CONTRIBUTING.md
2 months ago
ChangeLog
4 years ago
LICENSE
2 months ago
README.rst
2 months ago
composer.json
2 months ago
package.xml
4 years ago
phpunit.xml
2 months ago
sonar-project.properties
2 months ago
README.rst
531 lines
| 1 | ******************************************************** |
| 2 | JsonMapper - map nested JSON structures onto PHP classes |
| 3 | ******************************************************** |
| 4 | |
| 5 | .. image:: https://img.shields.io/packagist/v/apimatic/jsonmapper.svg?style=flat |
| 6 | :target: https://packagist.org/packages/apimatic/jsonmapper |
| 7 | .. image:: https://img.shields.io/packagist/dm/apimatic/jsonmapper.svg?style=flat |
| 8 | :target: https://packagist.org/packages/apimatic/jsonmapper |
| 9 | .. image:: https://github.com/apimatic/jsonmapper/workflows/Tests/badge.svg |
| 10 | :target: https://github.com/apimatic/jsonmapper/actions?query=workflow%3ATests |
| 11 | .. image:: https://sonarcloud.io/api/project_badges/measure?project=apimatic_jsonmapper&metric=coverage |
| 12 | :target: https://sonarcloud.io/summary/new_code?id=apimatic_jsonmapper |
| 13 | .. image:: https://sonarcloud.io/api/project_badges/measure?project=apimatic_jsonmapper&metric=sqale_rating |
| 14 | :target: https://sonarcloud.io/summary/new_code?id=apimatic_jsonmapper |
| 15 | .. image:: https://sonarcloud.io/api/project_badges/measure?project=apimatic_jsonmapper&metric=vulnerabilities |
| 16 | :target: https://sonarcloud.io/summary/new_code?id=apimatic_jsonmapper |
| 17 | .. image:: https://img.shields.io/packagist/l/apimatic/jsonmapper.svg?style=flat |
| 18 | :target: LICENSE |
| 19 | |
| 20 | Takes data retrieved from a JSON__ web service and converts them |
| 21 | into nested object and arrays - using your own model classes. |
| 22 | |
| 23 | Starting from a base object, it maps JSON data on class properties, |
| 24 | converting them into the correct simple types or objects. |
| 25 | |
| 26 | It's a bit like the native SOAP parameter mapping PHP's ``SoapClient`` |
| 27 | gives you, but for JSON. |
| 28 | Note that it does not rely on any schema, only your class definitions. |
| 29 | |
| 30 | Type detection works by parsing ``@var`` docblock annotations of |
| 31 | class properties, as well as type hints in setter methods. If docblock comments, |
| 32 | or comments in general are discarded through some configuration setting like ``opcache.save_comments=0``, |
| 33 | or any other similar configuration, an exception is thrown, blocking any further operation. |
| 34 | |
| 35 | You do not have to modify your model classes by adding JSON specific code; |
| 36 | it works automatically by parsing already-existing docblocks. |
| 37 | |
| 38 | Keywords: deserialization, hydration |
| 39 | |
| 40 | __ http://json.org/ |
| 41 | |
| 42 | |
| 43 | .. contents:: |
| 44 | |
| 45 | ============ |
| 46 | Pro & contra |
| 47 | ============ |
| 48 | |
| 49 | Benefits |
| 50 | ======== |
| 51 | - Autocompletion in IDEs |
| 52 | - It's easy to add comfort methods to data model classes |
| 53 | - Your JSON API may change, but your models can stay the same - not |
| 54 | breaking applications that use the model classes. |
| 55 | |
| 56 | Drawbacks |
| 57 | ========= |
| 58 | - Model classes need to be written by hand |
| 59 | |
| 60 | Since JsonMapper does not rely on any schema information |
| 61 | (e.g. from `json-schema`__), model classes cannot be generated |
| 62 | automatically. |
| 63 | |
| 64 | __ http://json-schema.org/ |
| 65 | |
| 66 | |
| 67 | ===== |
| 68 | Usage |
| 69 | ===== |
| 70 | |
| 71 | Basic usage |
| 72 | =========== |
| 73 | #. Register an autoloader that can load `PSR-0`__ compatible classes. |
| 74 | #. Create a ``JsonMapper`` object instance |
| 75 | #. Call the ``map`` or ``mapArray`` method, depending on your data |
| 76 | |
| 77 | Map a normal object: |
| 78 | |
| 79 | .. code:: php |
| 80 | |
| 81 | <?php |
| 82 | require 'autoload.php'; |
| 83 | $mapper = new JsonMapper(); |
| 84 | $contactObject = $mapper->map($jsonContact, new Contact()); |
| 85 | ?> |
| 86 | |
| 87 | Map an array of objects: |
| 88 | |
| 89 | .. code:: php |
| 90 | |
| 91 | <?php |
| 92 | require 'autoload.php'; |
| 93 | $mapper = new JsonMapper(); |
| 94 | $contactsArray = $mapper->mapArray( |
| 95 | $jsonContacts, new ArrayObject(), 'Contact' |
| 96 | ); |
| 97 | ?> |
| 98 | |
| 99 | __ http://www.php-fig.org/psr/psr-0/ |
| 100 | |
| 101 | |
| 102 | Example |
| 103 | ======= |
| 104 | JSON from a address book web service: |
| 105 | |
| 106 | .. code:: javascript |
| 107 | |
| 108 | { |
| 109 | 'name':'Sheldon Cooper', |
| 110 | 'address': { |
| 111 | 'street': '2311 N. Los Robles Avenue', |
| 112 | 'city': 'Pasadena' |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | Your local ``Contact`` class: |
| 117 | |
| 118 | .. code:: php |
| 119 | |
| 120 | <?php |
| 121 | class Contact |
| 122 | { |
| 123 | /** |
| 124 | * Full name |
| 125 | * @var string |
| 126 | */ |
| 127 | public $name; |
| 128 | |
| 129 | /** |
| 130 | * @var Address |
| 131 | */ |
| 132 | public $address; |
| 133 | } |
| 134 | ?> |
| 135 | |
| 136 | Your local ``Address`` class: |
| 137 | |
| 138 | .. code:: php |
| 139 | |
| 140 | <?php |
| 141 | class Address |
| 142 | { |
| 143 | public $street; |
| 144 | public $city; |
| 145 | |
| 146 | public function getGeoCoords() |
| 147 | { |
| 148 | //do something with the $street and $city |
| 149 | } |
| 150 | } |
| 151 | ?> |
| 152 | |
| 153 | Your application code: |
| 154 | |
| 155 | .. code:: php |
| 156 | |
| 157 | <?php |
| 158 | $json = json_decode(file_get_contents('http://example.org/bigbang.json')); |
| 159 | $mapper = new JsonMapper(); |
| 160 | $contact = $mapper->map($json, new Contact()); |
| 161 | |
| 162 | echo "Geo coordinates for " . $contact->name . ": " |
| 163 | . var_export($contact->address->getGeoCoords(), true); |
| 164 | ?> |
| 165 | |
| 166 | Letting JsonMapper create the instances for you |
| 167 | =============================================== |
| 168 | |
| 169 | Map a normal object (works similarly to ``map``): |
| 170 | |
| 171 | .. code:: php |
| 172 | |
| 173 | $mapper = new JsonMapper(); |
| 174 | $contactObject = $mapper->mapClass($jsonContact, 'Contact'); |
| 175 | |
| 176 | Map an array of objects (works similarly to ``mapArray``): |
| 177 | |
| 178 | .. code:: php |
| 179 | |
| 180 | $mapper = new JsonMapper(); |
| 181 | $contactsArray = $mapper->mapClassArray($jsonContacts, 'Contact'); |
| 182 | |
| 183 | Map a value with any combination of types e.g oneOf(string,int) or anyOf(string,Contact): |
| 184 | |
| 185 | .. code:: php |
| 186 | |
| 187 | $mapper = new JsonMapper(); |
| 188 | $contactObject = $mapper->mapFor($value, 'oneOf(string,Contact)'); |
| 189 | |
| 190 | Property type documentation |
| 191 | =========================== |
| 192 | ``JsonMapper`` uses several sources to detect the correct type of |
| 193 | a property: |
| 194 | |
| 195 | #. The setter method (``set`` + ``ucwords($propertyname)``) is inspected. |
| 196 | |
| 197 | Underscores make the next letter uppercase, which means that |
| 198 | for a JSON property ``foo_bar_baz`` a setter method of |
| 199 | ``setFooBarBaz`` is used. |
| 200 | |
| 201 | #. If it has a type hint in the method signature, this type used:: |
| 202 | |
| 203 | public function setPerson(Contact $person) {...} |
| 204 | |
| 205 | #. The method's docblock is inspected for ``@param $type`` annotations:: |
| 206 | |
| 207 | /** |
| 208 | * @param Contact $person Main contact for this application |
| 209 | */ |
| 210 | public function setPerson($person) {...} |
| 211 | |
| 212 | #. If no type could be detected, the plain JSON value is passed |
| 213 | to the setter method. |
| 214 | |
| 215 | #. ``@var $type`` docblock annotation of class properties:: |
| 216 | |
| 217 | /** |
| 218 | * @var \my\application\model\Contact |
| 219 | */ |
| 220 | public $person; |
| 221 | |
| 222 | Note that the property has to be public to be used directly. |
| 223 | |
| 224 | If no type could be detected, the property gets the plain JSON value. |
| 225 | |
| 226 | If a property can not be found, JsonMapper tries to find the property |
| 227 | in a case-insensitive manner. |
| 228 | A JSON property ``isempty`` would then be mapped to a PHP property |
| 229 | ``isEmpty``. |
| 230 | |
| 231 | To map a JSON key to an arbitrarily named class property, you can use |
| 232 | the ``@maps`` annotation: |
| 233 | |
| 234 | .. code:: php |
| 235 | |
| 236 | /** |
| 237 | * @var \my\application\model\Person |
| 238 | * @maps person_object |
| 239 | */ |
| 240 | public $person; |
| 241 | |
| 242 | Supported type names: |
| 243 | |
| 244 | - Simple types: |
| 245 | |
| 246 | - ``string`` |
| 247 | - ``bool``, ``boolean`` |
| 248 | - ``int``, ``integer`` |
| 249 | - ``float`` |
| 250 | - ``array`` |
| 251 | - ``object`` |
| 252 | - Class names, with and without namespaces |
| 253 | - Arrays of simple types and class names: |
| 254 | |
| 255 | - ``int[]`` |
| 256 | - ``Contact[]`` |
| 257 | - ArrayObjects of simple types and class names: |
| 258 | |
| 259 | - ``ContactList[Contact]`` |
| 260 | - ``NumberList[int]`` |
| 261 | - Nullable types: |
| 262 | |
| 263 | - ``int|null`` - will be ``null`` if the value in JSON is |
| 264 | ``null``, otherwise it will be an integer |
| 265 | |
| 266 | ArrayObjects and extending classes are treated as arrays. |
| 267 | |
| 268 | Variables without a type or with type ``mixed`` will get the |
| 269 | JSON value set directly without any conversion. |
| 270 | |
| 271 | See `phpdoc's type documentation`__ for more information. |
| 272 | |
| 273 | __ http://phpdoc.org/docs/latest/references/phpdoc/types.html |
| 274 | |
| 275 | |
| 276 | Simple type mapping |
| 277 | ------------------- |
| 278 | When an object shall be created but the JSON contains a simple type |
| 279 | only (e.g. string, float, boolean), this value is passed to |
| 280 | the classes' constructor. Example: |
| 281 | |
| 282 | PHP code: |
| 283 | |
| 284 | .. code:: php |
| 285 | |
| 286 | /** |
| 287 | * @var DateTime |
| 288 | */ |
| 289 | public $date; |
| 290 | |
| 291 | JSON: |
| 292 | |
| 293 | .. code:: js |
| 294 | |
| 295 | {"date":"2014-05-15"} |
| 296 | |
| 297 | This will result in ``new DateTime('2014-05-15')`` being called. |
| 298 | |
| 299 | Custom property initialization |
| 300 | ------------------------------ |
| 301 | |
| 302 | You can use the ``@factory`` annotation to specify a custom method that |
| 303 | will be called to get the value to be assigned to the property. |
| 304 | |
| 305 | .. code:: php |
| 306 | |
| 307 | /** |
| 308 | * @factory MyUtilityClass::createDate |
| 309 | */ |
| 310 | public $date; |
| 311 | |
| 312 | Here, ``createDate`` method in the ``MyUtilityClass`` is called with the |
| 313 | raw value for ``date`` property and the value returned by the factory method |
| 314 | is then assigned to the ``date`` property. |
| 315 | |
| 316 | The factory method should return true when tested with ``is_callable``, otherwise |
| 317 | an exception will be thrown. |
| 318 | |
| 319 | The factory annotation can be used with other annotations such as ``@var``; however, |
| 320 | only the value created by the factory method will be used while other typehints and |
| 321 | initialization methods for the property will be ignored. |
| 322 | |
| 323 | Logging |
| 324 | ======= |
| 325 | JsonMapper's ``setLogger()`` method supports all PSR-3__ compatible |
| 326 | logger instances. |
| 327 | |
| 328 | Events that get logged: |
| 329 | |
| 330 | - JSON data contain a key, but the class does not have a property |
| 331 | or setter method for it. |
| 332 | - Neither setter nor property can be set from outside because they |
| 333 | are protected or private |
| 334 | |
| 335 | __ http://www.php-fig.org/psr/psr-3/ |
| 336 | |
| 337 | |
| 338 | Handling invalid or missing data |
| 339 | ================================ |
| 340 | During development, APIs often change. |
| 341 | To get notified about such changes, JsonMapper may throw exceptions |
| 342 | in case of either missing or yet unknown data. |
| 343 | |
| 344 | |
| 345 | Unknown properties |
| 346 | ------------------ |
| 347 | When JsonMapper sees properties in the JSON data that are |
| 348 | not defined in the PHP class, you can let it throw an exception |
| 349 | by setting ``$bExceptionOnUndefinedProperty``: |
| 350 | |
| 351 | .. code:: php |
| 352 | |
| 353 | $jm = new JsonMapper(); |
| 354 | $jm->bExceptionOnUndefinedProperty = true; |
| 355 | $jm->map(...); |
| 356 | |
| 357 | To process unknown properties yourself, you can set a method on the |
| 358 | class as a collection method: |
| 359 | |
| 360 | .. code:: php |
| 361 | |
| 362 | $jm = new JsonMapper(); |
| 363 | $mapper->sAdditionalPropertiesCollectionMethod = 'addAdditionalProperty'; |
| 364 | $jm->map(...); |
| 365 | |
| 366 | Here, the ``addAdditionalProperty()`` method will be called with a ``name`` and |
| 367 | a ``value`` argument. |
| 368 | |
| 369 | Missing properties |
| 370 | ------------------ |
| 371 | Properties in your PHP classes can be marked as "required" by |
| 372 | putting ``@required`` in their docblock: |
| 373 | |
| 374 | .. code:: php |
| 375 | |
| 376 | /** |
| 377 | * @var string |
| 378 | * @required |
| 379 | */ |
| 380 | public $someDatum; |
| 381 | |
| 382 | When the JSON data do not contain this property, JsonMapper will throw |
| 383 | an exception when ``$bExceptionOnMissingData`` is activated: |
| 384 | |
| 385 | .. code:: php |
| 386 | |
| 387 | $jm = new JsonMapper(); |
| 388 | $jm->bExceptionOnMissingData = true; |
| 389 | $jm->map(...); |
| 390 | |
| 391 | |
| 392 | Passing arrays to ``map()`` |
| 393 | --------------------------- |
| 394 | You may wish to pass array data into ``map()`` that you got by calling |
| 395 | |
| 396 | .. code:: php |
| 397 | |
| 398 | json_decode($jsonString, true) |
| 399 | |
| 400 | By default, JsonMapper will throw an exception because ``map()`` requires |
| 401 | an object as first parameter. |
| 402 | You can circumvent that by setting ``$bEnforceMapType`` to ``false``: |
| 403 | |
| 404 | .. code:: php |
| 405 | |
| 406 | $jm = new JsonMapper(); |
| 407 | $jm->bEnforceMapType = false; |
| 408 | $jm->map(...); |
| 409 | |
| 410 | |
| 411 | Handling polymorphic responses |
| 412 | ============================== |
| 413 | |
| 414 | JsonMapper allows you to map a JSON object to a derived class based on a discriminator |
| 415 | field. The discriminator field's value is used to decide which class this JSON object |
| 416 | should be mapped to. |
| 417 | |
| 418 | Your local ``Person`` class: |
| 419 | |
| 420 | .. code:: php |
| 421 | |
| 422 | <?php |
| 423 | /** |
| 424 | * @discriminator type |
| 425 | * @discriminatorType person |
| 426 | */ |
| 427 | class Person |
| 428 | { |
| 429 | public $name; |
| 430 | public $age; |
| 431 | public $type; |
| 432 | } |
| 433 | |
| 434 | Your local ``Employee`` class: |
| 435 | |
| 436 | .. code:: php |
| 437 | |
| 438 | <?php |
| 439 | /** |
| 440 | * @discriminator type |
| 441 | * @discriminatorType employee |
| 442 | */ |
| 443 | class Employee extends Person |
| 444 | { |
| 445 | public $employeeId; |
| 446 | } |
| 447 | |
| 448 | Your application code: |
| 449 | |
| 450 | .. code:: php |
| 451 | |
| 452 | $mapper = new JsonMapper(); |
| 453 | $mapper->arChildClasses['Person'] = ['Employee']; |
| 454 | $mapper->arChildClasses['Employee'] = []; |
| 455 | $person = $mapper->mapClass($json, 'Person'); |
| 456 | |
| 457 | Now, if the value of the ``type`` key in JSON is ``"person"`` then an instance of |
| 458 | a ``Person`` class is returned. However, if the ``type`` is ``"employee"`` then |
| 459 | an instance of ``Employee`` class is returned. |
| 460 | |
| 461 | Classes need to be registered in ``arChildClasses`` before being used with |
| 462 | discriminator. |
| 463 | |
| 464 | Note that there can only be one discriminator field in an object hierarchy. |
| 465 | |
| 466 | Polymorphic responses also work if the polymorphic class is embedded as a field or |
| 467 | in an array. |
| 468 | |
| 469 | To map an array of classes, use the ``mapArrayClass`` which will create the right |
| 470 | type of objects by examining the ``discriminatorType`` value. |
| 471 | |
| 472 | ============ |
| 473 | Installation |
| 474 | ============ |
| 475 | |
| 476 | Supported PHP Versions |
| 477 | ====================== |
| 478 | - PHP 5.6 |
| 479 | - PHP 7.0 |
| 480 | - PHP 7.1 |
| 481 | - PHP 7.2 |
| 482 | - PHP 7.4 |
| 483 | - PHP 8.0 |
| 484 | - PHP 8.1 |
| 485 | - PHP 8.2 |
| 486 | |
| 487 | |
| 488 | Install the Package |
| 489 | ============ |
| 490 | From Packagist__:: |
| 491 | |
| 492 | $ composer require apimatic/jsonmapper |
| 493 | |
| 494 | __ https://packagist.org/packages/apimatic/jsonmapper |
| 495 | |
| 496 | |
| 497 | ================ |
| 498 | Related software |
| 499 | ================ |
| 500 | - `Jackson's data binding`__ for Java |
| 501 | - `Johannes Schmitt Serializer`__ for PHP |
| 502 | |
| 503 | __ http://wiki.fasterxml.com/JacksonDataBinding |
| 504 | __ http://jmsyst.com/libs/serializer |
| 505 | |
| 506 | |
| 507 | ================ |
| 508 | About JsonMapper |
| 509 | ================ |
| 510 | |
| 511 | License |
| 512 | ======= |
| 513 | JsonMapper is licensed under the `OSL 3.0`__. |
| 514 | |
| 515 | __ http://opensource.org/licenses/osl-3.0 |
| 516 | |
| 517 | |
| 518 | Coding style |
| 519 | ============ |
| 520 | JsonMapper follows the `PEAR Coding Standards`__. |
| 521 | |
| 522 | __ http://pear.php.net/manual/en/standards.php |
| 523 | |
| 524 | |
| 525 | Author |
| 526 | ====== |
| 527 | `Christian Weiske`__, `Netresearch GmbH & Co KG`__ |
| 528 | |
| 529 | __ mailto:christian.weiske@netresearch.de |
| 530 | __ http://www.netresearch.de/ |
| 531 |