| 1 | package Oryx::Schema::Generator; | ||
| 2 | |||
| 3 | use Oryx::Schema::Stub; | ||
| 4 | use XML::DOM::Lite qw(:constants); | ||
| 5 | |||
| 6 | sub new { | ||
| 7 | my ($class, $xmldoc) = @_; | ||
| 8 | |||
| 9 | my $self = bless { xmldoc => $xmldoc }, $class; | ||
| 10 | $self->{_classes} = { }; | ||
| 11 | |||
| 12 | foreach (@{ $xmldoc->documentElement->childNodes }) { | ||
| 13 | $self->{_classes}->{$_->getAttribute("name")} = $_; | ||
| 14 | } | ||
| 15 | |||
| 16 | return $self; | ||
| 17 | } | ||
| 18 | |||
| 19 | sub Oryx::Schema::Generator::INC { | ||
| 20 | my ($self, $filename) = @_; | ||
| 21 | my $class = "$filename"; | ||
| 22 | $class =~ s/\//::/g; | ||
| 23 | $class =~ s/\.pm$//; | ||
| 24 | my $node = $self->{_classes}->{$class}; | ||
| 25 | |||
| 26 | if ( $node ) { | ||
| 27 | my $stub = $INC{'Oryx/Schema/Stub.pm'}; | ||
| 28 | $INC{$filename} = $stub; | ||
| 29 | |||
| 30 | $self->load_class($class, $node); | ||
| 31 | open DEVNULL, "<$stub"; | ||
| 32 | return \*DEVNULL; | ||
| 33 | } | ||
| 34 | |||
| 35 | return undef; | ||
| 36 | } | ||
| 37 | |||
| 38 | sub load_class { | ||
| 39 | my ($self, $class, $node) = @_; | ||
| 40 | my $pkg = qq{ | ||
| 41 | package $class; | ||
| 42 | use base qw(Oryx::Class); | ||
| 43 | }; | ||
| 44 | $self->generate($class, $node); | ||
| 45 | eval $pkg; die $@ if $@; | ||
| 46 | } | ||
| 47 | |||
| 48 | sub generate { | ||
| 49 | my ($self, $class, $node) = @_; | ||
| 50 | |||
| 51 | my $schema = { attributes => [ ], associations => [ ] }; | ||
| 52 | no strict 'refs'; | ||
| 53 | foreach my $n (@{$node->childNodes}) { | ||
| 54 | if ($n->nodeType == ELEMENT_NODE) { | ||
| 55 | if ($n->nodeName eq 'Attribute') { | ||
| 56 | push @{$schema->{attributes}}, { | ||
| 57 | name => $n->getAttribute('name'), | ||
| 58 | type => $n->getAttribute('type'), | ||
| 59 | }; | ||
| 60 | } elsif ($n->nodeName eq 'Association') { | ||
| 61 | push @{$schema->{associations}}, { | ||
| 62 | class => $n->getAttribute('class'), | ||
| 63 | role => $n->getAttribute('role'), | ||
| 64 | type => $n->getAttribute('type'), | ||
| 65 | }; | ||
| 66 | } elsif ($n->nodeName eq 'Parent') { | ||
| 67 | push @{$class.'::ISA'}, $n->getAttribute('class'); | ||
| 68 | } | ||
| 69 | } | ||
| 70 | } | ||
| 71 | no warnings 'once'; | ||
| 72 | ${$class.'::schema'} = $schema; | ||
| 73 | return $schema; | ||
| 74 | } | ||
| 75 | |||
| 76 | sub requireAll { | ||
| 77 | my $self = shift; | ||
| 78 | foreach (keys %{$self->{_classes}}) { | ||
| 79 | eval "use $_"; die $@ if $@; | ||
| 80 | } | ||
| 81 | } | ||
| 82 | |||
| 83 | 1; |