Advertisement
Inverth

Chain Of Responsibilities - Цепочка обязанностей

Jul 14th, 2021
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.41 KB | None | 0 0
  1. Есть массив данных о комментарии:
  2.  
  3. $arComment = [
  4.   'user_id' => 102365,
  5.   'text' => 'Following extensive negotiations, the meeting participants agreed to terms of reference for the special programme, although some text remained within square brackets to indicate that agreement had not been reached with regard to that text.',
  6.   'article_id' => 137
  7.  ];
  8.  
  9.  Необходимо проверить этот массив данных на 3 бизнес-правила используя паттерн "Цепочка обязанностей" (https://refactoring.guru/ru/design-patterns/chain-of-responsibility/php/example#example-0):
  10.  1. 'user_id' - целочисленное и больше 0
  11.  2. 'text' - не пустое поле, но длина не превышает 1000 символов
  12.  3. 'article_id' - существует (предположим, что мы для этого хотим сделать GET-апрос на адрес http://ya.ru?article_id=<article_id из массива>, если API вернет 200, значит существует)
  13.  
  14.  
  15. <?php
  16.  
  17. interface HandlerInterface {
  18.     public function handle(array $arComment):void;
  19.  
  20.     public function setNext(HandlerInterface $handler):void;
  21. }
  22.  
  23. abstract class Handler implent HandlerInterface {
  24.   protected HandlerInterface $next;
  25.   public function setNext(HandlerInterface $handler):void {
  26.     $this->next = $next;
  27.   }
  28. }
  29.  
  30. class UserIdValidator extends Handler {
  31.     $KeyRequired = 'user_id';
  32.  
  33.     public function handle(array $arComment):void
  34.     {
  35.         $item = arComment[$KeyRequired];
  36.  
  37.         $next($arComment);
  38.         return;
  39.     }
  40. }
  41.  
  42. class TextValidator extends Handler {
  43.     $KeyRequired = 'text';
  44.  
  45.     public function handle(array $arComment):void
  46.     {
  47.         $item = arComment[$KeyRequired];
  48.         // Rule of validation
  49.  
  50.         $next($arComment);
  51.         return;
  52.     }
  53. }
  54.  
  55. class ArticleValidator extends Handler {
  56.     $KeyRequired = 'article_id';
  57.  
  58.     public function handle(array $arComment):void
  59.     {
  60.         $item = arComment[$KeyRequired];
  61.         // Rule of validation
  62.  
  63.         $next($arComment);
  64.         return;
  65.     }
  66. }
  67.  
  68.  
  69. class ChainController
  70. {
  71.     public Process($article) : void
  72.     {
  73.         $validator = new UserIdValidator();
  74.         $validator->setNext(new TextValidator())->setNext(new ArticleValidator());
  75.         $validator->handle($article);
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement