Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Convert XSD into PHP classes and JMS serializer definitions

License

NotificationsYou must be signed in to change notification settings

goetas-webservices/xsd2php

Repository files navigation

On 24 February 2022, RussianPresident Vladimir Putin ordered an invasion of Ukraine by Russian Armed Forces.

Your support is urgently needed.

THANK YOU!


xsd2php

Build StatusCode CoverageScrutinizer Code Quality

Convert XSD into PHP classes.

Withgoetas-webservices/xsd2php you can convert any XSD/WSDL definition into PHP classes.

XSD2PHP can also generateJMS Serializer compatible metadata that can be used to serialize/unserialize the object instances.

Installation

There is one recommended way to install xsd2php viaComposer:

  • adding the dependency to yourcomposer.json file:
"require":{..      "goetas-webservices/xsd2php-runtime":"^0.2.2",..},"require-dev":{..      "goetas-webservices/xsd2php":"^0.3",..},

Usage

With this example we will convertOTA XSD definitionsinto PHP classes.

Suppose that you have all XSD files in/home/my/ota, first of all we need a configuration file(as exampleconfig.yml) that will keep all the namespace and directory mappings information.

# config.yml# Linux Users: PHP Namespaces use back slash \ rather than a forward slash /# So for destinations_php, the namespace would be TestNs\MyAppxsd2php:namespaces:'http://www.example.org/test/':'TestNs\MyApp'destinations_php:'TestNs\MyApp':soap/src#    'TestNs\MyApp': soap\src  #  on Windowsdestinations_jms:'TestNs\MyApp':soap/metadata#    'TestNs\MyApp': soap\metadata  #  on Windows#  Uncomment this section if you want to have also symfony/validator metadata to be generated from XSD#  destinations_validation:#    'TestNs\MyApp': soap/validation#    'TestNs\MyApp': soap\validation  #  on Windowsaliases:# optional'http://www.example.org/test/':MyCustomXSDType:'MyCustomMappedPHPType'naming_strategy:short# optional and defaultpath_generator:psr4# optional and default#  known_locations: # optional#    "http://www.example.org/test/somefile.xsd": somefile.xsd#  known_namespace_locations: # optional#    "urn:veloconnect:catalog-1.1": xsd/catalog-1.1.xsd# configs_jms:  #optional#   xml_cdata: false # Disables CDATA

Here is an explanation on the meaning of each parameter:

  • xsd2php.namespaces (required) defines the mapping between XML namespaces and PHP namespaces.(in the example we have thehttp://www.example.org/test/ XML namespace mapped toTestNs\MyApp)

  • xsd2php.destinations_php (required) specifies the directory where to save the PHP classes that belongs toTestNs\MyApp PHP namespace. (in this exampleTestNs\MyApp classes will be saved intosoap/src directory.

  • xsd2php.destinations_jms (required) specifies the directory where to save JMS Serializer metadata filesthat belongs toTestNs\MyApp PHP namespace.(in this exampleTestNs\MyApp metadata will be saved intosoap/metadata directory.

  • xsd2php.aliases (optional) specifies some mappings that are handled by custom JMS serializer handlers.Allows to specify to do not generate metadata for some XML types, and assign them directly a PHP class.For that PHP class is necessary to create a custom JMS serialize/deserialize handler.

  • xsd2php.naming_strategy (optional) specifies the naming strategy to use when converting XML names PHP classes.

  • xsd2php.path_generator (optional) specifies the strategy to use for path generation and file saving

  • xsd2php.known_locations (optional) override remote location with a local file.

  • xsd2php.known_namespace_locations (optional) Specify schema location by namespace.This can be used to read schemas which import namespaces but do not specify schemaLocation attributes.

  • xsd2php.configs_jms.xml_cdata (optional) Specify if CDATA should be used or not in serialization.

Generate PHP classes and JMS metadata info

vendor/bin/xsd2php convert config.yml /home/my/ota/OTA_Air*.xsd

This command will generate PHP classes and JMS metadata files for all the XSD files matching/home/my/ota/OTA_Air*.xsdand using the configuration available inconfig.yml

Serialize / Unserialize

XSD2PHP can also generate for youJMS Serializer metadatathat you can use to serialize/unserialize the generated PHP class instances.

The parameteraliases in the configuration file, will instruct XSD2PHP to not generate any metadata information orPHP class for the{http://www.example.org/test/}MyCustomXSDType type.All reference to this type are replaced with theMyCustomMappedPHPType name.

You have to provide acustom serializerfor this type/alis.

Here is an example on how to configure JMS serializer to handle custom types

<?phpuseJMS\Serializer\SerializerBuilder;useJMS\Serializer\Handler\HandlerRegistryInterface;useGoetasWebservices\Xsd\XsdToPhpRuntime\Jms\Handler\BaseTypesHandler;useGoetasWebservices\Xsd\XsdToPhpRuntime\Jms\Handler\XmlSchemaDateHandler;$serializerBuilder = SerializerBuilder::create();$serializerBuilder->addMetadataDir('metadata dir','TestNs');$serializerBuilder->configureHandlers(function (HandlerRegistryInterface$handler)use ($serializerBuilder) {$serializerBuilder->addDefaultHandlers();$handler->registerSubscribingHandler(newBaseTypesHandler());// XMLSchema List handling$handler->registerSubscribingHandler(newXmlSchemaDateHandler());// XMLSchema date handling// $handler->registerSubscribingHandler(new YourhandlerHere());});$serializer =$serializerBuilder->build();// deserialize the XML into Demo\MyObject object$object =$serializer->deserialize('<some xml/>','TestNs\MyObject','xml');// some code ....// serialize the Demo\MyObject back into XML$newXml =$serializer->serialize($object,'xml');

To disable the CDATA, configure JMS as so:

xsd2php:configs_jms:xml_cdata:false

Validation

<?phpuseSymfony\Component\Validator\Validation;// get the validator$builder = Validation::createValidatorBuilder();foreach (glob('soap/validation/*.yml')as$file) {$builder->addYamlMapping($file);}$validator =$builder->getValidator();// validate $object$violations =$validator->validate($object,null, ['xsd_rules']);

Dealing withxsd:anyType orxsd:anySimpleType

If your XSD containsxsd:anyType orxsd:anySimpleType types you have to specify a handler for this.

When you generate the JMS metadata you have to specify a custom handler:

# config.ymlxsd2php:...aliases:'http://www.w3.org/2001/XMLSchema':anyType:'MyCustomAnyTypeHandler'anySimpleType:'MyCustomAnySimpleTypeHandler'

Now you have to create a custom serialization handler:

useJMS\Serializer\XmlSerializationVisitor;useJMS\Serializer\XmlDeserializationVisitor;useJMS\Serializer\Handler\SubscribingHandlerInterface;useJMS\Serializer\GraphNavigator;useJMS\Serializer\VisitorInterface;useJMS\Serializer\Context;class MyHandlerimplements SubscribingHandlerInterface{publicstaticfunctiongetSubscribingMethods()    {returnarray(array('direction' => GraphNavigator::DIRECTION_DESERIALIZATION,'format' =>'xml','type' =>'MyCustomAnyTypeHandler','method' =>'deserializeAnyType'            ),array('direction' => GraphNavigator::DIRECTION_SERIALIZATION,'format' =>'xml','type' =>'MyCustomAnyTypeHandler','method' =>'serializeAnyType'            )        );    }publicfunctionserializeAnyType(XmlSerializationVisitor$visitor,$data,array$type,Context$context)    {// serialize your object here    }publicfunctiondeserializeAnyType(XmlDeserializationVisitor$visitor,$data,array$type)    {// deserialize your object here    }}

Naming Strategy

There are two types of naming strategies:short andlong. The default isshort, this naming strategy can however generate naming conflicts.

Thelong naming strategy will suffix elements withElement and types withType.

  • MyNamespace\User will becomeMyNamespace\UserElement
  • MyNamespace\UserType will becomeMyNamespace\UserTypeType

An XSD for instance with a type namedUser, a type namedUserType, a root element namedUser andUserElement, will only work when using thelong naming strategy.

  • If you don't have naming conflicts and you want to have short and descriptive class names, use theshort option.
  • If you have naming conflicts use thelong option.
  • If you want to be safe, use thelong option.

Note

The code in this project is provided under theMIT license.For professional supportcontactgoetas@gmail.comor visithttps://www.goetas.com


[8]ページ先頭

©2009-2025 Movatter.jp