3v4l.org

run code in 300+ PHP versions simultaneously
<?php namespace RefactoringGuru\ChainOfResponsibility\RealWorld; /** * Классический паттерн CoR объявляет для объектов, составляющих цепочку, * единственную роль – Обработчик. В нашем примере давайте проводить различие * между middleware и конечным обработчиком приложения, который выполняется, * когда запрос проходит через все объекты middleware. * * Базовый класс Middleware объявляет интерфейс для связывания объектов * middleware в цепочку. */ abstract class Middleware { /** * @var Middleware */ private $next; /** * Этот метод можно использовать для построения цепочки объектов middleware. */ public function linkWith(Middleware $next): Middleware { $this->next = $next; return $next; } /** * Подклассы должны переопределить этот метод, чтобы предоставить свои * собственные проверки. Подкласс может обратиться к родительской реализации * проверки, если сам не в состоянии обработать запрос. */ public function check(string $email, string $password): bool { if (!$this->next) { return true; } return $this->next->check($email, $password); } } /** * Это Конкретное Middleware проверяет, существует ли пользователь с указанными * учётными данными. */ class UserExistsMiddleware extends Middleware { private $server; public function __construct(Server $server) { $this->server = $server; } public function check(string $email, string $password): bool { if (!$this->server->hasEmail($email)) { echo "UserExistsMiddleware: This email is not registered!\n"; return false; } if (!$this->server->isValidPassword($email, $password)) { echo "UserExistsMiddleware: Wrong password!\n"; return false; } return parent::check($email, $password); } } /** * Это Конкретное Middleware проверяет, имеет ли пользователь, связанный с * запросом, достаточные права доступа. */ class RoleCheckMiddleware extends Middleware { public function check(string $email, string $password): bool { if ($email === "admin@example.com") { echo "RoleCheckMiddleware: Hello, admin!\n"; return true; } echo "RoleCheckMiddleware: Hello, user!\n"; return parent::check($email, $password); } } /** * Это Конкретное Middleware проверяет, не было ли превышено максимальное число * неудачных запросов авторизации. */ class ThrottlingMiddleware extends Middleware { private $requestPerMinute; private $request; private $currentTime; public function __construct(int $requestPerMinute) { $this->requestPerMinute = $requestPerMinute; $this->currentTime = time(); } /** * Обратите внимание, что вызов parent::check можно вставить как в начале * этого метода, так и в конце. * * Это даёт значительно большую свободу действий, чем простой цикл по всем * объектам middleware. Например, middleware может изменить порядок * проверок, запустив свою проверку после всех остальных. */ public function check(string $email, string $password): bool { if (time() > $this->currentTime + 60) { $this->request = 0; $this->currentTime = time(); } $this->request++; if ($this->request > $this->requestPerMinute) { echo "ThrottlingMiddleware: Request limit exceeded!\n"; die(); } return parent::check($email, $password); } } /** * Это класс приложения, который осуществляет реальную обработку запроса. Класс * Сервер использует паттерн CoR для выполнения набора различных промежуточных * проверок перед запуском некоторой бизнес-логики, связанной с запросом. */ class Server { private $users = []; /** * @var Middleware */ private $middleware; /** * Клиент может настроить сервер с помощью цепочки объектов middleware. */ public function setMiddleware(Middleware $middleware): void { $this->middleware = $middleware; } /** * Сервер получает email и пароль от клиента и отправляет запрос авторизации * в middleware. */ public function logIn(string $email, string $password): bool { if ($this->middleware->check($email, $password)) { echo "Server: Authorization has been successful!\n"; // Выполняем что-нибудь полезное для авторизованных пользователей. return true; } return false; } public function register(string $email, string $password): void { $this->users[$email] = $password; } public function hasEmail(string $email): bool { return isset($this->users[$email]); } public function isValidPassword(string $email, string $password): bool { return $this->users[$email] === $password; } } /** * Клиентский код. */ $server = new Server(); $server->register("admin@example.com", "admin_pass"); $server->register("user@example.com", "user_pass"); // Все middleware соединены в цепочки. Клиент может построить различные // конфигурации цепочек в зависимости от своих потребностей. $middleware = new ThrottlingMiddleware(2); $middleware ->linkWith(new UserExistsMiddleware($server)) ->linkWith(new RoleCheckMiddleware()); // Сервер получает цепочку из клиентского кода. $server->setMiddleware($middleware); // ... do { echo "\nEnter your email:\n"; $email = readline(); echo "Enter your password:\n"; $password = readline(); $success = $server->logIn($email, $password); } while (!$success);
Finding entry points
Branch analysis from position: 0
2 jumps found. (Code = 44) Position 1 = 44, Position 2 = 29
Branch analysis from position: 44
1 jumps found. (Code = 62) Position 1 = -2
Branch analysis from position: 29
filename:       /in/W7JTi
function name:  (null)
number of ops:  45
compiled vars:  !0 = $server, !1 = $middleware, !2 = $email, !3 = $password, !4 = $success
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
  198     0  E >   NEW                                              $5      'RefactoringGuru%5CChainOfResponsibility%5CRealWorld%5CServer'
          1        DO_FCALL                                      0          
          2        ASSIGN                                                   !0, $5
  199     3        INIT_METHOD_CALL                                         !0, 'register'
          4        SEND_VAL_EX                                              'admin%40example.com'
          5        SEND_VAL_EX                                              'admin_pass'
          6        DO_FCALL                                      0          
  200     7        INIT_METHOD_CALL                                         !0, 'register'
          8        SEND_VAL_EX                                              'user%40example.com'
          9        SEND_VAL_EX                                              'user_pass'
         10        DO_FCALL                                      0          
  204    11        NEW                                              $10     'RefactoringGuru%5CChainOfResponsibility%5CRealWorld%5CThrottlingMiddleware'
         12        SEND_VAL_EX                                              2
         13        DO_FCALL                                      0          
         14        ASSIGN                                                   !1, $10
  206    15        INIT_METHOD_CALL                                         !1, 'linkWith'
         16        NEW                                              $13     'RefactoringGuru%5CChainOfResponsibility%5CRealWorld%5CUserExistsMiddleware'
         17        SEND_VAR_EX                                              !0
         18        DO_FCALL                                      0          
         19        SEND_VAR_NO_REF_EX                                       $13
         20        DO_FCALL                                      0  $15     
  207    21        INIT_METHOD_CALL                                         $15, 'linkWith'
         22        NEW                                              $16     'RefactoringGuru%5CChainOfResponsibility%5CRealWorld%5CRoleCheckMiddleware'
         23        DO_FCALL                                      0          
         24        SEND_VAR_NO_REF_EX                                       $16
         25        DO_FCALL                                      0          
  210    26        INIT_METHOD_CALL                                         !0, 'setMiddleware'
         27        SEND_VAR_EX                                              !1
         28        DO_FCALL                                      0          
  215    29    >   ECHO                                                     '%0AEnter+your+email%3A%0A'
  216    30        INIT_NS_FCALL_BY_NAME                                    'RefactoringGuru%5CChainOfResponsibility%5CRealWorld%5Creadline'
         31        DO_FCALL                                      0  $20     
         32        ASSIGN                                                   !2, $20
  217    33        ECHO                                                     'Enter+your+password%3A%0A'
  218    34        INIT_NS_FCALL_BY_NAME                                    'RefactoringGuru%5CChainOfResponsibility%5CRealWorld%5Creadline'
         35        DO_FCALL                                      0  $22     
         36        ASSIGN                                                   !3, $22
  219    37        INIT_METHOD_CALL                                         !0, 'logIn'
         38        SEND_VAR_EX                                              !2
         39        SEND_VAR_EX                                              !3
         40        DO_FCALL                                      0  $24     
         41        ASSIGN                                                   !4, $24
  220    42        BOOL_NOT                                         ~26     !4
         43      > JMPNZ                                                    ~26, ->29
         44    > > RETURN                                                   1

Class RefactoringGuru\ChainOfResponsibility\RealWorld\Middleware:
Function linkwith:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/W7JTi
function name:  linkWith
number of ops:  7
compiled vars:  !0 = $next
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   24     0  E >   RECV                                             !0      
   26     1        ASSIGN_OBJ                                               'next'
          2        OP_DATA                                                  !0
   28     3        VERIFY_RETURN_TYPE                                       !0
          4      > RETURN                                                   !0
   29     5*       VERIFY_RETURN_TYPE                                       
          6*     > RETURN                                                   null

End of function linkwith

Function check:
Finding entry points
Branch analysis from position: 0
2 jumps found. (Code = 43) Position 1 = 5, Position 2 = 6
Branch analysis from position: 5
1 jumps found. (Code = 62) Position 1 = -2
Branch analysis from position: 6
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/W7JTi
function name:  check
number of ops:  15
compiled vars:  !0 = $email, !1 = $password
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   36     0  E >   RECV                                             !0      
          1        RECV                                             !1      
   38     2        FETCH_OBJ_R                                      ~2      'next'
          3        BOOL_NOT                                         ~3      ~2
          4      > JMPZ                                                     ~3, ->6
   39     5    > > RETURN                                                   <true>
   42     6    >   FETCH_OBJ_R                                      ~4      'next'
          7        INIT_METHOD_CALL                                         ~4, 'check'
          8        SEND_VAR_EX                                              !0
          9        SEND_VAR_EX                                              !1
         10        DO_FCALL                                      0  $5      
         11        VERIFY_RETURN_TYPE                                       $5
         12      > RETURN                                                   $5
   43    13*       VERIFY_RETURN_TYPE                                       
         14*     > RETURN                                                   null

End of function check

End of class RefactoringGuru\ChainOfResponsibility\RealWorld\Middleware.

Class RefactoringGuru\ChainOfResponsibility\RealWorld\UserExistsMiddleware:
Function __construct:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/W7JTi
function name:  __construct
number of ops:  4
compiled vars:  !0 = $server
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   54     0  E >   RECV                                             !0      
   56     1        ASSIGN_OBJ                                               'server'
          2        OP_DATA                                                  !0
   57     3      > RETURN                                                   null

End of function __construct

Function check:
Finding entry points
Branch analysis from position: 0
2 jumps found. (Code = 43) Position 1 = 8, Position 2 = 10
Branch analysis from position: 8
1 jumps found. (Code = 62) Position 1 = -2
Branch analysis from position: 10
2 jumps found. (Code = 43) Position 1 = 17, Position 2 = 19
Branch analysis from position: 17
1 jumps found. (Code = 62) Position 1 = -2
Branch analysis from position: 19
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/W7JTi
function name:  check
number of ops:  27
compiled vars:  !0 = $email, !1 = $password
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   59     0  E >   RECV                                             !0      
          1        RECV                                             !1      
   61     2        FETCH_OBJ_R                                      ~2      'server'
          3        INIT_METHOD_CALL                                         ~2, 'hasEmail'
          4        SEND_VAR_EX                                              !0
          5        DO_FCALL                                      0  $3      
          6        BOOL_NOT                                         ~4      $3
          7      > JMPZ                                                     ~4, ->10
   62     8    >   ECHO                                                     'UserExistsMiddleware%3A+This+email+is+not+registered%21%0A'
   64     9      > RETURN                                                   <false>
   67    10    >   FETCH_OBJ_R                                      ~5      'server'
         11        INIT_METHOD_CALL                                         ~5, 'isValidPassword'
         12        SEND_VAR_EX                                              !0
         13        SEND_VAR_EX                                              !1
         14        DO_FCALL                                      0  $6      
         15        BOOL_NOT                                         ~7      $6
         16      > JMPZ                                                     ~7, ->19
   68    17    >   ECHO                                                     'UserExistsMiddleware%3A+Wrong+password%21%0A'
   70    18      > RETURN                                                   <false>
   73    19    >   INIT_STATIC_METHOD_CALL                                  'check'
         20        SEND_VAR_EX                                              !0
         21        SEND_VAR_EX                                              !1
         22        DO_FCALL                                      0  $8      
         23        VERIFY_RETURN_TYPE                                       $8
         24      > RETURN                                                   $8
   74    25*       VERIFY_RETURN_TYPE                                       
         26*     > RETURN                                                   null

End of function check

Function linkwith:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/W7JTi
function name:  linkWith
number of ops:  7
compiled vars:  !0 = $next
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   24     0  E >   RECV                                             !0      
   26     1        ASSIGN_OBJ                                               'next'
          2        OP_DATA                                                  !0
   28     3        VERIFY_RETURN_TYPE                                       !0
          4      > RETURN                                                   !0
   29     5*       VERIFY_RETURN_TYPE                                       
          6*     > RETURN                                                   null

End of function linkwith

End of class RefactoringGuru\ChainOfResponsibility\RealWorld\UserExistsMiddleware.

Class RefactoringGuru\ChainOfResponsibility\RealWorld\RoleCheckMiddleware:
Function check:
Finding entry points
Branch analysis from position: 0
2 jumps found. (Code = 43) Position 1 = 4, Position 2 = 6
Branch analysis from position: 4
1 jumps found. (Code = 62) Position 1 = -2
Branch analysis from position: 6
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/W7JTi
function name:  check
number of ops:  15
compiled vars:  !0 = $email, !1 = $password
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   83     0  E >   RECV                                             !0      
          1        RECV                                             !1      
   85     2        IS_IDENTICAL                                             !0, 'admin%40example.com'
          3      > JMPZ                                                     ~2, ->6
   86     4    >   ECHO                                                     'RoleCheckMiddleware%3A+Hello%2C+admin%21%0A'
   88     5      > RETURN                                                   <true>
   90     6    >   ECHO                                                     'RoleCheckMiddleware%3A+Hello%2C+user%21%0A'
   92     7        INIT_STATIC_METHOD_CALL                                  'check'
          8        SEND_VAR_EX                                              !0
          9        SEND_VAR_EX                                              !1
         10        DO_FCALL                                      0  $3      
         11        VERIFY_RETURN_TYPE                                       $3
         12      > RETURN                                                   $3
   93    13*       VERIFY_RETURN_TYPE                                       
         14*     > RETURN                                                   null

End of function check

Function linkwith:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/W7JTi
function name:  linkWith
number of ops:  7
compiled vars:  !0 = $next
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   24     0  E >   RECV                                             !0      
   26     1        ASSIGN_OBJ                                               'next'
          2        OP_DATA                                                  !0
   28     3        VERIFY_RETURN_TYPE                                       !0
          4      > RETURN                                                   !0
   29     5*       VERIFY_RETURN_TYPE                                       
          6*     > RETURN                                                   null

End of function linkwith

End of class RefactoringGuru\ChainOfResponsibility\RealWorld\RoleCheckMiddleware.

Class RefactoringGuru\ChainOfResponsibility\RealWorld\ThrottlingMiddleware:
Function __construct:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/W7JTi
function name:  __construct
number of ops:  8
compiled vars:  !0 = $requestPerMinute
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
  108     0  E >   RECV                                             !0      
  110     1        ASSIGN_OBJ                                               'requestPerMinute'
          2        OP_DATA                                                  !0
  111     3        INIT_NS_FCALL_BY_NAME                                    'RefactoringGuru%5CChainOfResponsibility%5CRealWorld%5Ctime'
          4        DO_FCALL                                      0  $3      
          5        ASSIGN_OBJ                                               'currentTime'
          6        OP_DATA                                                  $3
  112     7      > RETURN                                                   null

End of function __construct

Function check:
Finding entry points
Branch analysis from position: 0
2 jumps found. (Code = 43) Position 1 = 8, Position 2 = 14
Branch analysis from position: 8
2 jumps found. (Code = 43) Position 1 = 19, Position 2 = 21
Branch analysis from position: 19
1 jumps found. (Code = 79) Position 1 = -2
Branch analysis from position: 21
1 jumps found. (Code = 62) Position 1 = -2
Branch analysis from position: 14
filename:       /in/W7JTi
function name:  check
number of ops:  29
compiled vars:  !0 = $email, !1 = $password
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
  122     0  E >   RECV                                             !0      
          1        RECV                                             !1      
  124     2        INIT_NS_FCALL_BY_NAME                                    'RefactoringGuru%5CChainOfResponsibility%5CRealWorld%5Ctime'
          3        DO_FCALL                                      0  $2      
          4        FETCH_OBJ_R                                      ~3      'currentTime'
          5        ADD                                              ~4      ~3, 60
          6        IS_SMALLER                                               ~4, $2
          7      > JMPZ                                                     ~5, ->14
  125     8    >   ASSIGN_OBJ                                               'request'
          9        OP_DATA                                                  0
  126    10        INIT_NS_FCALL_BY_NAME                                    'RefactoringGuru%5CChainOfResponsibility%5CRealWorld%5Ctime'
         11        DO_FCALL                                      0  $8      
         12        ASSIGN_OBJ                                               'currentTime'
         13        OP_DATA                                                  $8
  129    14    >   PRE_INC_OBJ                                              'request'
  131    15        FETCH_OBJ_R                                      ~10     'request'
         16        FETCH_OBJ_R                                      ~11     'requestPerMinute'
         17        IS_SMALLER                                               ~11, ~10
         18      > JMPZ                                                     ~12, ->21
  132    19    >   ECHO                                                     'ThrottlingMiddleware%3A+Request+limit+exceeded%21%0A'
  133    20      > EXIT                                                     
  136    21    >   INIT_STATIC_METHOD_CALL                                  'check'
         22        SEND_VAR_EX                                              !0
         23        SEND_VAR_EX                                              !1
         24        DO_FCALL                                      0  $13     
         25        VERIFY_RETURN_TYPE                                       $13
         26      > RETURN                                                   $13
  137    27*       VERIFY_RETURN_TYPE                                       
         28*     > RETURN                                                   null

End of function check

Function linkwith:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/W7JTi
function name:  linkWith
number of ops:  7
compiled vars:  !0 = $next
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   24     0  E >   RECV                                             !0      
   26     1        ASSIGN_OBJ                                               'next'
          2        OP_DATA                                                  !0
   28     3        VERIFY_RETURN_TYPE                                       !0
          4      > RETURN                                                   !0
   29     5*       VERIFY_RETURN_TYPE                                       
          6*     > RETURN                                                   null

End of function linkwith

End of class RefactoringGuru\ChainOfResponsibility\RealWorld\ThrottlingMiddleware.

Class RefactoringGuru\ChainOfResponsibility\RealWorld\Server:
Function setmiddleware:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/W7JTi
function name:  setMiddleware
number of ops:  4
compiled vars:  !0 = $middleware
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
  157     0  E >   RECV                                             !0      
  159     1        ASSIGN_OBJ                                               'middleware'
          2        OP_DATA                                                  !0
  160     3      > RETURN                                                   null

End of function setmiddleware

Function login:
Finding entry points
Branch analysis from position: 0
2 jumps found. (Code = 43) Position 1 = 8, Position 2 = 10
Branch analysis from position: 8
1 jumps found. (Code = 62) Position 1 = -2
Branch analysis from position: 10
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/W7JTi
function name:  logIn
number of ops:  13
compiled vars:  !0 = $email, !1 = $password
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
  166     0  E >   RECV                                             !0      
          1        RECV                                             !1      
  168     2        FETCH_OBJ_R                                      ~2      'middleware'
          3        INIT_METHOD_CALL                                         ~2, 'check'
          4        SEND_VAR_EX                                              !0
          5        SEND_VAR_EX                                              !1
          6        DO_FCALL                                      0  $3      
          7      > JMPZ                                                     $3, ->10
  169     8    >   ECHO                                                     'Server%3A+Authorization+has+been+successful%21%0A'
  173     9      > RETURN                                                   <true>
  176    10    > > RETURN                                                   <false>
  177    11*       VERIFY_RETURN_TYPE                                       
         12*     > RETURN                                                   null

End of function login

Function register:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/W7JTi
function name:  register
number of ops:  6
compiled vars:  !0 = $email, !1 = $password
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
  179     0  E >   RECV                                             !0      
          1        RECV                                             !1      
  181     2        FETCH_OBJ_W                                      $2      'users'
          3        ASSIGN_DIM                                               $2, !0
          4        OP_DATA                                                  !1
  182     5      > RETURN                                                   null

End of function register

Function hasemail:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/W7JTi
function name:  hasEmail
number of ops:  7
compiled vars:  !0 = $email
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
  184     0  E >   RECV                                             !0      
  186     1        FETCH_OBJ_IS                                     ~1      'users'
          2        ISSET_ISEMPTY_DIM_OBJ                         0  ~2      ~1, !0
          3        VERIFY_RETURN_TYPE                                       ~2
          4      > RETURN                                                   ~2
  187     5*       VERIFY_RETURN_TYPE                                       
          6*     > RETURN                                                   null

End of function hasemail

Function isvalidpassword:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/W7JTi
function name:  isValidPassword
number of ops:  9
compiled vars:  !0 = $email, !1 = $password
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
  189     0  E >   RECV                                             !0      
          1        RECV                                             !1      
  191     2        FETCH_OBJ_R                                      ~2      'users'
          3        FETCH_DIM_R                                      ~3      ~2, !0
          4        IS_IDENTICAL                                     ~4      !1, ~3
          5        VERIFY_RETURN_TYPE                                       ~4
          6      > RETURN                                                   ~4
  192     7*       VERIFY_RETURN_TYPE                                       
          8*     > RETURN                                                   null

End of function isvalidpassword

End of class RefactoringGuru\ChainOfResponsibility\RealWorld\Server.

Generated using Vulcan Logic Dumper, using php 8.0.0


preferences:
141.62 ms | 1031 KiB | 15 Q