| 1 | package Poz::Types::enum; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use parent 'Poz::Types::scalar'; | ||
| 5 | |||
| 6 | sub new { | ||
| 7 | my ($class, $enum) = @_; | ||
| 8 | $enum = $enum || []; | ||
| 9 | my $opts = {}; | ||
| 10 | $opts->{required_error} //= "required"; | ||
| 11 | $opts->{invalid_type_error} //= "Invalid data of enum"; | ||
| 12 | my $self = $class->SUPER::new($opts); | ||
| 13 | $self->{__enum__} = $enum; | ||
| 14 | return $self; | ||
| 15 | } | ||
| 16 | |||
| 17 | sub rule { | ||
| 18 | my ($self, $value) = @_; | ||
| 19 | return $self->{required_error} unless defined $value; | ||
| 20 | return $self->{invalid_type_error} unless grep { $_ eq $value } @{$self->{__enum__}}; | ||
| 21 | return; | ||
| 22 | } | ||
| 23 | |||
| 24 | sub as { | ||
| 25 | my ($self, $typename) = @_; | ||
| 26 | $self->{__as__} = $typename; | ||
| 27 | return $self; | ||
| 28 | } | ||
| 29 | |||
| 30 | sub exclude { | ||
| 31 | my ($self, $opts) = @_; | ||
| 32 | $opts = $opts || []; | ||
| 33 | my $enum = []; | ||
| 34 | for my $e (@{$self->{__enum__}}) { | ||
| 35 | my $found = 0; | ||
| 36 | for my $o (@{$opts}) { | ||
| 37 | if ($e eq $o) { | ||
| 38 | $found = 1; | ||
| 39 | last; | ||
| 40 | } | ||
| 41 | } | ||
| 42 | push @{$enum}, $e unless $found; | ||
| 43 | } | ||
| 44 | return __PACKAGE__->new($enum); | ||
| 45 | } | ||
| 46 | |||
| 47 | sub extract { | ||
| 48 | my ($self, $opts) = @_; | ||
| 49 | $opts = $opts || []; | ||
| 50 | my $enum = []; | ||
| 51 | for my $e (@{$self->{__enum__}}) { | ||
| 52 | for my $o (@{$opts}) { | ||
| 53 | if ($e eq $o) { | ||
| 54 | push @{$enum}, $e; | ||
| 55 | last; | ||
| 56 | } | ||
| 57 | } | ||
| 58 | } | ||
| 59 | return __PACKAGE__->new($enum); | ||
| 60 | } | ||
| 61 | |||
| 62 | 1; | ||
| 63 | |||
| 64 | =head1 NAME | ||
| 65 | |||
| 66 | Poz::Types::enum - Enum type handling for Poz | ||
| 67 | |||
| 68 | =head1 SYNOPSIS | ||
| 69 | |||
| 70 | use Poz qw/z/; | ||
| 71 | |||
| 72 | my $enum = Poz::Types::enum->new(['foo', 'bar', 'baz']); | ||
| 73 | $enum->rule('foo'); # Valid | ||
| 74 | $enum->rule('qux'); # Throws error | ||
| 75 | |||
| 76 | =head1 DESCRIPTION | ||
| 77 | |||
| 78 | Poz::Types::enum is a module for handling enumeration types within the Poz framework. It allows you to define a set of valid values and provides methods to validate, exclude, and extract these values. | ||
| 79 | |||
| 80 | =head1 METHODS | ||
| 81 | |||
| 82 | =head2 new | ||
| 83 | |||
| 84 | my $enum = Poz::Types::enum->new(\@values); | ||
| 85 | |||
| 86 | Creates a new enum object with | ||
| 87 | =head1 AUTHOR | ||
| 88 | |||
| 89 | Your Name <your.email@example.com> | ||
| 90 | |||
| 91 | =head1 LICENSE | ||
| 92 | |||
| 93 | This library is free software; you can redistribute it and/or modify | ||
| 94 | it under the same terms as Perl itself. | ||
| 95 | |||
| 96 | =cut |