/**
  *
  * @param mixed $xml
  * @return \Zend\Code\Generator\ClassGenerator[]
  */
 protected function getPhpClasses($xml, array $types = array())
 {
     $creator = new PhpConverter(new ShortNamingStrategy());
     $creator->addNamespace('', 'Example');
     foreach ($types as $typeData) {
         list($ns, $name, $type) = $typeData;
         $creator->addAliasMapType($ns, $name, $type);
     }
     $generator = new ClassGenerator();
     $reader = new SchemaReader();
     if (!is_array($xml)) {
         $xml = ['schema.xsd' => $xml];
     }
     $schemas = [];
     foreach ($xml as $name => $str) {
         $schemas[] = $reader->readString($str, $name);
     }
     $items = $creator->convert($schemas);
     $classes = array();
     foreach ($items as $k => $item) {
         $codegen = new \Zend\Code\Generator\ClassGenerator();
         if ($generator->generate($codegen, $item)) {
             $classes[$k] = $codegen;
         }
     }
     return $classes;
 }
Пример #2
0
 public function testMissingClass()
 {
     $expectedItems = array('Epa\\Schema\\AdditionalIdentifier', 'Epa\\Schema\\AdditionalIdentifierType', 'Epa\\Schema\\AdditionalIdentifierTypes', 'Epa\\Schema\\AdditionalIdentifiers');
     $expectedItems = array_combine($expectedItems, $expectedItems);
     $reader = new SchemaReader();
     $schema = $reader->readFile(__DIR__ . '/data.xsd');
     $yamlConv = new YamlConverter(new ShortNamingStrategy());
     $yamlConv->addNamespace('', 'Epa\\Schema');
     $yamlItems = $yamlConv->convert([$schema]);
     $this->assertCount(count($expectedItems), $yamlItems);
     $this->assertEmpty(array_diff_key($expectedItems, $yamlItems));
     $phpConv = new PhpConverter(new ShortNamingStrategy());
     $phpConv->addNamespace('', 'Epa\\Schema');
     $phpClasses = $phpConv->convert([$schema]);
     $this->assertCount(count($expectedItems), $phpClasses);
     $this->assertEmpty(array_diff_key($expectedItems, $phpClasses));
     $yamlClass = $yamlItems['Epa\\Schema\\AdditionalIdentifier']['Epa\\Schema\\AdditionalIdentifier'];
     $yamlProperty = $yamlClass['properties']['additionalIdentifierType'];
     /** @var PHPClass $phpClass */
     $phpClass = $phpClasses['Epa\\Schema\\AdditionalIdentifier'];
     /** @var PHPProperty $phpProperty */
     $phpProperty = $phpClass->getProperty('additionalIdentifierType');
     /** @var PHPClass $phpType */
     $phpType = $phpProperty->getType();
     $this->assertSame($yamlProperty['type'], $phpType->getFullName());
 }
Пример #3
0
 public function testNaming()
 {
     $reader = new SchemaReader();
     $schema = $reader->readFile(__DIR__ . '/data.xsd');
     $phpConv = new PhpConverter(new ShortNamingStrategy());
     $phpConv->addNamespace('http://www.example.com/', 'Epa');
     $phpClasses = $phpConv->convert([$schema]);
     $this->assertEquals('convertToReseller', $phpClasses['Epa\\Two']->getProperty('convertToReseller')->getType()->getArg()->getName());
 }
Пример #4
0
 public function testNaming()
 {
     $reader = new SchemaReader();
     $schema = $reader->readFile(__DIR__ . '/data.xsd');
     $phpConv = new PhpConverter(new ShortNamingStrategy());
     $phpConv->addNamespace('http://www.example.com/', 'Epa');
     $phpClasses = $phpConv->convert([$schema]);
     $this->assertArrayHasKey('Epa\\ABType', $phpClasses);
     $class = $phpClasses['Epa\\ABType'];
     $this->assertArrayHasKey('cDe', $class->getProperties());
     $this->assertArrayHasKey('fGh', $class->getProperties());
 }
Пример #5
0
 public function testMissingClass()
 {
     $expectedItems = array('Epa\\Job', 'Epa\\Item', 'Epa\\Item\\PriceAType');
     $reader = new SchemaReader();
     $schema = $reader->readFile(__DIR__ . '/data.xsd');
     $yamlConv = new YamlConverter(new ShortNamingStrategy());
     $yamlConv->addNamespace('http://www.trogon.si/Schemas/2010/JobXML/2.0', 'Epa');
     $yamlItems = $yamlConv->convert([$schema]);
     $yamlItems = array_keys($yamlItems);
     $this->assertEmpty(array_diff($expectedItems, $yamlItems));
     $phpConv = new PhpConverter(new ShortNamingStrategy());
     $phpConv->addNamespace('http://www.trogon.si/Schemas/2010/JobXML/2.0', 'Epa');
     $phpClasses = $phpConv->convert([$schema]);
     $phpClasses = array_keys($phpClasses);
     $this->assertEmpty(array_diff_key($expectedItems, $phpClasses));
 }
Пример #6
0
 public static function setUpBeforeClass()
 {
     $tmp = sys_get_temp_dir();
     if (is_writable("/dev/shm")) {
         $tmp = "/dev/shm";
     }
     self::$phpDir = "{$tmp}/OTASerializationTestPHP";
     self::$jmsDir = "{$tmp}/OTASerializationTestJMS";
     self::$loader = new ClassLoader();
     self::$loader->addPsr4(self::$namespace . "\\", self::$phpDir);
     self::$loader->register();
     if (is_dir(self::$phpDir)) {
         self::delTree(self::$phpDir);
     }
     if (is_dir(self::$jmsDir)) {
         self::delTree(self::$jmsDir);
     }
     if (!is_dir(self::$phpDir)) {
         mkdir(self::$phpDir);
     }
     if (!is_dir(self::$jmsDir)) {
         mkdir(self::$jmsDir);
     }
     $reader = new SchemaReader();
     $schemas = array();
     foreach (self::getXmlFiles() as $d) {
         if (!isset($schemas[$d[1]])) {
             $schemas[$d[1]] = $reader->readFile($d[1]);
         }
     }
     self::generateJMSFiles($schemas);
     self::generatePHPFiles($schemas);
     $serializerBuiler = \JMS\Serializer\SerializerBuilder::create();
     $serializerBuiler->configureHandlers(function (HandlerRegistryInterface $h) use($serializerBuiler) {
         $serializerBuiler->addDefaultHandlers();
         $h->registerSubscribingHandler(new BaseTypesHandler());
         $h->registerSubscribingHandler(new XmlSchemaDateHandler());
         $h->registerSubscribingHandler(new OTASchemaDateHandler());
     });
     $serializerBuiler->addMetadataDir(self::$jmsDir, self::$namespace);
     self::$serializer = $serializerBuiler->build();
 }
Пример #7
0
 /**
  *
  * @param mixed $xml
  * @return \Zend\Code\Generator\ClassGenerator[]
  */
 protected function getClasses($xml)
 {
     $phpcreator = new PhpConverter(new ShortNamingStrategy());
     $phpcreator->addNamespace('http://www.example.com', 'Example');
     $generator = new ClassGenerator();
     $reader = new SchemaReader();
     if (!is_array($xml)) {
         $xml = ['schema.xsd' => $xml];
     }
     $schemas = [];
     foreach ($xml as $name => $str) {
         $schemas[] = $reader->readString($str, $name);
     }
     $items = $phpcreator->convert($schemas);
     $classes = array();
     foreach ($items as $k => $item) {
         $codegen = new \Zend\Code\Generator\ClassGenerator();
         if ($generator->generate($codegen, $item)) {
             $classes[$k] = $codegen;
         }
     }
     return $classes;
 }
Пример #8
0
 /**
  * @group long
  */
 public function testOpcGeneration()
 {
     $nss = array("http://schemas.openxmlformats.org/package/2006/metadata/core-properties" => "Iag/ECMA376/Package/Model/CoreProperties/", "http://purl.org/dc/elements/1.1/" => "Iag/ECMA376/Package/Model/CoreProperties/DcElements/", "http://purl.org/dc/terms/" => "Iag/ECMA376/Package/Model/CoreProperties/DcTerms/", "http://purl.org/dc/dcmitype/" => "Iag/ECMA376/Package/Model/CoreProperties/DcMiType/");
     $reader = new SchemaReader();
     $reader->addKnownSchemaLocation('http://dublincore.org/schemas/xmls/qdc/2003/04/02/dc.xsd', __DIR__ . '/opc/dc.xsd');
     $reader->addKnownSchemaLocation('http://dublincore.org/schemas/xmls/qdc/2003/04/02/dcterms.xsd', __DIR__ . '/opc/dcterms.xsd');
     $reader->addKnownSchemaLocation('http://dublincore.org/schemas/xmls/qdc/2003/04/02/dcterms.xsd', __DIR__ . '/opc/dcterms.xsd');
     $reader->addKnownSchemaLocation('http://dublincore.org/schemas/xmls/qdc/2003/04/02/dcmitype.xsd', __DIR__ . '/opc/dcmitype.xsd');
     $schema = $reader->readFile(__DIR__ . '/opc/opc-coreProperties.xsd');
     $yamlConv = new YamlConverter(new ShortNamingStrategy());
     $phpConv = new PhpConverter(new ShortNamingStrategy());
     foreach ($nss as $ns => $php) {
         $yamlConv->addNamespace($ns, $php);
         $phpConv->addNamespace($ns, $php);
     }
     $yamlItems = $yamlConv->convert([$schema]);
     $phpClasses = $phpConv->convert([$schema]);
     $this->assertEquals(count($phpClasses), count($yamlItems));
 }
Пример #9
0
 /**
  * Execute the code generation
  */
 public function generate()
 {
     /*
      * PROXY CONFIGURATION
      */
     $proxy = current(array_filter(array(getenv('HTTP_PROXY'), getenv('http_proxy')), 'strlen'));
     if ($proxy) {
         $parsedWsdlPath = Url::createFromUrl($this->config->getWsdlDocumentPath());
         // if not fetching the wsdl file from filesystem and a proxy has been set
         if ($parsedWsdlPath->getScheme()->get() !== 'file') {
             $proxy = Url::createFromUrl($proxy);
             libxml_set_streams_context(stream_context_get_default(array($proxy->getScheme()->get() => array('proxy' => 'tcp://' . $proxy->getAuthority() . $proxy->getRelativeUrl(), 'request_fulluri' => true))));
         }
     }
     unset($proxy);
     /*
      * LOAD THE WSDL DOCUMENT
      */
     $wsdlDocument = SimpleXMLElement::loadFile($this->config->getWsdlDocumentPath());
     $wsdlDocument->registerXPathNamespace('wsdl', static::WSDL_NS);
     $schemaReader = new SchemaReader();
     /* @var \Goetas\XML\XSDReader\Schema\Schema[] $schemas */
     $schemas = array();
     /* @var \Goetas\XML\XSDReader\Schema\Type\Type[] $types */
     $types = array();
     /*
      * LOAD THE XML SCHEMAS
      */
     // read the schemas included in the wsdl document
     foreach ($wsdlDocument->xpath('/wsdl:definitions/wsdl:types/xsd:schema') as $schemaNode) {
         $schemas[] = $schemaReader->readNode(dom_import_simplexml($schemaNode));
     }
     // exclude the schemas having the following namespaces
     $unusedSchemaNamespaces = array(SchemaReader::XML_NS, SchemaReader::XSD_NS);
     // recursively read all the schema chain
     $processedSchemas = array();
     while (!empty($schemas)) {
         /* @var \Goetas\XML\XSDReader\Schema\Schema $currentSchema */
         $currentSchema = array_shift($schemas);
         if (!in_array($currentSchema, $processedSchemas) and !in_array($currentSchema->getTargetNamespace(), $unusedSchemaNamespaces)) {
             $processedSchemas[] = $currentSchema;
             $schemas = array_merge($schemas, $currentSchema->getSchemas());
         }
     }
     $schemas = $processedSchemas;
     // cleanup
     unset($currentSchema);
     unset($processedSchemas);
     unset($unusedSchemaNamespaces);
     unset($schemaNode);
     unset($schemaReader);
     /*
      * LOAD THE DEFINED TYPES
      */
     // get the complete list of defined types
     foreach ($schemas as $schema) {
         $types = array_merge($types, $schema->getTypes());
     }
     /*
      * LOAD THE SERVICES
      */
     $services = $wsdlDocument->xpath('/wsdl:definitions/wsdl:portType');
     /*
      * CODE GENERATION
      */
     $classFactory = new ClassFactory($this->config, $schemas, $types);
     foreach ($types as $type) {
         if ($type instanceof SimpleType) {
             // build the inheritance chain of the current SimpleType
             /* @var \Goetas\XML\XSDReader\Schema\Type\SimpleType[] $inheritanceChain */
             $inheritanceChain = array($type->getRestriction());
             // loop through the type inheritance chain untill the base type
             while (end($inheritanceChain) !== null) {
                 $inheritanceChain[] = end($inheritanceChain)->getBase()->getParent();
             }
             // remove the null value
             array_pop($inheritanceChain);
             // remove the 'anySimpleType'
             array_pop($inheritanceChain);
             // now the last element of the chain is the base simple type
             // enums are built only of string enumerations
             if (end($inheritanceChain)->getBase()->getName() === 'string' and array_key_exists('enumeration', $type->getRestriction()->getChecks())) {
                 $className = $classFactory->createEnum($type);
                 $this->eventDispatcher->dispatch(Event::ENUM_CREATE, new Event($className));
             }
         } elseif ($type instanceof ComplexType) {
             $className = $classFactory->createDTO($type);
             $this->eventDispatcher->dispatch(Event::DTO_CREATE, new Event($className));
         }
     }
     foreach ($services as $service) {
         $className = $classFactory->createService($service);
         $this->eventDispatcher->dispatch(Event::SERVICE_CREATE, new Event($className));
     }
     $className = $classFactory->createClassmap();
     $this->eventDispatcher->dispatch(Event::CLASSMAP_CREATE, new Event($className));
     /*
      * GENERATED CODE FIX
      */
     // create the coding standards fixer
     $fixer = new Fixer();
     $config = new FixerConfig();
     $config->setDir($this->config->getOutputPath());
     // register all the existing fixers
     $fixer->registerBuiltInFixers();
     $config->fixers(array_filter($fixer->getFixers(), function (FixerInterface $fixer) {
         return $fixer->getLevel() === FixerInterface::PSR2_LEVEL;
     }));
     // fix the generated code
     $fixer->fix($config);
 }
Пример #10
0
 /**
  *
  * @see Console\Command\Command
  */
 protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
 {
     $src = $input->getArgument('src');
     $nsMap = $input->getOption('ns-map');
     if (!$nsMap) {
         throw new \RuntimeException(__CLASS__ . " requires at least one ns-map.");
     }
     $nsTarget = $input->getOption('ns-dest');
     if (!$nsTarget) {
         throw new \RuntimeException(__CLASS__ . " requires at least one ns-target.");
     }
     if ($input->getOption('naming-strategy') == 'short') {
         $naming = new ShortNamingStrategy();
     } elseif ($input->getOption('naming-strategy') == 'long') {
         $naming = new LongNamingStrategy();
     } else {
         throw new \InvalidArgumentException("Unsupported naming strategy");
     }
     $converter = $this->getConverterter($naming);
     $nsMapKeyed = array();
     $output->writeln("Namespaces:");
     foreach ($nsMap as $val) {
         if (substr_count($val, ';') !== 1) {
             throw new Exception("Invalid syntax for --ns-map");
         }
         list($xmlNs, $phpNs) = explode(";", $val, 2);
         $nsMapKeyed[$xmlNs] = $phpNs;
         $converter->addNamespace($xmlNs, trim(strtr($phpNs, "./", "\\\\"), "\\"));
         $output->writeln("\tXML namepsace: <comment>{$xmlNs}</comment> => PHP namepsace: <info>{$phpNs}</info>");
     }
     $targets = array();
     $output->writeln("Target directories:");
     foreach ($nsTarget as $val) {
         if (substr_count($val, ';') !== 1) {
             throw new Exception("Invalid syntax for --ns-dest");
         }
         list($phpNs, $dir) = explode(";", $val, 2);
         $phpNs = strtr($phpNs, "./", "\\\\");
         $targets[$phpNs] = $dir;
         $output->writeln("\tPHP namepsace: <comment>" . strtr($phpNs, "\\", "/") . "</comment> => Destination directory: <info>{$dir}</info>");
     }
     $arrayMap = $input->getOption('alias-map');
     if ($arrayMap) {
         $output->writeln("Aliases:");
         foreach ($arrayMap as $val) {
             if (substr_count($val, ';') !== 2) {
                 throw new Exception("Invalid syntax for --alias-map");
             }
             list($xmlNs, $name, $type) = explode(";", $val, 3);
             $converter->addAliasMapType($xmlNs, $name, $type);
             $output->writeln("\tXML Type: <comment>{$xmlNs}</comment>#<comment>{$name}</comment>  => PHP Class: <info>{$type}</info> ");
         }
     }
     $reader = new SchemaReader();
     $schemas = array();
     foreach ($src as $file) {
         $output->writeln("Reading <comment>{$file}</comment>");
         $xml = new \DOMDocument('1.0', 'UTF-8');
         if (!$xml->load($file)) {
             throw new \Exception("Can't load the schema '{$file}'");
         }
         if (!isset($nsMapKeyed[$xml->documentElement->getAttribute("targetNamespace")])) {
             $output->writeln("\tSkipping <comment>" . $xml->documentElement->getAttribute("targetNamespace") . "</comment>, can't find a PHP-equivalent namespace. Use --ns-map option?");
             continue;
         }
         $schema = $reader->readFile($file);
         $schemas[spl_object_hash($schema)] = $schema;
     }
     $this->convert($converter, $schemas, $targets, $output);
     return 0;
 }
Пример #11
0
 protected function getClasses($xml)
 {
     $schema = $this->reader->readString($xml);
     return $this->converter->convert(array($schema));
 }