This commit is contained in:
cutemeli
2025-12-22 10:35:30 +00:00
parent 0bfc6c8425
commit 5ce7ca2c5d
38927 changed files with 0 additions and 4594700 deletions

View File

@@ -1,55 +0,0 @@
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.
1. Definitions
"Adaptation" means a work based upon the Work, or upon the Work and other pre-existing works, such as a translation, adaptation, derivative work, arrangement of music or other alterations of a literary or artistic work, or phonogram or performance and includes cinematographic adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a work that constitutes a Collection will not be considered an Adaptation for the purpose of this License. For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an Adaptation for the purpose of this License.
"Collection" means a collection of literary or artistic works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other works or subject matter other than works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent works in themselves, which together are assembled into a collective whole. A work that constitutes a Collection will not be considered an Adaptation (as defined above) for the purposes of this License.
"Distribute" means to make available to the public the original and copies of the Work through sale or other transfer of ownership.
"Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License.
"Original Author" means, in the case of a literary or artistic work, the individual, individuals, entity or entities who created the Work or if no individual or entity can be identified, the publisher; and in addition (i) in the case of a performance the actors, singers, musicians, dancers, and other persons who act, sing, deliver, declaim, play in, interpret or otherwise perform literary or artistic works or expressions of folklore; (ii) in the case of a phonogram the producer being the person or legal entity who first fixes the sounds of a performance or other sounds; and, (iii) in the case of broadcasts, the organization that transmits the broadcast.
"Work" means the literary and/or artistic work offered under the terms of this License including without limitation any production in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as a book, pamphlet and other writing; a lecture, address, sermon or other work of the same nature; a dramatic or dramatico-musical work; a choreographic work or entertainment in dumb show; a musical composition with or without words; a cinematographic work to which are assimilated works expressed by a process analogous to cinematography; a work of drawing, painting, architecture, sculpture, engraving or lithography; a photographic work to which are assimilated works expressed by a process analogous to photography; a work of applied art; an illustration, map, plan, sketch or three-dimensional work relative to geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it is protected as a copyrightable work; or a work performed by a variety or circus performer to the extent it is not otherwise considered a literary or artistic work.
"You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
"Publicly Perform" means to perform public recitations of the Work and to communicate to the public those public recitations, by any means or process, including by wire or wireless means or public digital performances; to make available to the public Works in such a way that members of the public may access these Works from a place and at a place individually chosen by them; to perform the Work to the public by any means or process and the communication to the public of the performances of the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds or images.
"Reproduce" means to make copies of the Work by any means including without limitation by sound or visual recordings and the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital form or other electronic medium.
2. Fair Dealing Rights. Nothing in this License is intended to reduce, limit, or restrict any uses free from copyright or rights arising from limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws.
3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:
to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections; and,
to Distribute and Publicly Perform the Work including as incorporated in Collections.
The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats, but otherwise you have no rights to make Adaptations. Subject to 8(f), all rights not expressly granted by Licensor are hereby reserved, including but not limited to the rights set forth in Section 4(d).
4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:
You may Distribute or Publicly Perform the Work only under the terms of this License. You must include a copy of, or the Uniform Resource Identifier (URI) for, this License with every copy of the Work You Distribute or Publicly Perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of the recipient of the Work to exercise the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties with every copy of the Work You Distribute or Publicly Perform. When You Distribute or Publicly Perform the Work, You may not impose any effective technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this License. If You create a Collection, upon notice from any Licensor You must, to the extent practicable, remove from the Collection any credit as required by Section 4(c), as requested.
You may not exercise any of the rights granted to You in Section 3 above in any manner that is primarily intended for or directed toward commercial advantage or private monetary compensation. The exchange of the Work for other copyrighted works by means of digital file-sharing or otherwise shall not be considered to be intended for or directed toward commercial advantage or private monetary compensation, provided there is no payment of any monetary compensation in connection with the exchange of copyrighted works.
If You Distribute, or Publicly Perform the Work or Collections, You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reasonably practicable, the URI, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work. The credit required by this Section 4(c) may be implemented in any reasonable manner; provided, however, that in the case of a Collection, at a minimum such credit will appear, if a credit for all contributing authors of Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties.
For the avoidance of doubt:
Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme cannot be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License;
Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License if Your exercise of such rights is for a purpose or use which is otherwise than noncommercial as permitted under Section 4(b) and otherwise waives the right to collect royalties through any statutory or compulsory licensing scheme; and,
Voluntary License Schemes. The Licensor reserves the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this License that is for a purpose or use which is otherwise than noncommercial as permitted under Section 4(b).
Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, Distribute or Publicly Perform the Work either by itself or as part of any Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation.
5. Representations, Warranties and Disclaimer
UNLESS OTHERWISE MUTUALLY AGREED BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
7. Termination
This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Collections from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.
8. Miscellaneous
Each time You Distribute or Publicly Perform the Work or a Collection, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent.
This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.
The rights granted under, and the subject matter referenced, in this License were drafted utilizing the terminology of the Berne Convention for the Protection of Literary and Artistic Works (as amended on September 28, 1979), the Rome Convention of 1961, the WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 and the Universal Copyright Convention (as revised on July 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in which the License terms are sought to be enforced according to the corresponding provisions of the implementation of those treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes additional rights not granted under this License, such additional rights are deemed to be included in the License; this License is not intended to restrict the license of any rights under applicable law.

View File

@@ -1,41 +0,0 @@
# -*- coding: utf-8 -*-
import sys, os
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sensio.sphinx.configurationblock', 'sensio.sphinx.phpcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# This will be used when using the shorthand notation
highlight_language = 'php'
# -- Options for HTML output ---------------------------------------------------
import sphinx_rtd_theme
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# Output file base name for HTML help builder.
htmlhelp_basename = 'doc'

View File

@@ -1,106 +0,0 @@
Configuration
=============
.. note ::
If you are using Symfony2, this section is mostly irrelevant for you as the entire integration is provided by
JMSSerializerBundle; please see `its documentation <http://jmsyst.com/bundles/JMSSerializerBundle>`_. If you are
using another framework, there also might be a module, or other special integration. Please check packagist, or
whatever registry usually holds such information for your framework.
If you are using the standalone library and you want to use annotations, the annotation registry must be initialized::
Doctrine\Common\Annotations\AnnotationRegistry::registerLoader('class_exists');
Constructing a Serializer
-------------------------
This library provides a special builder object which makes constructing serializer instances a breeze in any PHP
project. In its shortest version, it's just a single line of code::
$serializer = JMS\Serializer\SerializerBuilder::create()->build();
This serializer is fully functional, but you might want to tweak it a bit for example to configure a cache directory.
Configuring a Cache Directory
-----------------------------
The serializer collects several metadata about your objects from various sources such as YML, XML, or annotations. In
order to make this process as efficient as possible, it is encourage to let the serializer cache that information. For
that, you can configure a cache directory::
$builder = new JMS\Serializer\SerializerBuilder();
$serializer =
JMS\Serializer\SerializerBuilder::create()
->setCacheDir($someWritableDir)
->setDebug($trueOrFalse)
->build();
As you can see, we also added a call to the ``setDebug`` method. In debug mode, the serializer will perform a bit more
filesystem checks to see whether the data that it has cached is still valid. These checks are useful during development
so that you do not need to manually clear cache folders, however in production they are just unnecessary overhead. The
debug setting allows you to make the behavior environment specific.
Adding Custom Handlers
----------------------
If you have created custom handlers, you can add them to the serializer easily::
$serializer =
JMS\Serializer\SerializerBuilder::create()
->addDefaultHandlers()
->configureHandlers(function(JMS\Serializer\Handler\HandlerRegistry $registry) {
$registry->registerHandler(JMS\Serializer\GraphNavigatorInterface::DIRECTION_SERIALIZATION, 'MyObject', 'json',
function($visitor, MyObject $obj, array $type) {
return $obj->getName();
}
);
})
->build();
For more complex handlers, it is advisable to extract them to dedicated classes,
see :doc:`handlers documentation <handlers>`.
Configuring Metadata Locations
------------------------------
This library supports several metadata sources. By default, it uses Doctrine annotations, but you may also store
metadata in XML, or YML files. For the latter, it is necessary to configure a metadata directory where those files
are located::
$serializer =
JMS\Serializer\SerializerBuilder::create()
->addMetadataDir($someDir)
->build();
The serializer would expect the metadata files to be named like the fully qualified class names where all ``\`` are
replaced with ``.``. So, if you class would be named ``Vendor\Package\Foo``, the metadata file would need to be located
at ``$someDir/Vendor.Package.Foo.(xml|yml)``. If not found, ``$someDir/Vendor.Package.(xml|yml)`` will be tried, then ``$someDir/Vendor.Package.(xml|yml)`` and so on. For more information, see the :doc:`reference <reference>`.
Setting a default SerializationContext factory
----------------------------------------------
To avoid to pass an instance of SerializationContext
every time you call method ``serialize()`` (or ``toArray()``),
you can set a ``SerializationContextFactory`` to the Serializer.
Example using the SerializerBuilder::
use JMS\Serializer\SerializationContext;
$serializer = JMS\Serializer\SerializerBuilder::create()
->setSerializationContextFactory(function () {
return SerializationContext::create()
->setSerializeNull(true)
;
})
->build()
;
Then, calling ``$serializer->serialize($data, 'json');`` will generate
a serialization context from your callable and use it.
.. note ::
You can also set a default DeserializationContextFactory with
``->setDeserializationContextFactory(function () { /* ... */ })``
to be used with methods ``deserialize()`` and ``fromArray()``.

View File

@@ -1,7 +0,0 @@
Cookbook
========
.. toctree ::
:glob:
cookbook/*

View File

@@ -1,47 +0,0 @@
Serializing arrays and hashes
=============================
Introduction
------------
Serializing arrays and hashes (a concept that in PHP has not explicit boundaries)
can be challenging. The serializer offers via ``@Type`` annotation different options
to configure its behavior, but if we try to serialize directly an array
(not as a property of an object), we need to use context information to determine the
array "type"
Examples
--------
In case of a JSON serialization:
.. code-block :: php
<?php
// default (let the PHP's json_encode function decide)
$serializer->serialize([1, 2]); // [1, 2]
$serializer->serialize(['a', 'b']); // ['a', 'b']
$serializer->serialize(['c' => 'd']); // {"c" => "d"}
// same as default (let the PHP's json_encode function decide)
$serializer->serialize([1, 2], SerializationContext::create()->setInitialType('array')); // [1, 2]
$serializer->serialize([1 => 2], SerializationContext::create()->setInitialType('array')); // {"1": 2}
$serializer->serialize(['a', 'b'], SerializationContext::create()->setInitialType('array')); // ['a', 'b']
$serializer->serialize(['c' => 'd'], SerializationContext::create()->setInitialType('array')); // {"c" => "d"}
// typehint as strict array, keys will be always discarded
$serializer->serialize([], SerializationContext::create()->setInitialType('array<integer>')); // []
$serializer->serialize([1, 2], SerializationContext::create()->setInitialType('array<integer>')); // [1, 2]
$serializer->serialize(['a', 'b'], SerializationContext::create()->setInitialType('array<integer>')); // ['a', 'b']
$serializer->serialize(['c' => 'd'], SerializationContext::create()->setInitialType('array<string>')); // ["d"]
// typehint as hash, keys will be always considered
$serializer->serialize([], SerializationContext::create()->setInitialType('array<integer,integer>')); // {}
$serializer->serialize([1, 2], SerializationContext::create()->setInitialType('array<integer,integer>')); // {"0" : 1, "1" : 2}
$serializer->serialize(['a', 'b'], SerializationContext::create()->setInitialType('array<integer,integer>')); // {"0" : "a", "1" : "b"}
$serializer->serialize(['c' => 'd'], SerializationContext::create()->setInitialType('array<string,string>')); // {"c" : "d"}
.. note ::
This applies only for the JSON serialization.

View File

@@ -1,408 +0,0 @@
Exclusion Strategies
====================
Introduction
------------
The serializer supports different exclusion strategies. Each strategy allows
you to define which properties of your objects should be serialized.
General Exclusion Strategies
----------------------------
If you would like to always expose, or exclude certain properties. Then, you can
do this with the annotations ``@ExclusionPolicy``, ``@Exclude``, and ``@Expose``.
The default exclusion policy is to exclude nothing. That is, all properties of the
object will be serialized. If you only want to expose a few of the properties,
then it is easier to change the exclusion policy, and only mark these few properties:
.. code-block :: php
<?php
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
/**
* The following annotations tells the serializer to skip all properties which
* have not marked with @Expose.
*
* @ExclusionPolicy("all")
*/
class MyObject
{
private $foo;
private $bar;
/**
* @Expose
*/
private $name;
}
.. note ::
A property that is excluded by ``@Exclude`` cannot be exposed anymore by any
of the following strategies, but is always hidden.
Versioning Objects
------------------
JMSSerializerBundle comes by default with a very neat feature which allows
you to add versioning support to your objects, e.g. if you want to
expose them via an API that is consumed by a third-party:
.. code-block :: php
<?php
class VersionedObject
{
/**
* @Until("1.0.x")
*/
private $name;
/**
* @Since("1.1")
* @SerializedName("name")
*/
private $name2;
}
.. note ::
``@Until``, and ``@Since`` both accept a standardized PHP version number.
If you have annotated your objects like above, you can serializing different
versions like this::
use JMS\Serializer\SerializationContext;
$serializer->serialize(new VersionObject(), 'json', SerializationContext::create()->setVersion(1));
Creating Different Views of Your Objects
----------------------------------------
Another default exclusion strategy is to create different views of your objects.
Let's say you would like to serialize your object in a different view depending
whether it is displayed in a list view or in a details view.
You can achieve that by using the ``@Groups`` annotation on your properties. Any
property without an explicit ``@Groups`` annotation will be included in a
``Default`` group, which can be used when specifying groups in the serialization
context.
.. code-block :: php
use JMS\Serializer\Annotation\Groups;
class BlogPost
{
/** @Groups({"list", "details"}) */
private $id;
/** @Groups({"list", "details"}) */
private $title;
/** @Groups({"list"}) */
private $nbComments;
/** @Groups({"details"}) */
private $comments;
private $createdAt;
}
You can then tell the serializer which groups to serialize in your controller::
use JMS\Serializer\SerializationContext;
$serializer->serialize(new BlogPost(), 'json', SerializationContext::create()->setGroups(array('list')));
//will output $id, $title and $nbComments.
$serializer->serialize(new BlogPost(), 'json', SerializationContext::create()->setGroups(array('Default', 'list')));
//will output $id, $title, $nbComments and $createdAt.
Overriding Groups of Deeper Branches of the Graph
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In some cases you want to control more precisely what is serialized because you may have the same class at different
depths of the object graph.
For example if you have a User that has a manager and friends::
use JMS\Serializer\Annotation\Groups;
class User
{
private $name;
/** @Groups({"manager_group"}) */
private $manager;
/** @Groups({"friends_group"}) */
private $friends;
public function __construct($name, User $manager = null, array $friends = null)
{
$this->name = $name;
$this->manager = $manager;
$this->friends = $friends;
}
}
And the following object graph::
$john = new User(
'John',
new User(
'John Manager',
new User('The boss'),
array(
new User('John Manager friend 1'),
)
),
array(
new User(
'John friend 1',
new User('John friend 1 manager')
),
new User(
'John friend 2',
new User('John friend 2 manager')
),
)
);
You can override groups on specific paths::
use JMS\Serializer\SerializationContext;
$context = SerializationContext::create()->setGroups(array(
'Default', // Serialize John's name
'manager_group', // Serialize John's manager
'friends_group', // Serialize John's friends
'manager' => array( // Override the groups for the manager of John
'Default', // Serialize John manager's name
'friends_group', // Serialize John manager's friends. If you do not override the groups for the friends, it will default to Default.
),
'friends' => array( // Override the groups for the friends of John
'manager_group' // Serialize John friends' managers.
'manager' => array( // Override the groups for the John friends' manager
'Default', // This would be the default if you did not override the groups of the manager property.
),
),
));
$serializer->serialize($john, 'json', $context);
This would result in the following json::
{
"name": "John",
"manager": {
"name": "John Manager",
"friends": [
{
"name": "John Manager friend 1"
}
]
},
"friends": [
{
"manager": {
"name": "John friend 1 manager"
},
},
{
"manager": {
"name": "John friend 2 manager"
},
},
]
}
Deserialization Exclusion Strategy with Groups
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can use ``@Groups`` to cut off unwanted properties while deserialization.
.. code-block:: php
use JMS\Serializer\Annotation\Groups;
class GroupsObject
{
/**
* @Groups({"foo"})
*/
public $foo;
/**
* @Groups({"foo","bar"})
*/
public $foobar;
/**
* @Groups({"bar", "Default"})
*/
public $bar;
/**
* @Type("string")
*/
public $none;
}
.. code-block:: php
$data = [
'foo' => 'foo',
'foobar' => 'foobar',
'bar' => 'bar',
'none' => 'none',
];
$context = DeserializationContext::create()->setGroups(['foo']);
$object = $serializer->fromArray($data, GroupsObject::class, $context);
// $object->foo is 'foo'
// $object->foobar is 'foobar'
// $object->bar is null
// $object->none is null
Limiting serialization depth of some properties
-----------------------------------------------
You can limit the depth of what will be serialized in a property with the
``@MaxDepth`` annotation.
This exclusion strategy is a bit different from the others, because it will
affect the serialized content of others classes than the one you apply the
annotation to.
.. code-block :: php
use JMS\Serializer\Annotation\MaxDepth;
class User
{
private $username;
/** @MaxDepth(1) */
private $friends;
/** @MaxDepth(2) */
private $posts;
}
class Post
{
private $title;
private $author;
}
In this example, serializing a user, because the max depth of the ``$friends``
property is 1, the user friends would be serialized, but not their friends;
and because the the max depth of the ``$posts`` property is 2, the posts would
be serialized, and their author would also be serialized.
You need to tell the serializer to take into account MaxDepth checks::
use JMS\Serializer\SerializationContext;
$serializer->serialize($data, 'json', SerializationContext::create()->enableMaxDepthChecks());
Dynamic exclusion strategy
--------------------------
If the previous exclusion strategies are not enough, is possible to use the ``ExpressionLanguageExclusionStrategy``
that uses the `symfony expression language`_ to
allow a more sophisticated exclusion strategies using ``@Exclude(if="expression")`` and ``@Expose(if="expression")`` methods.
This also works on class level, but is only evaluated during ``serialze`` and does not have any effect during ``deserialze``.
.. code-block :: php
<?php
/**
* @Exclude(if="true")
*/
class MyObject
{
/**
* @Exclude(if="true")
*/
private $name;
/**
* @Expose(if="true")
*/
private $name2;
}
.. note ::
``true`` is just a generic expression, you can use any expression allowed by the Symfony Expression Language
To enable this feature you have to set the Expression Evaluator when initializing the serializer.
.. code-block :: php
<?php
use JMS\Serializer\Expression\ExpressionEvaluator;
use JMS\Serializer\Expression\SerializerBuilder;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
$serializer = SerializerBuilder::create()
->setExpressionEvaluator(new ExpressionEvaluator(new ExpressionLanguage()))
->build();
.. _symfony expression language: https://github.com/symfony/expression-language
By default the serializer exposes three variables (`object`, `context` and `property_metadata` for use in an expression. This enables you to create custom exclusion strategies similar to i.e. the `GroupExclusionStrategy`_. In the below example, `someMethod` would receive all three variables.
.. code-block :: php
<?php
class MyObject
{
/**
* @Exclude(if="someMethod(object, context, property_metadata)")
*/
private $name;
/**
* @Expose(if="someMethod(object, context, property_metadata)")
*/
private $name2;
}
.. _GroupExclusionStrategy: https://github.com/schmittjoh/serializer/blob/master/src/Exclusion/GroupsExclusionStrategy.php
Using dynamic excludes on class level is also handy when you need to filter out certain objects in a collection, for example based on user permissions.
The following example shows how to exclude `Account` objects when serializing the `Person` object, if the `Account` is either expired or the user does not have the permission to view the account by calling `is_granted` with the `Account` object.
.. code-block :: php
<?php
class Person
{
/**
* @Type("array<Account>")
*/
public $accounts;
}
/**
* @Exclude(if="object.expired || !is_granted('view',object)")
*/
class Account
{
/**
* @Type("boolean")
*/
public $expired;
}

View File

@@ -1,56 +0,0 @@
Object constructor
==================
Deserialize on existing objects
-------------------------------
By default, a brand new instance of target class is created during deserialization. To deserialize into an existing object, you need to perform the following steps.
1. Create new class which implements ObjectConstructorInterface
.. code-block:: php
<?php declare(strict_types=1);
namespace Acme\ObjectConstructor;
use JMS\Serializer\Construction\ObjectConstructorInterface;
use JMS\Serializer\DeserializationContext;
use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Visitor\DeserializationVisitorInterface;
class ExistingObjectConstructor implements ObjectConstructorInterface
{
public const ATTRIBUTE = 'deserialization-constructor-target';
private $fallbackConstructor;
public function __construct(ObjectConstructorInterface $fallbackConstructor)
{
$this->fallbackConstructor = $fallbackConstructor;
}
public function construct(DeserializationVisitorInterface $visitor, ClassMetadata $metadata, $data, array $type, DeserializationContext $context): ?object
{
if ($context->hasAttribute(self::ATTRIBUTE)) {
return $context->getAttribute(self::ATTRIBUTE);
}
return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
}
}
2. Register ExistingObjectConstructor.
You should pass ExistingObjectConstructor to DeserializationGraphNavigatorFactory constructor.
3. Add special attribute to DeserializationContext
.. code-block:: php
$context = DeserializationContext::create();
$context->setAttribute('deserialization-constructor-target', $document);
$serializer->deserialize($data, get_class($document), 'json');

View File

@@ -1,16 +0,0 @@
stdClass
========
The serializer offers support for serializing ``stdClass`` objects, however the use of
``stdClass`` objects is discouraged.
The current implementation serializes all the properties of a ``stdClass`` object in
the order they appear.
There are many known limitations when dealing with ``stdClass`` objects.
More in detail, it is not possible to:
- change serialization order of properties
- apply per-property exclusion policies
- specify any extra serialization information for properties that are part of the ``stdClass`` object, as serialization name, type, xml structure and so on
- deserialize data into ``stdClass`` objects

View File

@@ -1,85 +0,0 @@
Event System
============
The serializer dispatches different events during the serialization, and
deserialization process which you can use to hook in and alter the default
behavior.
Register an Event Listener, or Subscriber
-----------------------------------------
The difference between listeners, and subscribers is that listener do not know to which events they listen
while subscribers contain that information. Thus, subscribers are easier to share, and re-use. Listeners
on the other hand, can be simple callables and do not require a dedicated class.
.. code-block :: php
class MyEventSubscriber implements JMS\Serializer\EventDispatcher\EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(
array(
'event' => 'serializer.pre_serialize',
'method' => 'onPreSerialize',
'class' => 'AppBundle\\Entity\\SpecificClass', // if no class, subscribe to every serialization
'format' => 'json', // optional format
'priority' => 0, // optional priority
),
);
}
public function onPreSerialize(JMS\Serializer\EventDispatcher\PreSerializeEvent $event)
{
// do something
}
}
$builder
->configureListeners(function(JMS\Serializer\EventDispatcher\EventDispatcher $dispatcher) {
$dispatcher->addListener('serializer.pre_serialize',
function(JMS\Serializer\EventDispatcher\PreSerializeEvent $event) {
// do something
}
);
$dispatcher->addSubscriber(new MyEventSubscriber());
})
;
Events
------
serializer.pre_serialize
~~~~~~~~~~~~~~~~~~~~~~~~
This is dispatched before a type is visited. You have access to the visitor,
data, and type. Listeners may modify the type that is being used for
serialization.
**Event Object**: ``JMS\Serializer\EventDispatcher\PreSerializeEvent``
serializer.post_serialize
~~~~~~~~~~~~~~~~~~~~~~~~~
This is dispatched right before a type is left. You can for example use this
to add additional data for an object that you normally do not save inside
objects such as links.
**Event Object**: ``JMS\Serializer\EventDispatcher\ObjectEvent``
serializer.pre_deserialize
~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded : 0.12
Event was added
This is dispatched before an object is deserialized. You can use this to
modify submitted data, or modify the type that is being used for deserialization.
**Event Object**: ``JMS\Serializer\EventDispatcher\PreDeserializeEvent``
serializer.post_deserialize
~~~~~~~~~~~~~~~~~~~~~~~~~~~
This is dispatched after a type is processed. You can use it to normalize
submitted data if you require external services for example, or also to
perform validation of the submitted data.
**Event Object**: ``JMS\Serializer\EventDispatcher\ObjectEvent``

View File

@@ -1,85 +0,0 @@
Handlers
========
Introduction
------------
Handlers allow you to change the serialization, or deserialization process
for a single type/format combination.
Handlers are simple callback which receive three arguments: the visitor,
the data, and the type.
Simple Callables
----------------
You can register simple callables on the builder object::
$builder
->configureHandlers(function(JMS\Serializer\Handler\HandlerRegistry $registry) {
$registry->registerHandler('serialization', 'MyObject', 'json',
function($visitor, MyObject $obj, array $type) {
return $obj->getName();
}
);
})
;
.. note ::
Be aware that when you call `configureHandlers` default handlers (like `DateHandler`)
won't be added and you will have to call `addDefaultHandlers` on the Builder
Subscribing Handlers
--------------------
Subscribing handlers contain the configuration themselves which makes them easier to share with other users,
and easier to set-up in general::
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\JsonSerializationVisitor;
use JMS\Serializer\JsonDeserializationVisitor;
use JMS\Serializer\Context;
class MyHandler implements SubscribingHandlerInterface
{
public static function getSubscribingMethods()
{
return [
[
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'format' => 'json',
'type' => 'DateTime',
'method' => 'serializeDateTimeToJson',
],
[
'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
'format' => 'json',
'type' => 'DateTime',
'method' => 'deserializeDateTimeToJson',
],
];
}
public function serializeDateTimeToJson(JsonSerializationVisitor $visitor, \DateTime $date, array $type, Context $context)
{
return $date->format($type['params'][0]);
}
public function deserializeDateTimeToJson(JsonDeserializationVisitor $visitor, $dateAsString, array $type, Context $context)
{
return new \DateTime($dateAsString);
}
}
Also, this type of handler is registered via the builder object::
$builder
->configureHandlers(function(JMS\Serializer\Handler\HandlerRegistry $registry) {
$registry->registerSubscribingHandler(new MyHandler());
})
;
Skippable Subscribing Handlers
-------------------------------
In case you need to be able to fall back to the default deserialization behavior instead of using your custom
handler, you can simply throw a `SkipHandlerException` from you custom handler method to do so.

View File

@@ -1,62 +0,0 @@
Serializer
==========
.. image:: logo-small.png
Introduction
------------
This library allows you to (de-)serialize data of any complexity. Currently, it supports XML and JSON.
It also provides you with a rich tool-set to adapt the output to your specific needs.
Built-in features include:
- (De-)serialize data of any complexity; circular references are handled gracefully.
- Supports many built-in PHP types (such as dates)
- Integrates with Doctrine ORM, et. al.
- Supports versioning, e.g. for APIs
- Configurable via XML, YAML, or Doctrine Annotations
Installation
------------
This library can be easily installed via composer
.. code-block :: bash
composer require jms/serializer
or just add it to your ``composer.json`` file directly.
Usage
-----
For standalone projects usage of the provided builder is encouraged::
$serializer = JMS\Serializer\SerializerBuilder::create()->build();
$jsonContent = $serializer->serialize($data, 'json');
echo $jsonContent; // or return it in a Response
Documentation
-------------
.. toctree ::
:maxdepth: 2
configuration
usage
event_system
handlers
reference
cookbook
License
-------
The code is released under the business-friendly `MIT license`_.
Documentation is subject to the `Attribution-NonCommercial-NoDerivs 3.0 Unported
license`_.
.. _MIT license: https://opensource.org/licenses/MIT
.. _Attribution-NonCommercial-NoDerivs 3.0 Unported license: http://creativecommons.org/licenses/by-nc-nd/3.0/

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

View File

@@ -1,8 +0,0 @@
Reference
=========
.. toctree ::
:glob:
:maxdepth: 1
reference/*

File diff suppressed because it is too large Load Diff

View File

@@ -1,112 +0,0 @@
XML Reference
-------------
::
<!-- MyBundle\Resources\config\serializer\Fully.Qualified.ClassName.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<serializer>
<class name="Fully\Qualified\ClassName" exclusion-policy="ALL" xml-root-name="foo-bar" exclude="true"
exclude-if="expr" accessor-order="custom" custom-accessor-order="propertyName1,propertyName2,...,propertyNameN"
access-type="public_method" discriminator-field-name="type" discriminator-disabled="false" read-only="false">
<xml-namespace prefix="atom" uri="http://www.w3.org/2005/Atom"/>
<xml-discriminator attribute="true" cdata="false" namespace=""/>
<discriminator-class value="some-value">ClassName</discriminator-class>
<discriminator-groups>
<group>foo</group>
</discriminator-groups>
<property name="some-property"
exclude="true"
expose="true"
exclude-if="expr"
expose-if="expr"
skip-when-empty="false"
type="string"
serialized-name="foo"
since-version="1.0"
until-version="1.1"
xml-attribute="true"
xml-value="true"
access-type="public_method"
accessor-getter="getSomeProperty"
accessor-setter="setSomeProperty"
inline="true"
read-only="true"
groups="foo,bar"
xml-key-value-pairs="true"
xml-attribute-map="true"
max-depth="2"
>
<!-- You can also specify the type as element which is necessary if
your type contains "<" or ">" characters. -->
<type><![CDATA[]]></type>
<xml-list inline="true" entry-name="foobar" namespace="http://www.w3.org/2005/Atom" skip-when-empty="true" />
<xml-map inline="true" key-attribute-name="foo" entry-name="bar" namespace="http://www.w3.org/2005/Atom" />
<xml-element cdata="false" namespace="http://www.w3.org/2005/Atom"/>
<groups>
<value>foo</value>
<value>bar</value>
</groups>
<union-discriminator field="foo">
<map>
<class key="a">SomeClassFQCN1</class>
<class key="b">SomeClassFQCN2</class>
<class key="c">SomeClassFQCN3</class>
</map>
</union-discriminator>
</property>
<callback-method name="foo" type="pre-serialize" />
<callback-method name="bar" type="post-serialize" />
<callback-method name="baz" type="post-deserialize" />
<virtual-property method="public_method"
name="some-property"
exclude="true"
expose="true"
skip-when-empty="false"
type="string"
serialized-name="foo"
since-version="1.0"
until-version="1.1"
xml-attribute="true"
access-type="public_method"
accessor-getter="getSomeProperty"
accessor-setter="setSomeProperty"
inline="true"
read-only="true"
groups="foo,bar"
xml-key-value-pairs="true"
xml-attribute-map="true"
max-depth="2"
>
<virtual-property expression="object.getName()"
name="some-property"
exclude="true"
expose="true"
type="string"
serialized-name="foo"
since-version="1.0"
until-version="1.1"
xml-attribute="true"
access-type="public_method"
accessor-getter="getSomeProperty"
accessor-setter="setSomeProperty"
inline="true"
read-only="true"
groups="foo,bar"
xml-key-value-pairs="true"
xml-attribute-map="true"
max-depth="2"
>
<!-- You can also specify the type as element which is necessary if
your type contains "<" or ">" characters. -->
<type><![CDATA[]]></type>
<groups>
<value>foo</value>
<value>bar</value>
</groups>
<xml-list inline="true" entry-name="foobar" namespace="http://www.w3.org/2005/Atom" skip-when-empty="true" />
<xml-map inline="true" key-attribute-name="foo" entry-name="bar" namespace="http://www.w3.org/2005/Atom" />
</virtual-property>
</class>
</serializer>

View File

@@ -1,98 +0,0 @@
YAML Reference
--------------
.. code-block :: yaml
# Vendor\MyBundle\Resources\config\serializer\Model.ClassName.yml
Vendor\MyBundle\Model\ClassName:
exclusion_policy: ALL
xml_root_name: foobar
xml_root_namespace: http://your.default.namespace
exclude: true
exclude_if: expr
read_only: false
access_type: public_method # defaults to property
accessor_order: custom
custom_accessor_order: [propertyName1, propertyName2, ..., propertyNameN]
discriminator:
field_name: type
disabled: false
map:
some-value: ClassName
groups: [foo, bar]
xml_attribute: true
xml_element:
cdata: false
namespace: http://www.w3.org/2005/Atom
virtual_properties:
getSomeProperty:
name: optional-prop-name
serialized_name: foo
type: integer
expression_prop:
name: optional-prop-name
exp: object.getName()
serialized_name: foo
type: integer
xml_namespaces:
"": http://your.default.namespace
atom: http://www.w3.org/2005/Atom
properties:
some-property:
exclude: true
expose: true
exclude_if: expr
expose_if: expr
skip_when_empty: false
access_type: public_method # defaults to property
accessor: # access_type must be set to public_method
getter: getSomeOtherProperty
setter: setSomeOtherProperty
type: string
serialized_name: foo
since_version: 1.0
until_version: 1.1
groups: [foo, bar]
xml_attribute: true
xml_value: true
inline: true
read_only: true
xml_key_value_pairs: true
xml_list:
inline: true
entry_name: foo
namespace: http://www.w3.org/2005/Atom
xml_map:
inline: true
key_attribute_name: foo
entry_name: bar
namespace: http://www.w3.org/2005/Atom
xml_attribute_map: true
xml_element:
cdata: false
namespace: http://www.w3.org/2005/Atom
max_depth: 2
union_discriminator:
filed: foo
map:
a: SomeClassFQCN1
b: SomeClassFQCN2
c: SomeClassFQCN3
callback_methods:
pre_serialize: [foo, bar]
post_serialize: [foo, bar]
post_deserialize: [foo, bar]
Constants
---------
In some cases, it may be helpful to reference constants in your YAML files.
You can do this by prefixing the constant with the special `!php/const` syntax.
.. code-block :: yaml
Vendor\MyBundle\Model\ClassName:
properties:
some-property:
serialized_name: !php/const Vendor\MyBundle\Model\ClassName::SOME_CONSTANT

View File

@@ -1,6 +0,0 @@
Sphinx==1.8.5
git+https://github.com/fabpot/sphinx-php.git
sphinx_rtd_theme
Jinja2<3.0
MarkupSafe<2.1
alabaster<0.7.14

View File

@@ -1,36 +0,0 @@
Usage
=====
Serializing Objects
-------------------
Most common usage is probably to serialize objects. This can be achieved
very easily:
.. configuration-block ::
.. code-block :: php
<?php
$serializer = JMS\Serializer\SerializerBuilder::create()->build();
$serializer->serialize($object, 'json');
$serializer->serialize($object, 'xml');
.. code-block :: jinja
{{ object | serialize }} {# uses JSON #}
{{ object | serialize('json') }}
{{ object | serialize('xml') }}
Deserializing Objects
---------------------
You can also deserialize objects from their XML, or JSON representation. For
example, when accepting data via an API.
.. code-block :: php
<?php
$serializer = JMS\Serializer\SerializerBuilder::create()->build();
$object = $serializer->deserialize($jsonData, \MyNamespace\MyObject::class, 'json');