diff --git a/composer.json b/composer.json index 73d13bf..1f8795b 100644 --- a/composer.json +++ b/composer.json @@ -1,13 +1,13 @@ { - "name":"goetas/xsd2php", - "description":"Convert XSD (XML Schema) definitions into PHP classes", - "type":"library", - "authors":[ + "name": "goetas/xsd2php", + "description": "Convert XSD (XML Schema) definitions into PHP classes", + "type": "library", + "authors": [ { - "name":"Asmir Mustafic" + "name": "Asmir Mustafic" } ], - "keywords":[ + "keywords": [ "converter", "xml", "xsd", @@ -15,38 +15,38 @@ "jms", "serializer" ], - "license":"LGPL", - "require":{ - "php":"~5.4", - "symfony/console":"~2.1", - "symfony/yaml":"~2.1", - "goetas/xsd-reader":"~2.0@dev", - "doctrine/inflector":"~1.0", - "zendframework/zend-code":"~2.2" + "license": "LGPL", + "require": { + "php": "~5.4", + "symfony/console": "~2.1", + "symfony/yaml": "~2.1", + "goetas/xsd-reader": "~2.0@dev", + "doctrine/inflector": "~1.0", + "zendframework/zend-code": "~2.2" }, - "require-dev":{ - "phpunit/phpunit":"~4.0", - "jms/serializer":"xsd2php-dev as 0.18.0" + "require-dev": { + "phpunit/phpunit": "~4.0", + "jms/serializer": "xsd2php-dev as 0.18.0" }, - "repositories":[ + "repositories": [ { - "type":"vcs", - "url":"https://github.com/goetas/serializer.git" + "type": "vcs", + "url": "https://github.com/goetas/serializer.git" } ], - "autoload":{ - "psr-4":{ + "autoload": { + "psr-4": { "Goetas\\Xsd\\XsdToPhp\\": "lib/" } }, "autoload-dev": { "psr-4": { - "Goetas\\Xsd\\XsdToPhp\\Tests\\":"tests/" + "Goetas\\Xsd\\XsdToPhp\\Tests\\": "tests/" } }, - "extra":{ - "branch-alias":{ - "dev-master":"2.0-dev" + "extra": { + "branch-alias": { + "dev-master": "2.0-dev" } }, "bin": [ diff --git a/lib/AbstractConverter.php b/lib/AbstractConverter.php index ee7a0cd..b8d7220 100644 --- a/lib/AbstractConverter.php +++ b/lib/AbstractConverter.php @@ -1,11 +1,11 @@ '', + 'http://www.w3.org/2001/XMLSchema' => '', 'http://www.w3.org/XML/1998/namespace' => '' ); @@ -47,15 +47,18 @@ public function addAliasMap($ns, $name, callable $handler) public function addAliasMapType($ns, $name, $type) { - $this->addAliasMap($ns, $name, function () use($type) - { - return $type; - }); + $this->addAliasMap( + $ns, + $name, + function () use ($type) { + return $type; + } + ); } public function getTypeAlias($type, Schema $schemapos = null) { - $schema = $schemapos ? : $type->getSchema(); + $schema = $schemapos ?: $type->getSchema(); $cid = $schema->getTargetNamespace() . "|" . $type->getName(); if (isset($this->aliasCache[$cid])) { @@ -70,152 +73,260 @@ public function __construct(NamingStrategy $namingStrategy) { $this->namingStrategy = $namingStrategy; - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "gYearMonth", function (Type $type) - { - return "integer"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "gMonthDay", function (Type $type) - { - return "integer"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "gMonth", function (Type $type) - { - return "integer"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "gYear", function (Type $type) - { - return "integer"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "NMTOKEN", function (Type $type) - { - return "string"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "NMTOKENS", function (Type $type) - { - return "string"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "QName", function (Type $type) - { - return "string"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "NCName", function (Type $type) - { - return "string"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "decimal", function (Type $type) - { - return "float"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "float", function (Type $type) - { - return "float"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "double", function (Type $type) - { - return "float"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "string", function (Type $type) - { - return "string"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "normalizedString", function (Type $type) - { - return "string"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "integer", function (Type $type) - { - return "integer"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "int", function (Type $type) - { - return "integer"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "unsignedInt", function (Type $type) - { - return "integer"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "negativeInteger", function (Type $type) - { - return "integer"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "positiveInteger", function (Type $type) - { - return "integer"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "nonNegativeInteger", function (Type $type) - { - return "integer"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "nonPositiveInteger", function (Type $type) - { - return "integer"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "long", function (Type $type) - { - return "integer"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "unsignedLong", function (Type $type) - { - return "integer"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "short", function (Type $type) - { - return "integer"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "boolean", function (Type $type) - { - return "boolean"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "nonNegativeInteger", function (Type $type) - { - return "integer"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "positiveInteger", function (Type $type) - { - return "integer"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "language", function (Type $type) - { - return "string"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "token", function (Type $type) - { - return "string"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "anyURI", function (Type $type) - { - return "string"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "byte", function (Type $type) - { - return "string"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "duration", function (Type $type) - { - return "DateInterval"; - }); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "gYearMonth", + function (Type $type) { + return "integer"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "gMonthDay", + function (Type $type) { + return "integer"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "gMonth", + function (Type $type) { + return "integer"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "gYear", + function (Type $type) { + return "integer"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "NMTOKEN", + function (Type $type) { + return "string"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "NMTOKENS", + function (Type $type) { + return "string"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "QName", + function (Type $type) { + return "string"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "NCName", + function (Type $type) { + return "string"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "decimal", + function (Type $type) { + return "float"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "float", + function (Type $type) { + return "float"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "double", + function (Type $type) { + return "float"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "string", + function (Type $type) { + return "string"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "normalizedString", + function (Type $type) { + return "string"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "integer", + function (Type $type) { + return "integer"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "int", + function (Type $type) { + return "integer"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "unsignedInt", + function (Type $type) { + return "integer"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "negativeInteger", + function (Type $type) { + return "integer"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "positiveInteger", + function (Type $type) { + return "integer"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "nonNegativeInteger", + function (Type $type) { + return "integer"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "nonPositiveInteger", + function (Type $type) { + return "integer"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "long", + function (Type $type) { + return "integer"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "unsignedLong", + function (Type $type) { + return "integer"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "short", + function (Type $type) { + return "integer"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "boolean", + function (Type $type) { + return "boolean"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "nonNegativeInteger", + function (Type $type) { + return "integer"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "positiveInteger", + function (Type $type) { + return "integer"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "language", + function (Type $type) { + return "string"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "token", + function (Type $type) { + return "string"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "anyURI", + function (Type $type) { + return "string"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "byte", + function (Type $type) { + return "string"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "duration", + function (Type $type) { + return "DateInterval"; + } + ); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "ID", function (Type $type) - { - return "string"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "IDREF", function (Type $type) - { - return "string"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "IDREFS", function (Type $type) - { - return "string"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "Name", function (Type $type) - { - return "string"; - }); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "ID", + function (Type $type) { + return "string"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "IDREF", + function (Type $type) { + return "string"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "IDREFS", + function (Type $type) { + return "string"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "Name", + function (Type $type) { + return "string"; + } + ); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "NCName", function (Type $type) - { - return "string"; - }); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "NCName", + function (Type $type) { + return "string"; + } + ); } /** @@ -254,18 +365,19 @@ protected function isArrayType(Type $type) */ protected function isArrayNestedElement(Type $type) { - if ($type instanceof ComplexType && ! $type->getParent() && ! $type->getAttributes() && count($type->getElements()) === 1) { + if ($type instanceof ComplexType && !$type->getParent() && !$type->getAttributes() && count($type->getElements()) === 1) { $elements = $type->getElements(); return $this->isArrayElement(reset($elements)); } } + /** * @param ElementSingle $type * @return \Goetas\XML\XSDReader\Schema\Element\ElementSingle|null */ protected function isArrayElement($element) { - if ($element instanceof ElementSingle && ($element->getMax() > 1 || $element->getMax() === - 1)) { + if ($element instanceof ElementSingle && ($element->getMax() > 1 || $element->getMax() === -1)) { return $element; } } diff --git a/lib/Command/AbstractConvert.php b/lib/Command/AbstractConvert.php index 87aec31..c30b7f2 100644 --- a/lib/Command/AbstractConvert.php +++ b/lib/Command/AbstractConvert.php @@ -2,61 +2,58 @@ namespace Goetas\Xsd\XsdToPhp\Command; use Exception; -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console; use Goetas\XML\XSDReader\SchemaReader; use Goetas\Xsd\XsdToPhp\AbstractConverter; -use Symfony\Component\Console\Output\OutputInterface; -use Goetas\Xsd\XsdToPhp\Naming\ShortNamingStrategy; use Goetas\Xsd\XsdToPhp\Naming\LongNamingStrategy; use Goetas\Xsd\XsdToPhp\Naming\NamingStrategy; +use Goetas\Xsd\XsdToPhp\Naming\ShortNamingStrategy; +use Symfony\Component\Console; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; -abstract class AbstractConvert extends Console\Command\Command +abstract class AbstractConvert extends Command { - - /** - * - * @see Console\Command\Command - */ protected function configure() { - $this->setDefinition(array( - new InputArgument('src', InputArgument::REQUIRED | InputArgument::IS_ARRAY, 'Where is located your XSD definitions'), - new InputOption('ns-map', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'How to map XML namespaces to PHP namespaces? Syntax: XML-namespace;PHP-namespace'), - new InputOption('ns-dest', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Where place the generated files? Syntax: PHP-namespace;destination-directory'), - new InputOption('alias-map', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'How to map XML namespaces into existing PHP classes? Syntax: XML-namespace;XML-type;PHP-type. '), - new InputOption('naming-strategy', null, InputOption::VALUE_REQUIRED, 'The naming strategy for classes. short|long', 'short') - )); + $this->setDefinition( + array( + new InputArgument('src', InputArgument::REQUIRED | InputArgument::IS_ARRAY, 'Where is located your XSD definitions'), + new InputOption('ns-map', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'How to map XML namespaces to PHP namespaces? Syntax: XML-namespace;PHP-namespace'), + new InputOption('ns-dest', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Where place the generated files? Syntax: PHP-namespace;destination-directory'), + new InputOption('alias-map', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'How to map XML namespaces into existing PHP classes? Syntax: XML-namespace;XML-type;PHP-type. '), + new InputOption('naming-strategy', null, InputOption::VALUE_REQUIRED, 'The naming strategy for classes. short|long', 'short') + ) + ); } /** + * @param InputInterface $input + * @param OutputInterface $output + * @return int + * @throws Exception */ - protected abstract function getConverterter(NamingStrategy $naming); - - /** - * - * @see Console\Command\Command - */ - protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output) { $src = $input->getArgument('src'); $nsMap = $input->getOption('ns-map'); - if (! $nsMap) { + if (!$nsMap) { throw new \RuntimeException(__CLASS__ . " requires at least one ns-map."); } $nsTarget = $input->getOption('ns-dest'); - if (! $nsTarget) { + if (!$nsTarget) { throw new \RuntimeException(__CLASS__ . " requires at least one ns-target."); } - if($input->getOption('naming-strategy')=='short'){ + if ($input->getOption('naming-strategy') == 'short') { $naming = new ShortNamingStrategy(); - }elseif($input->getOption('naming-strategy')=='long'){ + } elseif ($input->getOption('naming-strategy') == 'long') { $naming = new LongNamingStrategy(); - }else{ + } else { throw new \InvalidArgumentException("Unsupported naming strategy"); } @@ -71,7 +68,7 @@ protected function execute(Console\Input\InputInterface $input, Console\Output\O list ($xmlNs, $phpNs) = explode(";", $val, 2); $nsMapKeyed[$xmlNs] = $phpNs; $converter->addNamespace($xmlNs, trim(strtr($phpNs, "./", "\\\\"), "\\")); - $output->writeln("\tXML namepsace: $xmlNs => PHP namepsace: $phpNs"); + $output->writeln("\tXML namespace: $xmlNs => PHP namespace: $phpNs"); } $targets = array(); $output->writeln("Target directories:"); @@ -83,7 +80,7 @@ protected function execute(Console\Input\InputInterface $input, Console\Output\O $phpNs = strtr($phpNs, "./", "\\\\"); $targets[$phpNs] = $dir; - $output->writeln("\tPHP namepsace: " . strtr($phpNs, "\\", "/") . " => Destination directory: $dir"); + $output->writeln("\tPHP namespace: " . strtr($phpNs, "\\", "/") . " => Destination directory: $dir"); } $arrayMap = $input->getOption('alias-map'); if ($arrayMap) { @@ -103,11 +100,11 @@ protected function execute(Console\Input\InputInterface $input, Console\Output\O $output->writeln("Reading $file"); $xml = new \DOMDocument('1.0', 'UTF-8'); - if (! $xml->load($file)) { + if (!$xml->load($file)) { throw new \Exception("Can't load the schema '{$file}'"); } - if (! isset($nsMapKeyed[$xml->documentElement->getAttribute("targetNamespace")])) { + if (!isset($nsMapKeyed[$xml->documentElement->getAttribute("targetNamespace")])) { $output->writeln("\tSkipping " . $xml->documentElement->getAttribute("targetNamespace") . ", can't find a PHP-equivalent namespace. Use --ns-map option?"); continue; } @@ -122,5 +119,18 @@ protected function execute(Console\Input\InputInterface $input, Console\Output\O return 0; } + /** + * @param NamingStrategy $naming + * @return AbstractConverter + */ + protected abstract function getConverterter(NamingStrategy $naming); + + /** + * @param AbstractConverter $converter + * @param array $schemas + * @param array $targets + * @param OutputInterface $output + * @return mixed + */ protected abstract function convert(AbstractConverter $converter, array $schemas, array $targets, OutputInterface $output); } diff --git a/lib/Command/ConvertToPHP.php b/lib/Command/ConvertToPHP.php index 91e9201..0537b2f 100644 --- a/lib/Command/ConvertToPHP.php +++ b/lib/Command/ConvertToPHP.php @@ -1,48 +1,92 @@ setName('convert:php'); $this->setDescription('Convert XSD definitions into PHP classes'); + $this->addOption('docblock-nowordwrap', null, InputOption::VALUE_NONE); + } + + /** + * @param InputInterface $input + * @param OutputInterface $output + * @return int + * @throws \Exception + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + if ($input->getOption('docblock-nowordwrap')) { + $this->docBlockNoWordWrap = true; + } + + return parent::execute($input, $output); } + /** + * @param NamingStrategy $naming + * @return PhpConverter + */ protected function getConverterter(NamingStrategy $naming) { return new PhpConverter($naming); } + /** + * @param AbstractConverter $converter + * @param array $schemas + * @param array $targets + * @param OutputInterface $output + * @return mixed|void + * @throws PathGeneratorException + */ protected function convert(AbstractConverter $converter, array $schemas, array $targets, OutputInterface $output) { $generator = new ClassGenerator(); + + if ($this->docBlockNoWordWrap) { + $docBlock = new DocBlockGenerator(); + $docBlock->setWordWrap(false); + $generator->setDocBlockGeneratorPrototype($docBlock); + } + $pathGenerator = new Psr4PathGenerator($targets); + + /** @var ProgressHelper $progress */ $progress = $this->getHelperSet()->get('progress'); $items = $converter->convert($schemas); $progress->start($output, count($items)); + /** @var PHPClass $item */ foreach ($items as $item) { $progress->advance(1, true); - $output->write(" Creating " . $output->getFormatter()->escape($item->getFullName()) . "... "); + $output->write(" Creating " . OutputFormatter::escape($item->getFullName()) . "... "); $path = $pathGenerator->getPath($item); - $fileGen = new FileGenerator(); $fileGen->setFilename($path); $classGen = new \Zend\Code\Generator\ClassGenerator(); @@ -53,7 +97,7 @@ protected function convert(AbstractConverter $converter, array $schemas, array $ $fileGen->write(); $output->writeln("done."); - }else{ + } else { $output->write("skip."); } diff --git a/lib/Command/ConvertToYaml.php b/lib/Command/ConvertToYaml.php index 9221020..31feba2 100644 --- a/lib/Command/ConvertToYaml.php +++ b/lib/Command/ConvertToYaml.php @@ -1,12 +1,12 @@ GraphNavigator::DIRECTION_SERIALIZATION, - 'format' => 'xml', - 'type' => 'Goetas\Xsd\XsdToPhp\Jms\SimpleListOf', - 'method' => 'simpleListOfToXml' + 'format' => 'xml', + 'type' => 'Goetas\Xsd\XsdToPhp\Jms\SimpleListOf', + 'method' => 'simpleListOfToXml' ), array( 'direction' => GraphNavigator::DIRECTION_DESERIALIZATION, - 'format' => 'xml', - 'type' => 'Goetas\Xsd\XsdToPhp\Jms\SimpleListOf', - 'method' => 'simpleListOfFromXML' + 'format' => 'xml', + 'type' => 'Goetas\Xsd\XsdToPhp\Jms\SimpleListOf', + 'method' => 'simpleListOfFromXML' ) ); } @@ -32,12 +32,12 @@ public function simpleListOfToXml(XmlSerializationVisitor $visitor, $object, arr { $newType = array( - 'name' => $type["params"][0]["name"], + 'name' => $type["params"][0]["name"], 'params' => array() ); $ret = array(); - foreach ($object as $v){ + foreach ($object as $v) { $ret[] = $context->accept($v, $newType)->data; } @@ -47,11 +47,11 @@ public function simpleListOfToXml(XmlSerializationVisitor $visitor, $object, arr public function simpleListOfFromXml(XmlDeserializationVisitor $visitor, $node, array $type, Context $context) { $newType = array( - 'name' => $type["params"][0]["name"], + 'name' => $type["params"][0]["name"], 'params' => array() ); $ret = array(); - foreach (explode(" ", (string)$node) as $v){ + foreach (explode(" ", (string)$node) as $v) { $ret[] = $context->accept($v, $newType); } return $ret; diff --git a/lib/Jms/Handler/XmlSchemaDateHandler.php b/lib/Jms/Handler/XmlSchemaDateHandler.php index 1fc0a6b..7feb794 100644 --- a/lib/Jms/Handler/XmlSchemaDateHandler.php +++ b/lib/Jms/Handler/XmlSchemaDateHandler.php @@ -1,12 +1,12 @@ GraphNavigator::DIRECTION_DESERIALIZATION, - 'format' => 'xml', - 'type' => 'Goetas\Xsd\XsdToPhp\XMLSchema\DateTime', - 'method' => 'deserializeDateTime' + 'format' => 'xml', + 'type' => 'Goetas\Xsd\XsdToPhp\XMLSchema\DateTime', + 'method' => 'deserializeDateTime' ), array( 'direction' => GraphNavigator::DIRECTION_SERIALIZATION, - 'format' => 'xml', - 'type' => 'Goetas\Xsd\XsdToPhp\XMLSchema\DateTime', - 'method' => 'serializeDateTime' + 'format' => 'xml', + 'type' => 'Goetas\Xsd\XsdToPhp\XMLSchema\DateTime', + 'method' => 'serializeDateTime' ), array( 'direction' => GraphNavigator::DIRECTION_DESERIALIZATION, - 'format' => 'xml', - 'type' => 'Goetas\Xsd\XsdToPhp\XMLSchema\Time', - 'method' => 'deserializeTime' + 'format' => 'xml', + 'type' => 'Goetas\Xsd\XsdToPhp\XMLSchema\Time', + 'method' => 'deserializeTime' ), array( 'direction' => GraphNavigator::DIRECTION_SERIALIZATION, - 'format' => 'xml', - 'type' => 'Goetas\Xsd\XsdToPhp\XMLSchema\Time', - 'method' => 'serializeTime' + 'format' => 'xml', + 'type' => 'Goetas\Xsd\XsdToPhp\XMLSchema\Time', + 'method' => 'serializeTime' ) ); } @@ -53,8 +53,8 @@ public function serializeDateTime(XmlSerializationVisitor $visitor, \DateTime $d { $v = $date->format(\DateTime::W3C); - if (substr($v, - 5) == "00:00") { - $v = substr($v, 0, - 6); + if (substr($v, -5) == "00:00") { + $v = substr($v, 0, -6); } return $visitor->visitSimpleString($v, $type, $context); } @@ -62,7 +62,7 @@ public function serializeDateTime(XmlSerializationVisitor $visitor, \DateTime $d public function deserializeDateTime(XmlDeserializationVisitor $visitor, $data, array $type) { $attributes = $data->attributes('xsi', true); - if (isset($attributes['nil'][0]) && (string) $attributes['nil'][0] === 'true') { + if (isset($attributes['nil'][0]) && (string)$attributes['nil'][0] === 'true') { return null; } @@ -73,8 +73,8 @@ public function deserializeDateTime(XmlDeserializationVisitor $visitor, $data, a public function serializeTime(XmlSerializationVisitor $visitor, \DateTime $date, array $type, Context $context) { $v = $date->format('H:i:s'); - if ($date->getTimezone()->getOffset($date)!==$this->defaultTimezone->getOffset($date)){ - $v.= $date->format('P'); + if ($date->getTimezone()->getOffset($date) !== $this->defaultTimezone->getOffset($date)) { + $v .= $date->format('P'); } return $visitor->visitSimpleString($v, $type, $context); } @@ -82,19 +82,19 @@ public function serializeTime(XmlSerializationVisitor $visitor, \DateTime $date, public function deserializeTime(XmlDeserializationVisitor $visitor, $data, array $type) { $attributes = $data->attributes('xsi', true); - if (isset($attributes['nil'][0]) && (string) $attributes['nil'][0] === 'true') { + if (isset($attributes['nil'][0]) && (string)$attributes['nil'][0] === 'true') { return null; } - $data = (string) $data; + $data = (string)$data; - return new \DateTime( $data, $this->defaultTimezone ); + return new \DateTime($data, $this->defaultTimezone); } private function parseDateTime($data, array $type) { $timezone = isset($type['params'][1]) ? new \DateTimeZone($type['params'][1]) : $this->defaultTimezone; - $datetime = new \DateTime((string) $data, $timezone); + $datetime = new \DateTime((string)$data, $timezone); if (false === $datetime) { throw new RuntimeException(sprintf('Invalid datetime "%s", expected valid XML Schema dateTime string.', $data)); } diff --git a/lib/Jms/PathGenerator/Psr4PathGenerator.php b/lib/Jms/PathGenerator/Psr4PathGenerator.php index 8653a3f..5540986 100644 --- a/lib/Jms/PathGenerator/Psr4PathGenerator.php +++ b/lib/Jms/PathGenerator/Psr4PathGenerator.php @@ -16,7 +16,7 @@ public function getPath($yaml) $pos = strpos($ns, $namespace); if ($pos === 0) { - if (! is_dir($dir) && ! mkdir($dir, 0777, true)) { + if (!is_dir($dir) && !mkdir($dir, 0777, true)) { throw new PathGeneratorException("Can't create the folder '$dir'"); } $f = strtr(substr($ns, strlen($namespace)), "\\/", ".."); diff --git a/lib/Jms/YamlConverter.php b/lib/Jms/YamlConverter.php index 3e9a60d..99704a5 100644 --- a/lib/Jms/YamlConverter.php +++ b/lib/Jms/YamlConverter.php @@ -1,44 +1,54 @@ addAliasMap("http://www.w3.org/2001/XMLSchema", "dateTime", function (Type $type) - { - return "Goetas\Xsd\XsdToPhp\XMLSchema\DateTime"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "time", function (Type $type) - { - return "Goetas\Xsd\XsdToPhp\XMLSchema\Time"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "date", function (Type $type) - { - return "DateTime<'Y-m-d'>"; - }); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "dateTime", + function (Type $type) { + return "Goetas\Xsd\XsdToPhp\XMLSchema\DateTime"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "time", + function (Type $type) { + return "Goetas\Xsd\XsdToPhp\XMLSchema\Time"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "date", + function (Type $type) { + return "DateTime<'Y-m-d'>"; + } + ); } private $classes = []; @@ -85,16 +95,18 @@ private function flattElements(ElementContainer $container) */ public function getTypes() { - uasort($this->classes, function ($a, $b) - { - return strcmp(key($a), key($b)); - }); + uasort( + $this->classes, + function ($a, $b) { + return strcmp(key($a), key($b)); + } + ); $ret = array(); foreach ($this->classes as $definition) { $classname = key($definition["class"]); - if (strpos($classname, '\\') !== false && (! isset($definition["skip"]) || ! $definition["skip"])) { + if (strpos($classname, '\\') !== false && (!isset($definition["skip"]) || !$definition["skip"])) { $ret[$classname] = $definition["class"]; } } @@ -117,7 +129,7 @@ private function navigate(Schema $schema, array &$visited) } foreach ($schema->getSchemas() as $schildSchema) { - if (! in_array($schildSchema->getTargetNamespace(), $this->baseSchemas, true)) { + if (!in_array($schildSchema->getTargetNamespace(), $this->baseSchemas, true)) { $this->navigate($schildSchema, $visited); } } @@ -138,8 +150,8 @@ private function visitTypeBase(&$class, &$data, Type $type, $name) private function &visitElementDef(Schema $schema, ElementDef $element) { - if (! isset($this->classes[spl_object_hash($element)])) { - $className = $this->findPHPNamespace($element)."\\".$this->getNamingStrategy()->getItemName($element); + if (!isset($this->classes[spl_object_hash($element)])) { + $className = $this->findPHPNamespace($element) . "\\" . $this->getNamingStrategy()->getItemName($element); $class = array(); $data = array(); $ns = $className; @@ -151,7 +163,7 @@ private function &visitElementDef(Schema $schema, ElementDef $element) } $this->classes[spl_object_hash($element)]["class"] = &$class; - if (! $element->getType()->getName()) { + if (!$element->getType()->getName()) { $this->visitTypeBase($class, $data, $element->getType(), $element->getName()); } else { $this->handleClassExtension($class, $data, $element->getType(), $element->getName()); @@ -164,13 +176,12 @@ private function findPHPNamespace(SchemaItem $item) { $schema = $item->getSchema(); - if (! isset($this->namespaces[$schema->getTargetNamespace()])) { + if (!isset($this->namespaces[$schema->getTargetNamespace()])) { throw new Exception(sprintf("Can't find a PHP namespace to '%s' namespace", $schema->getTargetNamespace())); } return $this->namespaces[$schema->getTargetNamespace()]; } - private function findPHPName(Type $type) { $schema = $type->getSchema(); @@ -185,11 +196,10 @@ private function findPHPName(Type $type) return $ns . "\\" . $name; } - private function &visitType(Type $type, $force = false) { - if (! isset($this->classes[spl_object_hash($type)])) { + if (!isset($this->classes[spl_object_hash($type)])) { if ($alias = $this->getTypeAlias($type)) { $class = array(); @@ -211,7 +221,7 @@ private function &visitType(Type $type, $force = false) $this->visitTypeBase($class, $data, $type, $type->getName()); - if ($type instanceof SimpleType){ + if ($type instanceof SimpleType) { $this->classes[spl_object_hash($type)]["skip"] = true; return $class; } @@ -220,8 +230,8 @@ private function &visitType(Type $type, $force = false) $this->classes[spl_object_hash($type)]["skip"] = true; return $class; } - }elseif ($force) { - if (!($type instanceof SimpleType) && !$this->getTypeAlias($type)){ + } elseif ($force) { + if (!($type instanceof SimpleType) && !$this->getTypeAlias($type)) { $this->classes[spl_object_hash($type)]["skip"] = false; } } @@ -241,7 +251,7 @@ private function &visitTypeAnonymous(Type $type, $parentName, $parentClass) if ($parentName) { $this->classes[spl_object_hash($type)]["class"] = &$class; - if ($type instanceof SimpleType){ + if ($type instanceof SimpleType) { $this->classes[spl_object_hash($type)]["skip"] = true; } } @@ -251,7 +261,7 @@ private function &visitTypeAnonymous(Type $type, $parentName, $parentClass) private function visitComplexType(&$class, &$data, ComplexType $type) { $schema = $type->getSchema(); - if (! isset($data["properties"])) { + if (!isset($data["properties"])) { $data["properties"] = array(); } foreach ($this->flattElements($type) as $element) { @@ -268,7 +278,7 @@ private function visitSimpleType(&$class, &$data, SimpleType $type, $name) } } elseif ($unions = $type->getUnions()) { foreach ($unions as $i => $unon) { - $this->handleClassExtension($class, $data, $unon, $name.$i); + $this->handleClassExtension($class, $data, $unon, $name . $i); break; } } @@ -285,7 +295,7 @@ private function visitBaseComplexType(&$class, &$data, BaseComplexType $type, $n } $schema = $type->getSchema(); - if (! isset($data["properties"])) { + if (!isset($data["properties"])) { $data["properties"] = array(); } foreach ($this->flattAttributes($type) as $attr) { @@ -297,7 +307,6 @@ private function handleClassExtension(&$class, &$data, Type $type, $parentName) { if ($alias = $this->getTypeAlias($type)) { - $property = array(); $property["expose"] = true; $property["xml_value"] = true; @@ -308,14 +317,13 @@ private function handleClassExtension(&$class, &$data, Type $type, $parentName) $data["properties"]["__value"] = $property; - - }else{ + } else { $extension = $this->visitType($type, true); if (isset($extension['properties']['__value']) && count($extension['properties']) === 1) { $data["properties"]["__value"] = $extension['properties']['__value']; } else { - if($type instanceof SimpleType){ // @todo ?? basta come controllo? + if ($type instanceof SimpleType) { // @todo ?? basta come controllo? $property = array(); $property["expose"] = true; $property["xml_value"] = true; @@ -348,10 +356,10 @@ private function visitAttribute(&$class, Schema $schema, AttributeItem $attribut $property["xml_attribute"] = true; - if ($alias = $this->getTypeAlias($attribute)) { + if ($alias = $this->getTypeAlias($attribute)) { $property["type"] = $alias; - }elseif ($itemOfArray = $this->isArrayType($attribute->getType())) { + } elseif ($itemOfArray = $this->isArrayType($attribute->getType())) { if ($valueProp = $this->typeHasValue($itemOfArray, $class, 'xx')) { $property["type"] = "Goetas\Xsd\XsdToPhp\Jms\SimpleListOf<" . $valueProp . ">"; @@ -372,7 +380,7 @@ private function visitAttribute(&$class, Schema $schema, AttributeItem $attribut private function typeHasValue(Type $type, $parentClass, $name) { - $collected = array(); + $collected = array(); do { if ($alias = $this->getTypeAlias($type)) { return $alias; @@ -416,12 +424,12 @@ private function visitElement(&$class, Schema $schema, ElementItem $element, $ar $property["accessor"]["setter"] = "set" . Inflector::classify($element->getName()); $t = $element->getType(); - if ($arrayize){ + if ($arrayize) { - if($itemOfArray = $this->isArrayNestedElement($t)) { - if(!$t->getName()){ + if ($itemOfArray = $this->isArrayNestedElement($t)) { + if (!$t->getName()) { $classType = $this->visitTypeAnonymous($t, $element->getName(), $class); - }else{ + } else { $classType = $this->visitType($t); } @@ -436,15 +444,15 @@ private function visitElement(&$class, Schema $schema, ElementItem $element, $ar return $property; } elseif ($itemOfArray = $this->isArrayType($t)) { - if(!$t->getName()){ + if (!$t->getName()) { $visitedType = $this->visitTypeAnonymous($itemOfArray, $element->getName(), $class); - if($prop = $this->typeHasValue($itemOfArray, $class, 'xx')){ - $property["type"] = "array<" .$prop . ">"; - }else{ + if ($prop = $this->typeHasValue($itemOfArray, $class, 'xx')) { + $property["type"] = "array<" . $prop . ">"; + } else { $property["type"] = "array<" . key($visitedType) . ">"; } - }else{ + } else { $this->visitType($itemOfArray); $property["type"] = "array<" . $this->findPHPName($itemOfArray) . ">"; } @@ -482,10 +490,10 @@ private function findPHPClass(&$class, Item $node) $elementRef = $this->visitElementDef($node->getSchema(), $node->getReferencedElement()); return key($elementRef); } - if($valueProp = $this->typeHasValue($type, $class, '')){ + if ($valueProp = $this->typeHasValue($type, $class, '')) { return $valueProp; } - if (! $node->getType()->getName()) { + if (!$node->getType()->getName()) { $visited = $this->visitTypeAnonymous($node->getType(), $node->getName(), $class); } else { $visited = $this->visitType($node->getType()); diff --git a/lib/Naming/LongNamingStrategy.php b/lib/Naming/LongNamingStrategy.php index 70537bf..aa6c44b 100644 --- a/lib/Naming/LongNamingStrategy.php +++ b/lib/Naming/LongNamingStrategy.php @@ -2,8 +2,8 @@ namespace Goetas\Xsd\XsdToPhp\Naming; use Doctrine\Common\Inflector\Inflector; -use Goetas\XML\XSDReader\Schema\Type\Type; use Goetas\XML\XSDReader\Schema\Item; +use Goetas\XML\XSDReader\Schema\Type\Type; class LongNamingStrategy implements NamingStrategy { @@ -25,11 +25,11 @@ public function getItemName(Item $item) public function getPropertyName($item) { - return Inflector::camelize(str_replace(".", " ", $item->getName())); + return Inflector::camelize(str_replace(".", " ", $item->getName())); } private function classify($name) { - return Inflector::classify(str_replace(".", " ", $name)); + return Inflector::classify(str_replace(".", " ", $name)); } } \ No newline at end of file diff --git a/lib/Naming/NamingStrategy.php b/lib/Naming/NamingStrategy.php index d52d265..1793ead 100644 --- a/lib/Naming/NamingStrategy.php +++ b/lib/Naming/NamingStrategy.php @@ -1,8 +1,8 @@ classify($type->getName()); - if ($name && substr($name, - 4) !== 'Type') { + if ($name && substr($name, -4) !== 'Type') { $name .= "Type"; } return $name; @@ -24,7 +24,7 @@ public function getAnonymousTypeName(Type $type, $parentName) public function getPropertyName($item) { - return Inflector::camelize(str_replace(".", " ", $item->getName())); + return Inflector::camelize(str_replace(".", " ", $item->getName())); } public function getItemName(Item $item) @@ -34,6 +34,6 @@ public function getItemName(Item $item) private function classify($name) { - return Inflector::classify(str_replace(".", " ", $name)); + return Inflector::classify(str_replace(".", " ", $name)); } } \ No newline at end of file diff --git a/lib/PathGenerator/Psr4PathGenerator.php b/lib/PathGenerator/Psr4PathGenerator.php index b4e607f..9f3a21a 100644 --- a/lib/PathGenerator/Psr4PathGenerator.php +++ b/lib/PathGenerator/Psr4PathGenerator.php @@ -14,10 +14,10 @@ public function __construct(array $namespaces) if ($namespace[strlen($namespace) - 1] !== "\\") { throw new PathGeneratorException("A non-empty PSR-4 prefix must end with a namespace separator, you entered '$namespace'."); } - if (! is_dir($dir)) { + if (!is_dir($dir)) { throw new PathGeneratorException("The folder '$dir' does not exist."); } - if (! is_writable($dir)) { + if (!is_writable($dir)) { throw new PathGeneratorException("The folder '$dir' is not writable."); } } diff --git a/lib/Php/ClassGenerator.php b/lib/Php/ClassGenerator.php index 19c524e..716782c 100644 --- a/lib/Php/ClassGenerator.php +++ b/lib/Php/ClassGenerator.php @@ -3,20 +3,81 @@ use Doctrine\Common\Inflector\Inflector; use Goetas\Xsd\XsdToPhp\Php\Structure\PHPClass; -use Goetas\Xsd\XsdToPhp\Php\Structure\PHPProperty; use Goetas\Xsd\XsdToPhp\Php\Structure\PHPClassOf; +use Goetas\Xsd\XsdToPhp\Php\Structure\PHPProperty; use Zend\Code\Generator; -use Zend\Code\Generator\PropertyGenerator; -use Zend\Code\Generator\DocBlockGenerator; use Zend\Code\Generator\DocBlock\Tag\ParamTag; +use Zend\Code\Generator\DocBlock\Tag\PropertyTag; use Zend\Code\Generator\DocBlock\Tag\ReturnTag; +use Zend\Code\Generator\DocBlockGenerator; use Zend\Code\Generator\MethodGenerator; use Zend\Code\Generator\ParameterGenerator; -use Zend\Code\Generator\DocBlock\Tag\PropertyTag; +use Zend\Code\Generator\PropertyGenerator; class ClassGenerator { + /** + * @var DocBlockGenerator + */ + private $docBlockGeneratorPrototype; + + /** + * @param Generator\ClassGenerator $class + * @param PHPClass $type + * @return bool + */ + public function generate(Generator\ClassGenerator $class, PHPClass $type) + { + $docblock = $this->createDocBlockGenerator("Class representing " . $type->getName()); + if ($type->getDoc()) { + $docblock->setLongDescription($type->getDoc()); + } + $class->setNamespaceName($type->getNamespace()); + $class->setName($type->getName()); + $class->setDocblock($docblock); + + if ($extends = $type->getExtends()) { + + if ($p = $this->isOneType($extends)) { + $this->handleProperty($class, $p); + $this->handleValueMethod($class, $p, $extends); + } else { + + $class->setExtendedClass($extends->getName()); + + if ($extends->getNamespace() != $type->getNamespace()) { + if ($extends->getName() == $type->getName()) { + $class->addUse( + $type->getExtends() + ->getFullName(), + $extends->getName() . "Base" + ); + $class->setExtendedClass($extends->getName() . "Base"); + } else { + $class->addUse($extends->getFullName()); + } + } + } + } + + if ($this->handleBody($class, $type)) { + return true; + } + } + + /** + * @param DocBlockGenerator $docBlockGeneratorPrototype + */ + public function setDocBlockGeneratorPrototype(DocBlockGenerator $docBlockGeneratorPrototype = null) + { + $this->docBlockGeneratorPrototype = $docBlockGeneratorPrototype; + } + /** + * @param Generator\ClassGenerator $class + * @param PHPClass $type + * @return bool + */ private function handleBody(Generator\ClassGenerator $class, PHPClass $type) { foreach ($type->getProperties() as $prop) { @@ -37,23 +98,52 @@ private function handleBody(Generator\ClassGenerator $class, PHPClass $type) return true; } + /** + * @param PHPClass $class + * @return bool + */ private function isNativeType(PHPClass $class) { - return ! $class->getNamespace() && in_array($class->getName(), [ - 'string', - 'int', - 'float', - 'integer', - 'boolean', - 'array', - 'mixed', - 'callable' - ]); + return !$class->getNamespace() && in_array( + $class->getName(), + [ + 'string', + 'int', + 'float', + 'integer', + 'boolean', + 'array', + 'mixed', + 'callable' + ] + ); + } + + /** + * @param string $shortDescription + * @param string $longDescription + * @param array $tags + * @return DocBlockGenerator + */ + private function createDocBlockGenerator($shortDescription = null, $longDescription = null, array $tags = []) + { + $docBlockGenerator = $this->docBlockGeneratorPrototype ? + clone $this->docBlockGeneratorPrototype : new DocBlockGenerator(); + + $docBlockGenerator->setShortDescription($shortDescription); + $docBlockGenerator->setLongDescription($longDescription); + $docBlockGenerator->setTags($tags); + + return $docBlockGenerator; } + /** + * @param PHPClass $class + * @return string + */ private function getPhpType(PHPClass $class) { - if (! $class->getNamespace()) { + if (!$class->getNamespace()) { if ($this->isNativeType($class)) { return $class->getName(); } @@ -62,33 +152,45 @@ private function getPhpType(PHPClass $class) return "\\" . $class->getFullName(); } + /** + * @param Generator\ClassGenerator $generator + * @param PHPProperty $prop + * @param PHPClass $class + * @param bool|true $all + */ private function handleValueMethod(Generator\ClassGenerator $generator, PHPProperty $prop, PHPClass $class, $all = true) { $type = $prop->getType(); - $docblock = new DocBlockGenerator('Construct'); + $docblock = $this->createDocBlockGenerator('Construct'); $paramTag = new ParamTag("value", "mixed"); $paramTag->setTypes(($type ? $this->getPhpType($type) : "mixed")); $docblock->setTag($paramTag); $param = new ParameterGenerator("value"); - if ($type && ! $this->isNativeType($type)) { + if ($type && !$this->isNativeType($type)) { $param->setType($this->getPhpType($type)); } - $method = new MethodGenerator("__construct", [ - $param - ]); + $method = new MethodGenerator( + "__construct", [ + $param + ] + ); $method->setDocBlock($docblock); $method->setBody("\$this->value(\$value);"); $generator->addMethodFromGenerator($method); - $docblock = new DocBlockGenerator('Gets or sets the inner value'); + $docblock = $this->createDocBlockGenerator('Gets or sets the inner value'); $paramTag = new ParamTag("value", "mixed"); if ($type && $type instanceof PHPClassOf) { - $paramTag->setTypes($this->getPhpType($type->getArg() - ->getType()) . "[]"); + $paramTag->setTypes( + $this->getPhpType( + $type->getArg() + ->getType() + ) . "[]" + ); } elseif ($type) { $paramTag->setTypes($this->getPhpType($prop->getType())); } @@ -97,8 +199,12 @@ private function handleValueMethod(Generator\ClassGenerator $generator, PHPPrope $returnTag = new ReturnTag("mixed"); if ($type && $type instanceof PHPClassOf) { - $returnTag->setTypes($this->getPhpType($type->getArg() - ->getType()) . "[]"); + $returnTag->setTypes( + $this->getPhpType( + $type->getArg() + ->getType() + ) . "[]" + ); } elseif ($type) { $returnTag->setTypes($this->getPhpType($type)); } @@ -107,7 +213,7 @@ private function handleValueMethod(Generator\ClassGenerator $generator, PHPPrope $param = new ParameterGenerator("value"); $param->setDefaultValue(null); - if ($type && ! $this->isNativeType($type)) { + if ($type && !$this->isNativeType($type)) { $param->setType($this->getPhpType($type)); } $method = new MethodGenerator("value", []); @@ -121,7 +227,7 @@ private function handleValueMethod(Generator\ClassGenerator $generator, PHPPrope $generator->addMethodFromGenerator($method); - $docblock = new DocBlockGenerator('Gets a string value'); + $docblock = $this->createDocBlockGenerator('Gets a string value'); $docblock->setTag(new ReturnTag("string")); $method = new MethodGenerator("__toString"); $method->setDocBlock($docblock); @@ -129,10 +235,15 @@ private function handleValueMethod(Generator\ClassGenerator $generator, PHPPrope $generator->addMethodFromGenerator($method); } + /** + * @param Generator\ClassGenerator $generator + * @param PHPProperty $prop + * @param PHPClass $class + */ private function handleSetter(Generator\ClassGenerator $generator, PHPProperty $prop, PHPClass $class) { $methodBody = ''; - $docblock = new DocBlockGenerator(); + $docblock = $this->createDocBlockGenerator(); $docblock->setShortDescription("Sets a new " . $prop->getName()); @@ -153,12 +264,19 @@ private function handleSetter(Generator\ClassGenerator $generator, PHPProperty $ $parameter = new ParameterGenerator($prop->getName(), "mixed"); if ($type && $type instanceof PHPClassOf) { - $patramTag->setTypes($this->getPhpType($type->getArg() - ->getType()) . "[]"); + $patramTag->setTypes( + $this->getPhpType( + $type->getArg() + ->getType() + ) . "[]" + ); $parameter->setType("array"); - if ($p = $this->isOneType($type->getArg() - ->getType())) { + if ($p = $this->isOneType( + $type->getArg() + ->getType() + ) + ) { if (($t = $p->getType())) { $patramTag->setTypes($this->getPhpType($t)); } @@ -167,10 +285,10 @@ private function handleSetter(Generator\ClassGenerator $generator, PHPProperty $ if ($this->isNativeType($type)) { $patramTag->setTypes($this->getPhpType($type)); } elseif ($p = $this->isOneType($type)) { - if (($t = $p->getType()) && ! $this->isNativeType($t)) { + if (($t = $p->getType()) && !$this->isNativeType($t)) { $patramTag->setTypes($this->getPhpType($t)); $parameter->setType($this->getPhpType($t)); - } elseif ($t && ! $this->isNativeType($t)) { + } elseif ($t && !$this->isNativeType($t)) { $patramTag->setTypes($this->getPhpType($t)); $parameter->setType($this->getPhpType($t)); } elseif ($t) { @@ -191,11 +309,16 @@ private function handleSetter(Generator\ClassGenerator $generator, PHPProperty $ $generator->addMethodFromGenerator($method); } + /** + * @param Generator\ClassGenerator $generator + * @param PHPProperty $prop + * @param PHPClass $class + */ private function handleGetter(Generator\ClassGenerator $generator, PHPProperty $prop, PHPClass $class) { - if ($prop->getType() instanceof PHPClassOf){ - $docblock = new DocBlockGenerator(); + if ($prop->getType() instanceof PHPClassOf) { + $docblock = $this->createDocBlockGenerator(); $docblock->setShortDescription("isset " . $prop->getName()); if ($prop->getDoc()) { $docblock->setLongDescription($prop->getDoc()); @@ -213,7 +336,7 @@ private function handleGetter(Generator\ClassGenerator $generator, PHPProperty $ $method->setBody("return isset(\$this->" . $prop->getName() . "[\$index]);"); $generator->addMethodFromGenerator($method); - $docblock = new DocBlockGenerator(); + $docblock = $this->createDocBlockGenerator(); $docblock->setShortDescription("unset " . $prop->getName()); if ($prop->getDoc()) { $docblock->setLongDescription($prop->getDoc()); @@ -225,16 +348,13 @@ private function handleGetter(Generator\ClassGenerator $generator, PHPProperty $ $docblock->setTag(new ReturnTag("void")); - - $method = new MethodGenerator("unset" . Inflector::classify($prop->getName()), [$paramIndex]); $method->setDocBlock($docblock); $method->setBody("unset(\$this->" . $prop->getName() . "[\$index]);"); $generator->addMethodFromGenerator($method); } - // //// - $docblock = new DocBlockGenerator(); + $docblock = $this->createDocBlockGenerator(); $docblock->setShortDescription("Gets as " . $prop->getName()); @@ -272,6 +392,11 @@ private function handleGetter(Generator\ClassGenerator $generator, PHPProperty $ $generator->addMethodFromGenerator($method); } + /** + * @param PHPClass $type + * @param bool|false $onlyParent + * @return PHPProperty + */ private function isOneType(PHPClass $type, $onlyParent = false) { if ($onlyParent) { @@ -288,12 +413,17 @@ private function isOneType(PHPClass $type, $onlyParent = false) } } + /** + * @param Generator\ClassGenerator $generator + * @param PHPProperty $prop + * @param PHPClass $class + */ private function handleAdder(Generator\ClassGenerator $generator, PHPProperty $prop, PHPClass $class) { $type = $prop->getType(); $propName = $type->getArg()->getName(); - $docblock = new DocBlockGenerator(); + $docblock = $this->createDocBlockGenerator(); $docblock->setShortDescription("Adds as $propName"); if ($prop->getDoc()) { @@ -304,26 +434,30 @@ private function handleAdder(Generator\ClassGenerator $generator, PHPProperty $p $return->setTypes("self"); $docblock->setTag($return); - $patramTag = new ParamTag($propName, $this->getPhpType($type->getArg() - ->getType())); + $patramTag = new ParamTag( + $propName, $this->getPhpType( + $type->getArg() + ->getType() + ) + ); $docblock->setTag($patramTag); - $method = new MethodGenerator("addTo".Inflector::classify($prop->getName())); + $method = new MethodGenerator("addTo" . Inflector::classify($prop->getName())); $parameter = new ParameterGenerator($propName); $tt = $type->getArg()->getType(); - if (! $this->isNativeType($tt)) { + if (!$this->isNativeType($tt)) { if ($p = $this->isOneType($tt)) { if (($t = $p->getType())) { $patramTag->setTypes($this->getPhpType($t)); - if (! $this->isNativeType($t)) { + if (!$this->isNativeType($t)) { $parameter->setType($this->getPhpType($t)); } } - } elseif (! $this->isNativeType($tt)) { + } elseif (!$this->isNativeType($tt)) { $parameter->setType($this->getPhpType($tt)); } } @@ -337,6 +471,11 @@ private function handleAdder(Generator\ClassGenerator $generator, PHPProperty $p $generator->addMethodFromGenerator($method); } + /** + * @param Generator\ClassGenerator $generator + * @param PHPProperty $prop + * @param PHPClass $class + */ private function handleMethod(Generator\ClassGenerator $generator, PHPProperty $prop, PHPClass $class) { if ($prop->getType() instanceof PHPClassOf) { @@ -347,6 +486,10 @@ private function handleMethod(Generator\ClassGenerator $generator, PHPProperty $ $this->handleSetter($generator, $prop, $class); } + /** + * @param Generator\ClassGenerator $class + * @param PHPProperty $prop + */ private function handleProperty(Generator\ClassGenerator $class, PHPProperty $prop) { $generatedProp = new PropertyGenerator($prop->getName()); @@ -354,11 +497,11 @@ private function handleProperty(Generator\ClassGenerator $class, PHPProperty $pr $class->addPropertyFromGenerator($generatedProp); - if ($prop->getType() && (! $prop->getType()->getNamespace() && $prop->getType()->getName() == "array")) { + if ($prop->getType() && (!$prop->getType()->getNamespace() && $prop->getType()->getName() == "array")) { // $generatedProp->setDefaultValue(array(), PropertyValueGenerator::TYPE_AUTO, PropertyValueGenerator::OUTPUT_SINGLE_LINE); } - $docBlock = new DocBlockGenerator(); + $docBlock = $this->createDocBlockGenerator(); $generatedProp->setDocBlock($docBlock); if ($prop->getDoc()) { @@ -388,40 +531,4 @@ private function handleProperty(Generator\ClassGenerator $class, PHPProperty $pr } $docBlock->setTag($tag); } - - public function generate(Generator\ClassGenerator $class, PHPClass $type) - { - $docblock = new DocBlockGenerator("Class representing " . $type->getName()); - if ($type->getDoc()) { - $docblock->setLongDescription($type->getDoc()); - } - $class->setNamespaceName($type->getNamespace()); - $class->setName($type->getName()); - $class->setDocblock($docblock); - - if ($extends = $type->getExtends()) { - - if ($p = $this->isOneType($extends)) { - $this->handleProperty($class, $p); - $this->handleValueMethod($class, $p, $extends); - } else { - - $class->setExtendedClass($extends->getName()); - - if ($extends->getNamespace() != $type->getNamespace()) { - if ($extends->getName() == $type->getName()) { - $class->addUse($type->getExtends() - ->getFullName(), $extends->getName() . "Base"); - $class->setExtendedClass($extends->getName() . "Base"); - } else { - $class->addUse($extends->getFullName()); - } - } - } - } - - if ($this->handleBody($class, $type)) { - return true; - } - } } diff --git a/lib/Php/PathGenerator/PathGenerator.php b/lib/Php/PathGenerator/PathGenerator.php index a7a83cc..2aec0e2 100644 --- a/lib/Php/PathGenerator/PathGenerator.php +++ b/lib/Php/PathGenerator/PathGenerator.php @@ -1,8 +1,8 @@ getNamespace()) . "\\", $namespace) === 0) { $d = strtr(substr($php->getNamespace(), strlen($namespace)), "\\", "/"); $dir = rtrim($dir, "/") . "/" . $d; - if (! is_dir($dir) && ! mkdir($dir, 0777, true)) { + if (!is_dir($dir) && !mkdir($dir, 0777, true)) { throw new PathGeneratorException("Can't create the '$dir' directory"); } diff --git a/lib/Php/PhpConverter.php b/lib/Php/PhpConverter.php index ae33a00..f7f44fb 100644 --- a/lib/Php/PhpConverter.php +++ b/lib/Php/PhpConverter.php @@ -2,53 +2,68 @@ namespace Goetas\Xsd\XsdToPhp\Php; use Exception; -use Doctrine\Common\Inflector\Inflector; -use Goetas\Xsd\XsdToPhp\Php\Structure\PHPClassOf; -use Goetas\Xsd\XsdToPhp\Php\Structure\PHPArg; -use Goetas\Xsd\XsdToPhp\Php\Structure\PHPClass; -use Goetas\Xsd\XsdToPhp\Php\Structure\PHPProperty; +use Goetas\XML\XSDReader\Schema\Attribute\AttributeItem; +use Goetas\XML\XSDReader\Schema\Attribute\Group as AttributeGroup; +use Goetas\XML\XSDReader\Schema\Element\Element; +use Goetas\XML\XSDReader\Schema\Element\ElementDef; +use Goetas\XML\XSDReader\Schema\Element\ElementRef; +use Goetas\XML\XSDReader\Schema\Element\ElementSingle; +use Goetas\XML\XSDReader\Schema\Element\Group; +use Goetas\XML\XSDReader\Schema\Item; use Goetas\XML\XSDReader\Schema\Schema; -use Goetas\XML\XSDReader\Schema\Type\Type; use Goetas\XML\XSDReader\Schema\Type\BaseComplexType; use Goetas\XML\XSDReader\Schema\Type\ComplexType; -use Goetas\XML\XSDReader\Schema\Element\Element; -use Goetas\XML\XSDReader\Schema\Item; -use Goetas\XML\XSDReader\Schema\Attribute\Group as AttributeGroup; -use Goetas\XML\XSDReader\Schema\Element\Group; use Goetas\XML\XSDReader\Schema\Type\SimpleType; -use Goetas\XML\XSDReader\Schema\Attribute\AttributeItem; -use Goetas\XML\XSDReader\Schema\Element\ElementRef; -use Goetas\XML\XSDReader\Schema\Element\ElementDef; -use Goetas\XML\XSDReader\Schema\Element\ElementSingle; +use Goetas\XML\XSDReader\Schema\Type\Type; use Goetas\Xsd\XsdToPhp\AbstractConverter; use Goetas\Xsd\XsdToPhp\Naming\NamingStrategy; +use Goetas\Xsd\XsdToPhp\Php\Structure\PHPArg; +use Goetas\Xsd\XsdToPhp\Php\Structure\PHPClass; +use Goetas\Xsd\XsdToPhp\Php\Structure\PHPClassOf; +use Goetas\Xsd\XsdToPhp\Php\Structure\PHPProperty; class PhpConverter extends AbstractConverter { - public function __construct(NamingStrategy $namingStrategy){ + public function __construct(NamingStrategy $namingStrategy) + { parent::__construct($namingStrategy); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "dateTime", function (Type $type) - { - return "DateTime"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "time", function (Type $type) - { - return "DateTime"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "date", function (Type $type) - { - return "DateTime"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "anySimpleType", function (Type $type) - { - return "mixed"; - }); - $this->addAliasMap("http://www.w3.org/2001/XMLSchema", "anyType", function (Type $type) - { - return "mixed"; - }); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "dateTime", + function (Type $type) { + return "DateTime"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "time", + function (Type $type) { + return "DateTime"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "date", + function (Type $type) { + return "DateTime"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "anySimpleType", + function (Type $type) { + return "mixed"; + } + ); + $this->addAliasMap( + "http://www.w3.org/2001/XMLSchema", + "anyType", + function (Type $type) { + return "mixed"; + } + ); } private $classes = []; @@ -69,13 +84,15 @@ public function convert(array $schemas) */ private function getTypes() { - uasort($this->classes, function ($a, $b) - { - return strcmp($a["class"]->getFullName(), $b["class"]->getFullName()); - }); + uasort( + $this->classes, + function ($a, $b) { + return strcmp($a["class"]->getFullName(), $b["class"]->getFullName()); + } + ); $ret = array(); foreach ($this->classes as $classData) { - if (! isset($classData["skip"]) || ! $classData["skip"]) { + if (!isset($classData["skip"]) || !$classData["skip"]) { $ret[$classData["class"]->getFullName()] = $classData["class"]; } } @@ -98,7 +115,7 @@ private function navigate(Schema $schema, array &$visited) } foreach ($schema->getSchemas() as $schildSchema) { - if (! in_array($schildSchema->getTargetNamespace(), $this->baseSchemas, true)) { + if (!in_array($schildSchema->getTargetNamespace(), $this->baseSchemas, true)) { $this->navigate($schildSchema, $visited); } } @@ -145,7 +162,7 @@ private function visitAttributeGroup(PHPClass $class, Schema $schema, AttributeG private function visitElementDef(ElementDef $element) { - if (! isset($this->classes[spl_object_hash($element)])) { + if (!isset($this->classes[spl_object_hash($element)])) { $schema = $element->getSchema(); $class = new PHPClass(); @@ -153,14 +170,14 @@ private function visitElementDef(ElementDef $element) $class->setName($this->getNamingStrategy()->getItemName($element)); $class->setDoc($element->getDoc()); - if (! isset($this->namespaces[$schema->getTargetNamespace()])) { + if (!isset($this->namespaces[$schema->getTargetNamespace()])) { throw new Exception(sprintf("Can't find a PHP namespace to '%s' namespace", $schema->getTargetNamespace())); } $class->setNamespace($this->namespaces[$schema->getTargetNamespace()]); $this->classes[spl_object_hash($element)]["class"] = $class; - if (! $element->getType()->getName()) { + if (!$element->getType()->getName()) { $this->visitTypeBase($class, $element->getType()); } else { $this->handleClassExtension($class, $element->getType()); @@ -190,7 +207,7 @@ private function findPHPName(Type $type) $name = $this->getNamingStrategy()->getTypeName($type); - if (! isset($this->namespaces[$schema->getTargetNamespace()])) { + if (!isset($this->namespaces[$schema->getTargetNamespace()])) { throw new Exception(sprintf("Can't find a PHP namespace to '%s' namespace", $schema->getTargetNamespace())); } $ns = $this->namespaces[$schema->getTargetNamespace()]; @@ -208,7 +225,7 @@ private function findPHPName(Type $type) */ private function visitType(Type $type, $force = false) { - if (! isset($this->classes[spl_object_hash($type)])) { + if (!isset($this->classes[spl_object_hash($type)])) { $this->classes[spl_object_hash($type)]["class"] = $class = new PHPClass(); @@ -222,11 +239,11 @@ private function visitType(Type $type, $force = false) $class->setName($name); $class->setNamespace($ns); - $class->setDoc($type->getDoc() . PHP_EOL . "XSD Type: " . ($type->getName() ? : 'anonymous')); + $class->setDoc($type->getDoc() . PHP_EOL . "XSD Type: " . ($type->getName() ?: 'anonymous')); $this->visitTypeBase($class, $type); - if ($type instanceof SimpleType){ + if ($type instanceof SimpleType) { $this->classes[spl_object_hash($type)]["skip"] = true; return $class; } @@ -236,8 +253,8 @@ private function visitType(Type $type, $force = false) } $this->classes[spl_object_hash($type)]["skip"] = !!$this->getTypeAlias($type); - }elseif ($force) { - if (!($type instanceof SimpleType) && !$this->getTypeAlias($type)){ + } elseif ($force) { + if (!($type instanceof SimpleType) && !$this->getTypeAlias($type)) { $this->classes[spl_object_hash($type)]["skip"] = false; } } @@ -252,7 +269,7 @@ private function visitType(Type $type, $force = false) */ private function visitTypeAnonymous(Type $type, $name, PHPClass $parentClass) { - if (! isset($this->classes[spl_object_hash($type)])) { + if (!isset($this->classes[spl_object_hash($type)])) { $this->classes[spl_object_hash($type)]["class"] = $class = new PHPClass(); $class->setName($this->getNamingStrategy()->getAnonymousTypeName($type, $name)); @@ -261,7 +278,7 @@ private function visitTypeAnonymous(Type $type, $name, PHPClass $parentClass) $this->visitTypeBase($class, $type); - if ($type instanceof SimpleType){ + if ($type instanceof SimpleType) { $this->classes[spl_object_hash($type)]["skip"] = true; } } @@ -298,7 +315,7 @@ private function visitSimpleType(PHPClass $class, SimpleType $type) } elseif ($unions = $type->getUnions()) { $types = array(); foreach ($unions as $i => $unon) { - if (! $unon->getName()) { + if (!$unon->getName()) { $types[] = $this->visitTypeAnonymous($unon, $type->getName() . $i, $class); } else { $types[] = $this->visitType($unon); @@ -386,9 +403,9 @@ private function visitElement(PHPClass $class, Schema $schema, ElementSingle $el if ($arrayize) { if ($itemOfArray = $this->isArrayType($t)) { - if(!$itemOfArray->getName()){ + if (!$itemOfArray->getName()) { $classType = $this->visitTypeAnonymous($itemOfArray, $element->getName(), $class); - }else{ + } else { $classType = $this->visitType($itemOfArray); } @@ -396,10 +413,10 @@ private function visitElement(PHPClass $class, Schema $schema, ElementSingle $el $arg->setType($classType); $property->setType(new PHPClassOf($arg)); return $property; - }elseif ($itemOfArray = $this->isArrayNestedElement($t)) { - if(!$t->getName()){ + } elseif ($itemOfArray = $this->isArrayNestedElement($t)) { + if (!$t->getName()) { $classType = $this->visitTypeAnonymous($t, $element->getName(), $class); - }else{ + } else { $classType = $this->visitType($t); } $elementProp = $this->visitElement($classType, $schema, $itemOfArray, false); @@ -425,7 +442,7 @@ private function findPHPClass(PHPClass $class, Item $node, $force = false) return $this->visitElementDef($node->getReferencedElement()); } - if (! $node->getType()->getName()) { + if (!$node->getType()->getName()) { return $this->visitTypeAnonymous($node->getType(), $node->getName(), $class); } else { return $this->visitType($node->getType(), $force); diff --git a/lib/Php/Structure/PHPClass.php b/lib/Php/Structure/PHPClass.php index 7511f8a..866f457 100644 --- a/lib/Php/Structure/PHPClass.php +++ b/lib/Php/Structure/PHPClass.php @@ -9,19 +9,42 @@ class PHPClass protected $namespace; protected $doc; + protected $checks = array(); + /** + * + * @var PHPConstant[] + */ + protected $constants = array(); + /** + * + * @var PHPProperty[] + */ + protected $properties = array(); + /** + * + * @var boolean + */ + protected $abstract; + /** + * + * @var PHPClass + */ + protected $extends; - public static function createFromFQCN($className){ + public function __construct($name = null, $namespace = null) + { + $this->name = $name; + $this->namespace = $namespace; + } + + public static function createFromFQCN($className) + { if (($pos = strrpos($className, '\\')) !== false) { return new self(substr($className, $pos + 1), substr($className, 0, $pos)); } else { return new self($className); } } - public function __construct($name = null, $namespace = null) - { - $this->name = $name; - $this->namespace = $namespace; - } public function getName() { @@ -66,20 +89,6 @@ public function getFullName() return "{$this->namespace}\\{$this->name}"; } - protected $checks = array(); - - /** - * - * @var PHPConstant[] - */ - protected $constants = array(); - - /** - * - * @var PHPProperty[] - */ - protected $properties = array(); - /** * * @param @@ -195,18 +204,6 @@ public function addProperty(PHPProperty $property) return $this; } - /** - * - * @var boolean - */ - protected $abstract; - - /** - * - * @var PHPClass - */ - protected $extends; - /** * * @return PHPClass @@ -234,7 +231,7 @@ public function getAbstract() public function setAbstract($abstract) { - $this->abstract = (boolean) $abstract; + $this->abstract = (boolean)$abstract; return $this; } }