All Projects → goetas-webservices → Xsd2php

goetas-webservices / Xsd2php

Licence: mit
Convert XSD into PHP classes and JMS serializer definitions

Projects that are alternatives of or similar to Xsd2php

Dbcc
CAN DBC to C (and CSV, JSON and XML) compiler using the mpc parser combinator library
Stars: ✭ 142 (-25.26%)
Mutual labels:  xml, code-generation
Zek
Generate a Go struct from XML.
Stars: ✭ 451 (+137.37%)
Mutual labels:  xml, code-generation
Node Js2xmlparser
Popular Node.js module for parsing JavaScript objects into XML
Stars: ✭ 171 (-10%)
Mutual labels:  xml
Activej
ActiveJ is an alternative Java platform built from the ground up. ActiveJ redefines web, high load, and cloud programming in Java, featuring ultimate performance and scalability!
Stars: ✭ 183 (-3.68%)
Mutual labels:  code-generation
Cidlib
The CIDLib general purpose C++ development environment
Stars: ✭ 179 (-5.79%)
Mutual labels:  xml
Otpview
A custom view to enter otp/pin of different sizes used usually in cases of authentication.
Stars: ✭ 172 (-9.47%)
Mutual labels:  xml
Bancosbrasileiros
Lista de bancos brasileiros | Brazilian banks list
Stars: ✭ 178 (-6.32%)
Mutual labels:  xml
Goxml2json
XML to JSON converter written in Go (no schema, no structs)
Stars: ✭ 170 (-10.53%)
Mutual labels:  xml
Libxo
The libxo library allows an application to generate text, XML, JSON, and HTML output using a common set of function calls. The application decides at run time which output style should be produced.
Stars: ✭ 185 (-2.63%)
Mutual labels:  xml
Xdxf makedict
XDXF — a dictionary format, that stores word definitions that are free from representation
Stars: ✭ 177 (-6.84%)
Mutual labels:  xml
Xml2
Bindings to libxml2
Stars: ✭ 184 (-3.16%)
Mutual labels:  xml
Ksprefs
🚀⚡ Kotlin SharedPreferences wrapper & cryptographic preferences android library.
Stars: ✭ 176 (-7.37%)
Mutual labels:  xml
Jquery Xpath
jQuery XPath plugin (with full XPath 2.0 language support)
Stars: ✭ 173 (-8.95%)
Mutual labels:  xml
Re2dfa
Transform regular expressions into finite state machines and output Go source code. This repository has migrated to https://gitlab.com/opennota/re2dfa
Stars: ✭ 182 (-4.21%)
Mutual labels:  code-generation
Cve Check Tool
Original Automated CVE Checking Tool
Stars: ✭ 172 (-9.47%)
Mutual labels:  xml
Parse Xml
A fast, safe, compliant XML parser for Node.js and browsers.
Stars: ✭ 184 (-3.16%)
Mutual labels:  xml
Xbmc
Kodi is an award-winning free and open source home theater/media center software and entertainment hub for digital media. With its beautiful interface and powerful skinning engine, it's available for Android, BSD, Linux, macOS, iOS and Windows.
Stars: ✭ 13,175 (+6834.21%)
Mutual labels:  xml
Qxorm
QxOrm library - C++ Qt ORM (Object Relational Mapping) and ODM (Object Document Mapper) library - Official repository
Stars: ✭ 176 (-7.37%)
Mutual labels:  xml
Rawspeed
fast raw decoding library
Stars: ✭ 179 (-5.79%)
Mutual labels:  xml
Tagalong.vim
Change an HTML(ish) opening tag and take the closing one along as well
Stars: ✭ 184 (-3.16%)
Mutual labels:  xml

xsd2php

Build Status Code Coverage Scrutinizer Code Quality

Convert XSD into PHP classes.

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

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

Installation

There is one recommended way to install xsd2php via Composer:

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

Usage

With this example we will convert OTA XSD definitions into PHP classes.

Suppose that you have all XSD files in /home/my/ota, first of all we need a configuration file (as example config.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\MyApp

xsd2php:
  namespaces:
    'http://www.example.org/test/': 'TestNs\MyApp'
  destinations_php: 
    'TestNs\MyApp': soap/src
#    'TestNs\MyApp': soap\src  #  on Windows

  destinations_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 Windows
    
  aliases: # optional
    'http://www.example.org/test/':
      MyCustomXSDType:  'MyCustomMappedPHPType'
  naming_strategy: short # optional and default
  path_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

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 the http://www.example.org/test/ XML namespace mapped to TestNs\MyApp)

  • xsd2php.destinations_php (required) specifies the directory where to save the PHP classes that belongs to TestNs\MyApp PHP namespace. (in this example TestNs\MyApp classes will be saved into soap/src directory.

  • xsd2php.destinations_jms (required) specifies the directory where to save JMS Serializer metadata files that belongs to TestNs\MyApp PHP namespace. (in this example TestNs\MyApp metadata will be saved into soap/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.

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*.xsd and using the configuration available in config.yml

Serialize / Unserialize

XSD2PHP can also generate for you JMS Serializer metadata that you can use to serialize/unserialize the generated PHP class instances.

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

You have to provide a custom serializer for this type/alis.

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

<?php

use JMS\Serializer\SerializerBuilder;
use JMS\Serializer\Handler\HandlerRegistryInterface;

use GoetasWebservices\Xsd\XsdToPhpRuntime\Jms\Handler\BaseTypesHandler;
use GoetasWebservices\Xsd\XsdToPhpRuntime\Jms\Handler\XmlSchemaDateHandler;

$serializerBuilder = SerializerBuilder::create();
$serializerBuilder->addMetadataDir('metadata dir', 'TestNs');
$serializerBuilder->configureHandlers(function (HandlerRegistryInterface $handler) use ($serializerBuilder) {
    $serializerBuilder->addDefaultHandlers();
    $handler->registerSubscribingHandler(new BaseTypesHandler()); // XMLSchema List handling
    $handler->registerSubscribingHandler(new XmlSchemaDateHandler()); // 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');

Validation

<?php

use Symfony\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 with xsd:anyType or xsd:anySimpleType

If your XSD contains xsd:anyType or xsd:anySimpleType types you have to specify a handler for this.

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

# config.yml

xsd2php:
  ...
  aliases: 
    'http://www.w3.org/2001/XMLSchema':
      anyType: 'MyCustomAnyTypeHandler'
      anySimpleType: 'MyCustomAnySimpleTypeHandler'

Now you have to create a custom serialization handler:

use JMS\Serializer\XmlSerializationVisitor;
use JMS\Serializer\XmlDeserializationVisitor;

use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\VisitorInterface;
use JMS\Serializer\Context;

class MyHandler implements SubscribingHandlerInterface
{
    public static function getSubscribingMethods()
    {
        return array(
            array(
                'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
                'format' => 'xml',
                'type' => 'MyCustomAnyTypeHandler',
                'method' => 'deserializeAnyType'
            ),
            array(
                'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
                'format' => 'xml',
                'type' => 'MyCustomAnyTypeHandler',
                'method' => 'serializeAnyType'
            )
        );
    }

    public function serializeAnyType(XmlSerializationVisitor $visitor, $data, array $type, Context $context)
    {
        // serialize your object here
    }

    public function deserializeAnyType(XmlDeserializationVisitor $visitor, $data, array $type)
    {
        // deserialize your object here
    }
}

Naming Strategy

There are two types of naming strategies: short and long. The default is short, this naming strategy can however generate naming conflicts.

The long naming strategy will suffix elements with Element and types with Type.

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

An XSD for instance with a type named User, a type named UserType, a root element named User and UserElement, will only work when using the long naming strategy.

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

Note

The code in this project is provided under the MIT license. For professional support contact [email protected] or visit https://www.goetas.com

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].