File: Graph.pm

package info (click to toggle)
libclass-prototyped-perl 1.11-3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 544 kB
  • sloc: perl: 1,448; makefile: 8
file content (78 lines) | stat: -rwxr-xr-x 1,766 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# Graph an object structure using GraphViz.
use Class::Prototyped;
use GraphViz;
use IO::File;

package Class::Prototyped::Mirror;

my %graphOpts = (
	R => 1,        # H or V orientation
	i => 'png',    # output format
	u => 0,        # output image map?
	s => 1,        # what kind of image map?
);

sub graphOptions {
	shift if ref( $_[0] );
	%graphOpts = ( %graphOpts, @_ );
}

# look familiar?
sub visitAllParents {
	my $mirror   = shift;
	my $sub      = shift;
	my $userData = shift;
	my $stack    = shift || [];
	my $seen     = shift || {};

	push ( @$stack, $mirror );
	$sub->( $parentMirror, $userData, $stack );
	foreach my $parent ( $mirror->parents ) {
		next unless UNIVERSAL::can( $parent, 'reflect' );
		my $parentMirror = $parent->reflect;
		$parentMirror->visitAllParents( $sub, $userData, $stack, $seen );
	}
	pop (@$stack);
}

sub _graphOneObject {
	my $mirror   = shift;
	my $data     = shift;
	my $g        = $data->[0];
	my $slotName = $data->[1];
	my $stack    = shift;

	my $name = $stack->[-1]->getSlot($slotName);
	$g->add_node($name);

	my $fromName;

	if ( @$stack >= 2 ) {
		$fromName = $stack->[-2]->getSlot($slotName);
		$g->add_edge( $fromName, $name );
	}
}

sub graph {
	shift if UNIVERSAL::isa( $_[0], 'Class::Prototyped::Mirror' );
	my $slotName = shift;

	my $outfile = 'graph.png';
	my $g = GraphViz->new( rankdir => $graphOpts{R} || 0 );

	foreach my $obj (@_) {
		my $mirror = $obj->reflect;
		$mirror->visitAllParents( \&_graphOneObject, [ $g, $slotName ] );
	}

	my $output = IO::File->new( $outfile, 'w' )
	  or die "can't open $outfile: $!\n";
	$output->print( eval "\$g->as_$graphOpts{i}()" );
	$output->close();

	if ( $graphOpts{u} ) {
		STDOUT->print( exists( $graphOpts{s} ) ? $g->as_imap : $g->as_ismap() );
	}
}

1;