From Code to Community: Sponsoring The Perl and Raku Conference 2025 Learn more

use overload (
fallback => 1,
'""' => 'SCALAR',
);
require Tie::Hash;
our @ISA = qw(Twilio Tie::StdHash);
sub SCALAR {
my $self = shift;
my $pack = caller;
my @call = caller(0);
return $self if $pack =~ /^Twilio(::\w+)*$/;
if (exists $self->{$self->default_property}) {
return $self->{$self->default_property};
}
$self;
}
sub default_property {
'sid'
}
sub new {
my $class = shift;
my $self = {};
tie %$self, $class;
merge %$self, @_;
bless $self, $class;
$self->Objects->{subresources} = [];
if (exists $self->{Twilio}) {
$self->Objects->{Twilio} = delete $self->{Twilio};
}
$self->classify_subresources;
$self;
}
sub classify_subresources {
my $self = shift;
my $uris = $self->{subresource_uris};
if ($uris and ref($uris) and ref($uris) eq 'HASH') {
$uris = { %{$self->{subresource_uris}} };
for my $res (keys %$uris) {
my $res_class = $self->get_mapping(modern_to_camel $res);
eval {
$self->Objects->{modern_to_camel $res} = $res_class->new (
Twilio => $self->Twilio,
uri => $uris->{$res},
);
push @{$self->Objects->{subresources}}, modern_to_camel $res;
};
if (my $e = $@) {
$self->die("While creating ".ref($self)." subresource class:\n$e\nInitial object was:\n".dumped($self)."\n...");
}
}
@{$self->Objects->{subresources}} = sort @{$self->Objects->{subresources}};
}
delete $self->{subresource_uris};
}
sub update {
my $self = shift;
my $r = $self->Twilio->post($self->root_url.$self->{uri}, { @_ });
for my $new (keys %$r) {
for my $old (keys %$self) {
delete $self->{$old} unless exists $r->{$old};
}
$self->{$new} = $r->{$new};
}
$self->classify_subresources;
$self;
}
sub delete {
my $self = shift;
my $url = $self->root_url.$self->uri;
my $r = $self->Twilio->ua->delete($url);
if ($r->is_success) {
return 1;
} else {
$self->die("Error deleting $url:\n".$r->status_line."\n".$r->decoded_content);
}
}
sub STORE {
my ($self, $k, $v) = @_;
my @call = caller(0);
if ($self->isa($call[0]) or $call[0] =~ /^Perlmazing(::\w+)*/) {
$self->{$k} = $v;
} else {
$self->update($k => $v);
}
$self;
}
sub resources {
my $self = shift;
@{$self->Objects->subresources};
}
sub list {
my $self = shift;
$self->die(ref($self).' is a resource, not a collection. Only collections have the method \'list\'');
}
1;