API-MikroTik
view release on metacpan or search on metacpan
lib/API/MikroTik/Query.pm view on Meta::CPAN
package API::MikroTik::Query;
use Mojo::Base '-base';
use Exporter 'import';
use Scalar::Util 'blessed';
our @EXPORT_OK = ('build_query');
sub build_query {
my $query = blessed $_[0] ? $_[1] : $_[0];
return $$query if ref $query eq 'REF' && ref $$query eq 'ARRAY';
if (my $type = ref $query) {
return [_block(_ref_op($type), $query)];
}
else { return [] }
}
sub _block {
my ($logic, $items) = @_;
@{($items = [])} = map { $_ => $items->{$_} } sort keys %$items
if ref $items eq 'HASH';
my ($count, @words) = (0, ());
while (my $el = shift @$items) {
my @expr;
if (ref $el eq 'REF' && ref $$el eq 'ARRAY') {
@expr = @{$$el};
}
elsif (my $type = ref $el) {
@expr = _block(_ref_op($type), $el);
}
elsif ($el =~ /^-(?:and|or)$/) {
@expr = _block(_ref_op($el), shift @$items);
}
elsif ($el =~ /^-has(?:_not)?$/) {
push @words, '?' . ($el eq '-has_not' ? '-' : '') . (shift @$items);
$count++;
next;
}
else {
@expr = _value($el, shift @$items);
}
++$count && push @words, @expr if @expr;
}
push @words, '?#' . ($logic x ($count - 1)) if $count > 1;
return @words;
}
sub _ref_op {
return
($_[0] eq 'HASH' || $_[0] eq '-and') ? '&'
: ($_[0] eq 'ARRAY' || $_[0] eq '-or') ? '|'
: '';
}
sub _value {
my ($name, $val) = @_;
my $type = ref $val;
if ($type eq 'HASH') {
( run in 2.230 seconds using v1.01-cache-2.11-cpan-39bf76dae61 )