| 1 | package Oryx::Schema::XSD; | ||
| 2 | |||
| 3 | use XML::DOM::Lite qw(Document); | ||
| 4 | |||
| 5 | our $XSD_TYPES = { | ||
| 6 | 'xsd:token' => 'String', | ||
| 7 | 'xsd:string' => 'Text', | ||
| 8 | 'xsd:integer' => 'Integer', | ||
| 9 | 'xsd:float' => 'Float', | ||
| 10 | 'xsd:dateTime' => 'DateTime', | ||
| 11 | 'xsd:boolean' => 'Boolean', | ||
| 12 | 'xsd:base64Binary' => 'Binary', | ||
| 13 | }; | ||
| 14 | |||
| 15 | our $TYPE_2_XSD = { reverse %$XSD_TYPES }; | ||
| 16 | |||
| 17 | sub complexType { | ||
| 18 | my ($self, $class, $doc) = @_; | ||
| 19 | $doc ||= Document->new(); | ||
| 20 | |||
| 21 | my $complexType = $doc->createElement('xsd:complexType'); | ||
| 22 | $complexType->setAttribute("name", $class); | ||
| 23 | my $all = $doc->createElement("xsd:all"); | ||
| 24 | $complexType->appendChild($all); | ||
| 25 | |||
| 26 | foreach (values %{$class->attributes}) { | ||
| 27 | my $attribute = $doc->createElement("xsd:attribute"); | ||
| 28 | $attribute->setAttribute("name", $_->name); | ||
| 29 | $attribute->setAttribute("type", $TYPE_2_XSD->{$_->type}); | ||
| 30 | $all->appendChild($attribute); | ||
| 31 | } | ||
| 32 | |||
| 33 | foreach (values %{$class->associations}) { | ||
| 34 | my $element = $doc->createElement("xsd:element"); | ||
| 35 | $element->setAttribute("name", $_->role); | ||
| 36 | $all->appendChild($element); | ||
| 37 | |||
| 38 | if ($_->type eq "Reference") { | ||
| 39 | $element->setAttribute("type", $_->class); | ||
| 40 | } | ||
| 41 | else { | ||
| 42 | my $complexType2 = $doc->createElement("xsd:complexType"); | ||
| 43 | $element->appendChild($complexType2); | ||
| 44 | |||
| 45 | my $sequence = $doc->createElement("xsd:sequence"); | ||
| 46 | $complexType2->appendChild($sequence); | ||
| 47 | |||
| 48 | my $element2 = $doc->createElement("xsd:element"); | ||
| 49 | $element2->setAttribute("name", $_->class->name); | ||
| 50 | $element2->setAttribute("type", $_->class); | ||
| 51 | $sequence->appendChild($element2); | ||
| 52 | |||
| 53 | if ($_->type eq "Hash") { | ||
| 54 | my $attribute = $doc->createElement("xsd:attribute"); | ||
| 55 | $attribute->setAttribute("name", "keys"); | ||
| 56 | $attribute->setAttribute("type", "NMTOKENS"); | ||
| 57 | $sequence->appendChild($attribute); | ||
| 58 | } | ||
| 59 | } | ||
| 60 | } | ||
| 61 | return $complexType; | ||
| 62 | } | ||
| 63 | |||
| 64 | sub generate { | ||
| 65 | my ($self, $schema) = @_; | ||
| 66 | my $doc = Document->new(); | ||
| 67 | |||
| 68 | my $xsdschema = $doc->createElement("xsd:schema"); | ||
| 69 | $xsdschema->setAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema'); | ||
| 70 | $doc->appendChild($xsdschema); | ||
| 71 | |||
| 72 | foreach my $class ($schema->classes) { | ||
| 73 | $xsdschema->appendChild($self->complexType($class, $doc)); | ||
| 74 | } | ||
| 75 | |||
| 76 | return $doc; | ||
| 77 | } | ||
| 78 | |||
| 79 |