11-validator.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace cx_newsletter;
  3. abstract class validator
  4. implements validator_interface {
  5. public function __construct(\wpdb $database, table_names $tables) {
  6. $this->database = $database;
  7. $this->target = null;
  8. $this->error = null;
  9. $this->prevalidate($database, $tables);
  10. }
  11. protected abstract function prevalidate(
  12. \wpdb $database,
  13. table_names $tables
  14. ) : void;
  15. public function check() : self {
  16. $result = $this->validate();
  17. $this->error = null;
  18. if ($result !== null) {
  19. $this->make_error($result);
  20. }
  21. return $this;
  22. }
  23. protected abstract function validate() : ?string;
  24. protected function is_loaded() : bool {
  25. return $this->target !== null;
  26. }
  27. protected function get_target() : mixed {
  28. if (!$this->is_loaded()) {
  29. throw new \exception('Must load target before get it.');
  30. }
  31. return $this->target;
  32. }
  33. public function load(mixed $target) : self {
  34. $this->target = $target;
  35. return $this;
  36. }
  37. protected function make_error(string $content) : void {
  38. if (!$this->is_valid()) {
  39. throw new \exception('This validator has already error.');
  40. }
  41. $this->error = $content;
  42. }
  43. public function is_valid() : bool {
  44. return $this->error === null;
  45. }
  46. public function error_on() : string {
  47. if ($this->is_valid()) {
  48. throw new \exception('Trying to load error on valid object.');
  49. }
  50. return $this->error;
  51. }
  52. private mixed $target;
  53. private ?string $error;
  54. }