Skip to content

Commit

Permalink
Implement replace method
Browse files Browse the repository at this point in the history
  • Loading branch information
reneeb authored and oalders committed Jul 13, 2022
1 parent 8e39ba5 commit 4c06900
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 6 deletions.
4 changes: 2 additions & 2 deletions lib/PPI/Element.pm
Expand Up @@ -593,8 +593,8 @@ one being replaced.

sub replace {
my $self = ref $_[0] ? shift : return undef;
_INSTANCE(shift, ref $self) or return undef;
die "The ->replace method has not yet been implemented";
my $replace = _INSTANCE(shift, ref $self) or return undef;
$self->parent->replace_child( $self, $replace );
}

=pod
Expand Down
27 changes: 25 additions & 2 deletions lib/PPI/Node.pm
Expand Up @@ -522,6 +522,25 @@ sub remove_child {
$child;
}

=head2 replace_child $Element, $Replacement
If successful, returns the replace element. Otherwise, returns C<undef>.
=cut

sub replace_child {
my $self = shift;

my $child = _INSTANCE(shift, 'PPI::Element') or return undef;
my $replacement = _INSTANCE(shift, 'PPI::Element') or return undef;

my $success = $self->__replace_child( $child, $replacement );

return if !$success;
return $replacement;
}


=pod
=head2 prune $class | \&wanted
Expand Down Expand Up @@ -732,14 +751,18 @@ sub __replace_child {
my $self = shift;
my $key = refaddr shift;
my $p = List::Util::first {
refaddr $self->{children}[$_] == $key
} 0..$#{$self->{children}};
refaddr $self->{children}[$_] == $key
} 0..$#{$self->{children}};

return if !defined $p;

foreach ( @_ ) {
Scalar::Util::weaken(
$_PARENT{refaddr $_} = $self
);
}
splice( @{$self->{children}}, $p, 1, @_ );
delete $_PARENT{$key};
1;
}

Expand Down
2 changes: 0 additions & 2 deletions t/ppi_element_replace.t
Expand Up @@ -8,8 +8,6 @@ use PPI::Test::pragmas;
use PPI::Document ();
use Test::More;

local $TODO = 'Not yet implemented';

__REPLACE: {
my $Document = PPI::Document->new( \"print 'Hello World';" );
isa_ok( $Document, 'PPI::Document' );
Expand Down

0 comments on commit 4c06900

Please sign in to comment.