FollowList.pm

filter: Statementstmt 83.3% 10 / 12 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 87.5% 14 / 16 CC 1 SCAR 0.7
CC
1
Cov
83%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« FileMetadata.pm ↑ Summary Label.pm »
1 package Net::Nostr::FollowList;
2  
3 1 ▶use strictures 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 1 ▶use Net::Nostr::_ConstructorArgs ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 1 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 0 ▶use Net::Nostr::Event;
Subroutine BEGIN: called CC=1 SCAR=2.6
9  
10 my $HEX64 = qr/\A[0-9a-f]{64}\z/;
11  
12 use Class::Tiny qw(_follows);
13  
14 sub new {
15 my $class = shift;
16 my %args = Net::Nostr::_ConstructorArgs::normalize(@_);
17 croak "unknown argument(s): " . join(', ', sort keys %args) if %args;
18 my $self = bless {}, $class;
19 $self->_follows([]);
20 return $self;
21 }
22  
23 sub from_event {
24 my ($class, $event) = @_;
25 croak "event must be kind 3" unless $event->kind == 3;
26 my $self = $class->new;
27 for my $tag (@{$event->tags}) {
28 next unless $tag->[0] eq 'p';
29 push @{$self->_follows}, {
30 pubkey => $tag->[1],
31 relay => $tag->[2] // '',
32 petname => $tag->[3] // '',
33 };
34 }
35 return $self;
36 }
37  
38 sub add {
39 my ($self, $pubkey, %opts) = @_;
40 croak "pubkey must be 64-char lowercase hex"
41 unless defined $pubkey && $pubkey =~ $HEX64;
42 my $entry = {
43 pubkey => $pubkey,
44 relay => $opts{relay} // '',
45 petname => $opts{petname} // '',
46 };
47 # replace existing entry in place
48 for my $i (0 .. $#{$self->_follows}) {
49 if ($self->_follows->[$i]{pubkey} eq $pubkey) {
50 $self->_follows->[$i] = $entry;
51 return $self;
52 }
53 }
54 push @{$self->_follows}, $entry;
55 return $self;
56 }
57  
58 sub remove {
59 my ($self, $pubkey) = @_;
60 $self->_follows([grep { $_->{pubkey} ne $pubkey } @{$self->_follows}]);
61 return $self;
62 }
63  
64 sub contains {
65 my ($self, $pubkey) = @_;
66 for my $entry (@{$self->_follows}) {
67 return 1 if $entry->{pubkey} eq $pubkey;
68 }
69 return 0;
70 }
71  
72 sub count {
73 my ($self) = @_;
74 return scalar @{$self->_follows};
75 }
76  
77 sub follows {
78 my ($self) = @_;
79 return @{$self->_follows};
80 }
81  
82 sub to_tags {
83 my ($self) = @_;
84 return [map { ['p', $_->{pubkey}, $_->{relay}, $_->{petname}] } @{$self->_follows}];
85 }
86  
87 sub to_event {
88 my $self = shift;
89 my %args = Net::Nostr::_ConstructorArgs::normalize(@_);
90 return Net::Nostr::Event->new(
91 %args,
92 kind => 3,
93 content => '',
94 tags => $self->to_tags,
95 );
96 }
97  
98 1;
99  
100 __END__
« FileMetadata.pm ↑ Summary Label.pm »