Base.pm 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package Playwright::Base;
  2. use strict;
  3. use warnings;
  4. use Sub::Install();
  5. use Playwright::Util();
  6. #ABSTRACT: Object representing Playwright pages
  7. no warnings 'experimental';
  8. use feature qw{signatures};
  9. =head2 DESCRIPTION
  10. Base class for each Playwright class magic'd up by Sub::Install in Playwright's BEGIN block.
  11. You probably shouldn't use this.
  12. The specification for each class can be inspected with the 'spec' property:
  13. use Data::Dumper;
  14. my $object = Playwright::Base->new(...);
  15. print Dumper($object->{spec});
  16. =head1 CONSTRUCTOR
  17. =head2 new(HASH) = (Playwright::Base)
  18. Creates a new page and returns a handle to interact with it.
  19. =head3 INPUT
  20. handle (Playwright) : Playwright object.
  21. id (STRING) : _guid returned by a response from the Playwright server with the provided type.
  22. type (STRING) : Type to actually use
  23. =cut
  24. our %methods_to_rename = (
  25. '$' => 'select',
  26. '$$' => 'selectMulti',
  27. '$eval' => 'eval',
  28. '$$eval' => 'evalMulti',
  29. );
  30. sub new ($class, %options) {
  31. my $self = bless({
  32. spec => $Playwright::spec->{$options{type}}{members},
  33. type => $options{type},
  34. guid => $options{id},
  35. ua => $options{handle}{ua},
  36. port => $options{handle}{port},
  37. }, $class);
  38. # Install the subroutines if they aren't already
  39. foreach my $method (keys(%{$self->{spec}})) {
  40. my $renamed = exists $methods_to_rename{$method} ? $methods_to_rename{$method} : $method;
  41. Sub::Install::install_sub({
  42. code => sub {
  43. my $self = shift;
  44. Playwright::Base::_request($self, args => [@_], command => $method, object => $self->{guid}, type => $self->{type} );
  45. },
  46. as => $renamed,
  47. into => $class,
  48. }) unless $self->can($method);
  49. }
  50. return ($self);
  51. }
  52. sub _request ($self, %args) {
  53. my $msg = Playwright::Util::request ('POST', 'command', $self->{port}, $self->{ua}, %args);
  54. if (ref $msg eq 'ARRAY') {
  55. @$msg = map {
  56. my $subject = $_;
  57. $subject = $Playwright::mapper{$_->{_type}}->($self,$_) if (ref $_ eq 'HASH') && $_->{_type} && exists $Playwright::mapper{$_->{_type}};
  58. $subject
  59. } @$msg;
  60. }
  61. return $Playwright::mapper{$msg->{_type}}->($self,$msg) if (ref $msg eq 'HASH') && $msg->{_type} && exists $Playwright::mapper{$msg->{_type}};
  62. return $msg;
  63. }
  64. 1;