File Coverage

blib/lib/IOC/Visitor/SearchForContainer.pm
Criterion Covered Total %
statement 34 34 100.0
branch 8 8 100.0
condition 4 6 66.6
subroutine 9 9 100.0
pod 2 2 100.0
total 57 59 96.6


line stmt bran cond sub pod time code
1              
2             package IOC::Visitor::SearchForContainer;
3              
4 11     11   2175 use strict;
  11         25  
  11         487  
5 11     11   67 use warnings;
  11         89  
  11         687  
6              
7             our $VERSION = '0.03';
8              
9 11     11   67 use Scalar::Util qw(blessed);
  11         21  
  11         885  
10              
11 11     11   3991 use IOC::Interfaces;
  11         21  
  11         336  
12 11     11   60 use IOC::Exceptions;
  11         20  
  11         311  
13              
14 11     11   81 use base 'IOC::Visitor';
  11         59  
  11         13659  
15              
16             sub new {
17 8     8 1 1810 my ($_class, $container_name) = @_;
18 8 100       24 ($container_name)
19             || throw IOC::InsufficientArguments "You must provide a name of a container to find";
20 7   33     30 my $class = ref($_class) || $_class;
21 7         21 my $visitor = {
22             container_to_find => $container_name
23             };
24 7         26 bless($visitor, $class);
25 7         24 return $visitor;
26             }
27              
28             sub visit {
29 10     10 1 4010 my ($self, $container) = @_;
30 10 100 100     92 (blessed($container) && $container->isa('IOC::Container'))
31             || throw IOC::InsufficientArguments "You must provide an IOC::Container object to search";
32 6         14 my $container_to_find = $self->{container_to_find};
33 6         16 return $self->_recursiveSearch($container, $container_to_find);
34             }
35              
36             sub _recursiveSearch {
37 9     9   14 my ($self, $container, $container_to_find) = @_;
38             # if we have it stored, then return it
39 9 100       25 return $container->getSubContainer($container_to_find)
40             if $container->hasSubContainer($container_to_find);
41             # otherwise, loop through all the sub-containers
42             # sort the names too, which will make sure the
43             # search will roughly take the same amount of time
44             # each time we do it, otherwise we are at the
45             # mercy of the hash ordering
46 8         30 foreach my $sub_container_name (sort $container->getSubContainerList()) {
47             # otherwise we need to search the next level
48 12         31 my $sub_container = $container->getSubContainer($sub_container_name);
49 12 100       27 $self->_recursiveSearch($sub_container, $container_to_find)
50             if $sub_container->hasSubContainers();
51             }
52 8         25 return undef;
53             }
54              
55             1;
56              
57             __END__