Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Есть массив данных о комментарии:
- $arComment = [
- 'user_id' => 102365,
- '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.',
- 'article_id' => 137
- ];
- Необходимо проверить этот массив данных на 3 бизнес-правила используя паттерн "Цепочка обязанностей" (https://refactoring.guru/ru/design-patterns/chain-of-responsibility/php/example#example-0):
- 1. 'user_id' - целочисленное и больше 0
- 2. 'text' - не пустое поле, но длина не превышает 1000 символов
- 3. 'article_id' - существует (предположим, что мы для этого хотим сделать GET-апрос на адрес http://ya.ru?article_id=<article_id из массива>, если API вернет 200, значит существует)
- <?php
- interface HandlerInterface {
- public function handle(array $arComment):void;
- public function setNext(HandlerInterface $handler):void;
- }
- abstract class Handler implent HandlerInterface {
- protected HandlerInterface $next;
- public function setNext(HandlerInterface $handler):void {
- $this->next = $next;
- }
- }
- class UserIdValidator extends Handler {
- $KeyRequired = 'user_id';
- public function handle(array $arComment):void
- {
- $item = arComment[$KeyRequired];
- $next($arComment);
- return;
- }
- }
- class TextValidator extends Handler {
- $KeyRequired = 'text';
- public function handle(array $arComment):void
- {
- $item = arComment[$KeyRequired];
- // Rule of validation
- $next($arComment);
- return;
- }
- }
- class ArticleValidator extends Handler {
- $KeyRequired = 'article_id';
- public function handle(array $arComment):void
- {
- $item = arComment[$KeyRequired];
- // Rule of validation
- $next($arComment);
- return;
- }
- }
- class ChainController
- {
- public Process($article) : void
- {
- $validator = new UserIdValidator();
- $validator->setNext(new TextValidator())->setNext(new ArticleValidator());
- $validator->handle($article);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement