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