diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 888645750..802a12cff 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,10 +13,10 @@ permissions: jobs: testsuite: - uses: ADmad/.github/.github/workflows/testsuite-with-db.yml@master + uses: ADmad/.github/.github/workflows/testsuite-with-db.yml@cake6 secrets: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} cs-stan: - uses: ADmad/.github/.github/workflows/cs-stan.yml@master + uses: ADmad/.github/.github/workflows/cs-stan.yml@cake6 secrets: inherit diff --git a/.phive/phars.xml b/.phive/phars.xml index a1627f6bc..c93b53797 100644 --- a/.phive/phars.xml +++ b/.phive/phars.xml @@ -1,4 +1,4 @@ - + diff --git a/composer.json b/composer.json index d1b8fdcda..b4e36b9b6 100644 --- a/composer.json +++ b/composer.json @@ -38,14 +38,14 @@ } ], "require": { - "php": ">=8.1", - "cakephp/cakephp": "^5.0" + "php": ">=8.5", + "cakephp/cakephp": "^6.0@dev" }, "require-dev": { - "friendsofcake/cakephp-test-utilities": "^3.0", - "friendsofcake/search": "^7.0", - "phpunit/phpunit": "^10.5.58 || ^11.5.3 || ^12.4", - "cakephp/cakephp-codesniffer": "^5.3" + "friendsofcake/cakephp-test-utilities": "dev-cake6", + "friendsofcake/search": "dev-cake6", + "phpunit/phpunit": "^13.0", + "cakephp/cakephp-codesniffer": "^6.0@dev" }, "autoload": { "psr-4": { @@ -85,5 +85,7 @@ "allow-plugins": { "dealerdirect/phpcodesniffer-composer-installer": true } - } + }, + "minimum-stability": "dev", + "prefer-stable": true } diff --git a/docs/_code/action_index.php b/docs/_code/action_index.php index d2468aff0..1083e2217 100644 --- a/docs/_code/action_index.php +++ b/docs/_code/action_index.php @@ -8,30 +8,30 @@ class Index extends BaseAction * * @return \Cake\Http\Response|null */ - protected function _handle(): ?Response + protected function handleRequest(): ?Response { - [$finder, $options] = $this->_extractFinder(); - $query = $this->_model()->find($finder, ...$options); - $subject = $this->_subject(['success' => true, 'query' => $query]); + [$finder, $options] = $this->extractFinder(); + $query = $this->model()->find($finder, ...$options); + $subject = $this->subject(['success' => true, 'query' => $query]); - $this->_trigger('beforePaginate', $subject); + $this->trigger('beforePaginate', $subject); try { - $items = $this->_controller()->paginate($subject->query); + $items = $this->controller()->paginate($subject->query); } catch (NotFoundException $e) { /** @var \Cake\Core\Exception\CakeException $previous */ $previous = $e->getPrevious(); $pagingParams = $previous->getAttributes()['pagingParams']; - $url = Router::reverseToArray($this->_request()); + $url = Router::reverseToArray($this->request()); $url['?']['page'] = $pagingParams['pageCount']; - return $this->_controller()->redirect($url); + return $this->controller()->redirect($url); } $subject->set(['entities' => $items]); - $this->_trigger('afterPaginate', $subject); - $this->_trigger('beforeRender', $subject); + $this->trigger('afterPaginate', $subject); + $this->trigger('beforeRender', $subject); return null; } diff --git a/docs/_code/listener_example.php b/docs/_code/listener_example.php index 45ac91677..4b3da9c22 100644 --- a/docs/_code/listener_example.php +++ b/docs/_code/listener_example.php @@ -25,7 +25,8 @@ public function implementedEvents(): array */ public function beforeRender(\Cake\Event\EventInterface $event) { - $this->_response()->header('X-Powered-By', 'CRUD 4.0'); + $response = $this->response()->withHeader('X-Powered-By', 'CRUD 4.0'); + $this->controller()->setResponse($response); } } diff --git a/docs/_partials/events/after_bulk.rst b/docs/_partials/events/after_bulk.rst index cc58fbaad..faa2fdc6e 100644 --- a/docs/_partials/events/after_bulk.rst +++ b/docs/_partials/events/after_bulk.rst @@ -1,11 +1,11 @@ Crud.afterBulk ^^^^^^^^^^^^^^ -This event is emitted after calling ``_bulk()`` on a Bulk Crud action. +This event is emitted after calling ``bulk()`` on a Bulk Crud action. The :ref:`Crud Subject ` contains two keys: -- **success** if ``true`` the ``_bulk()`` call succeeded, ``false`` otherwise +- **success** if ``true`` the ``bulk()`` call succeeded, ``false`` otherwise - **ids** A list of ids of entities, from the request data - **repository** An instance of the ``Repository`` (``Table``) which the query will be executed against. - **query** A ``Query`` object from the ``Repository`` where ``$PrimaryKey => $IdFromRequest`` is already added to the conditions. diff --git a/docs/_partials/events/before_bulk.rst b/docs/_partials/events/before_bulk.rst index 9699d9d53..9cff5efa0 100644 --- a/docs/_partials/events/before_bulk.rst +++ b/docs/_partials/events/before_bulk.rst @@ -1,7 +1,7 @@ Crud.beforeBulk ^^^^^^^^^^^^^^^ -This event is emitted before ``_bulk()`` is called on a Bulk Crud action. +This event is emitted before ``bulk()`` is called on a Bulk Crud action. The :ref:`Crud Subject ` contains the following keys: diff --git a/docs/actions.rst b/docs/actions.rst index 8fa7310d4..174cd61b2 100644 --- a/docs/actions.rst +++ b/docs/actions.rst @@ -55,12 +55,12 @@ namespace your action class accordingly. Request Methods --------------- -Next is the method ``_handle``. A Crud Action can respond to any HTTP verb +Next is the method ``handleRequest``. A Crud Action can respond to any HTTP verb (``GET``, ``POST``, ``PUT``, ``DELETE``). -Each HTTP verb can be implemented as method, e.g. ``_get()`` for HTTP GET, -``_post()`` for HTTP POST and ``_put()`` for HTTP PUT. +Each HTTP verb can be implemented as method, e.g. ``handleGet()`` for HTTP GET, +``handlePost()`` for HTTP POST and ``handlePut()`` for HTTP PUT. -If no HTTP verb specific method is found in the class, ``_handle()`` will be +If no HTTP verb specific method is found in the class, ``handleRequest()`` will be executed. .. literalinclude:: _code/action_index.php @@ -68,15 +68,15 @@ executed. :linenos: :emphasize-lines: 6-10 -You can treat the ``_handle()`` method as a catch-all, if your crud action +You can treat the ``handleRequest()`` method as a catch-all, if your crud action wants to process all possible HTTP verbs. An advantage of this setup is that you can separate the logic on a request type level instead of mixing all of the logic into one big block of code. -For example the :doc:`Edit Crud Action` implements ``_get()``, -``_post()`` and ``_put()`` methods. The ``_get()`` method simply reads the entity -from the database and passes it to the form, while ``_put()`` handles validation +For example the :doc:`Edit Crud Action` implements ``handleGet()``, +``handlePost()`` and ``handlePut()`` methods. The ``handleGet()`` method simply reads the entity +from the database and passes it to the form, while ``handlePut()`` handles validation and saving the entity back to the database. Events & Subject @@ -87,10 +87,10 @@ change its state between emitted events. This object is a ``Crud\Event\Subject`` The real beauty of Crud is the events and the flexibility they provide. -All calls to ``_trigger()`` emit an event, that you as a developer can listen to and inject your own application logic. +All calls to ``trigger()`` emit an event, that you as a developer can listen to and inject your own application logic. These events are in no way magical, they are simply normal -`CakePHP events `_, dispatched like all -other `events in CakePHP `_. +`CakePHP events `_, dispatched like all +other `events in CakePHP `_. You can for example listen for the ``beforePaginate`` event and add conditions to your pagination query, just with a few lines of code. Those few lines of code is what makes your application unique. The rest of the code you would diff --git a/docs/actions/bulk.rst b/docs/actions/bulk.rst index b88ebdbac..e440bafef 100644 --- a/docs/actions/bulk.rst +++ b/docs/actions/bulk.rst @@ -10,15 +10,15 @@ Three BulkAction classes exist in the core: - :doc:`SetValue`: Sets a field to a value for a set of entities - :doc:`Toggle`: Toggles the value of a boolean field for a set of entities -To create your own BulkAction, simply create a new action class with a ``_bulk`` -method. This method takes a CakePHP ``Query`` object as its first argument +To create your own BulkAction, simply create a new action class with a ``bulk`` +method. This method takes a ``Cake\Database\Query`` object as its first argument .. code-block:: phpinline update()->set(['approved' => true]); $statement = $query->execute(); diff --git a/docs/actions/custom.rst b/docs/actions/custom.rst index be8d4f55a..aa2512ea8 100644 --- a/docs/actions/custom.rst +++ b/docs/actions/custom.rst @@ -4,10 +4,10 @@ Custom Action Classes If you need to customize an action for any reason, you can create your own custom Crud action class. A Crud Action can respond to any ``HTTP`` verb (``GET``, ``POST``, ``PUT``, ``DELETE``). -Each HTTP verb can be implemented as method, e.g. ``_get()`` for HTTP ``GET``, -``_post()`` for HTTP ``POST`` and ``_put()`` for HTTP ``PUT``. +Each HTTP verb can be implemented as method, e.g. ``handleGet()`` for HTTP ``GET``, +``handlePost()`` for HTTP ``POST`` and ``handlePut()`` for HTTP ``PUT``. -If no HTTP verb specific method is found in the class, ``_handle()`` will be executed. +If no HTTP verb specific method is found in the class, ``handleRequest()`` will be executed. A default custom index action might be as simple as the following: @@ -27,7 +27,7 @@ A default custom index action might be as simple as the following: * * @var array */ - protected array $_defaultConfig = [ + protected array $defaultConfig = [ 'enabled' => true, 'scope' => 'table', 'findMethod' => 'all', @@ -49,10 +49,10 @@ A default custom index action might be as simple as the following: * * @return void */ - protected function _handle(): void + protected function handleRequest(): void { - $query = $this->_table()->find($this->findMethod()); - $items = $this->_controller()->paginate($query); + $query = $this->model()->find($this->findMethod()); + $items = $this->controller()->paginate($query); } } diff --git a/docs/configuration.rst b/docs/configuration.rst index 7fc858b67..e84cf90a0 100644 --- a/docs/configuration.rst +++ b/docs/configuration.rst @@ -242,7 +242,7 @@ The easiest way to achieve this is to create an ``AppController`` for the prefix extend from that one. Then you can configure Crud in your prefixes ``AppController``. Let's look at an example, using an ``api`` prefix. For this example, we'll assume your -`prefix routing `_ is already configured. +`prefix routing `_ is already configured. First step is to create your new ``ApiAppController`` which should be in ``src/Controller/Api/``. diff --git a/docs/listeners.rst b/docs/listeners.rst index 47b824be5..44886f2bb 100644 --- a/docs/listeners.rst +++ b/docs/listeners.rst @@ -16,7 +16,7 @@ The Anatomy Of A Listener ========================= The listener system is simply the -`Events System `_ from +`Events System `_ from CakePHP, and all the official documentation and usage also applies to Crud. The Crud event system uses two methods ``trigger()`` and ``on()`` to interface @@ -47,7 +47,7 @@ as an action creator. Implemented Events ------------------ -As documented in the `CakePHP Events System `_ +As documented in the `CakePHP Events System `_ all listeners must contain a ``implementedEvents`` method. In this example, we simply request that ``beforeRender`` in our class is executed diff --git a/docs/listeners/api-pagination.rst b/docs/listeners/api-pagination.rst index e86d1d826..e1eb48e87 100644 --- a/docs/listeners/api-pagination.rst +++ b/docs/listeners/api-pagination.rst @@ -73,7 +73,7 @@ Configuration ------------- Configure this listener by setting the -`CakePHP Pagination `_ options directly to the +`CakePHP Pagination `_ options directly to the query object. .. code-block:: php diff --git a/docs/listeners/api.rst b/docs/listeners/api.rst index df9181cb7..bfa6a6c85 100644 --- a/docs/listeners/api.rst +++ b/docs/listeners/api.rst @@ -9,7 +9,7 @@ Setup Routing ^^^^^^^ -You need to tell the ``Router`` to `parse extensions `_ else it won't be able to process and render ``json`` and ``xml`` +You need to tell the ``Router`` to `parse extensions `_ else it won't be able to process and render ``json`` and ``xml`` URL extension. Controller diff --git a/docs/listeners/custom.rst b/docs/listeners/custom.rst index a2b3800ee..672710c3e 100644 --- a/docs/listeners/custom.rst +++ b/docs/listeners/custom.rst @@ -7,7 +7,7 @@ Using a controller as a listener -------------------------------- We override the ``implementedEvents()`` method in the controller, and bind -the ``Crud.beforeFind`` event to the ``_beforeFind()`` method in the controller. +the ``Crud.beforeFind`` event to the ``beforeFind()`` method in the controller. .. code-block:: phpinline @@ -19,11 +19,11 @@ the ``Crud.beforeFind`` event to the ``_beforeFind()`` method in the controller. public function implementedEvents(): array { return parent::implementedEvents() + [ - 'Crud.beforeFind' => '_beforeFind' + 'Crud.beforeFind' => 'beforeFind' ]; } - public function _beforeFind(\Cake\Event\EventInterface $event, \Cake\ORM\Query\SelectQuery $query): void + public function beforeFind(\Cake\Event\EventInterface $event, \Cake\ORM\Query\SelectQuery $query): void { ... } @@ -48,11 +48,11 @@ Creating your own listener class is very similar to using a controller as a list public function implementedEvents(): array { return [ - 'Crud.beforeFind' => '_beforeFind' + 'Crud.beforeFind' => 'beforeFind' ]; } - public function _beforeFind(Event $event) + public function beforeFind(Event $event) { Log::debug('Inside the listener!'); } diff --git a/docs/listeners/related-models.rst b/docs/listeners/related-models.rst index d7f0f1842..214e5e337 100644 --- a/docs/listeners/related-models.rst +++ b/docs/listeners/related-models.rst @@ -120,7 +120,7 @@ subject, which can be altered on the fly before any result is fetched * ``name`` The name of the relation * ``viewVar`` The name of the variable when set to the view -* ``query`` The ``\Cake\ORM\Query`` object used for the ``find('list')`` +* ``query`` The ``\Cake\ORM\Query\SelectQuery`` object used for the ``find('list')`` * ``association`` The ``\Cake\ORM\Association`` object * ``entity`` The ``Cake\ORM\Entity`` you are finding relations for diff --git a/docs/quick-start.rst b/docs/quick-start.rst index ee38df438..b1ea2b46e 100644 --- a/docs/quick-start.rst +++ b/docs/quick-start.rst @@ -62,7 +62,7 @@ So, our new Blog needs a Posts controller to allow us to create, read, update an This is all the code we need in the ``PostsController`` as Crud will scaffold the controller actions for us. If you are not using `Crud-View `_ then you will have -to `bake your templates `_. +to `bake your templates `_. .. code-block:: sh diff --git a/docs/unit-testing.rst b/docs/unit-testing.rst index 42c4aa21f..92ab9bb08 100644 --- a/docs/unit-testing.rst +++ b/docs/unit-testing.rst @@ -15,105 +15,105 @@ Proxy methods These methods are available in all `CrudAction` and `CrudListener` objects. -_crud() +crud() ------- Get the CrudComponent instance .. code-block:: phpinline - $this->_crud() + $this->crud() -_action($name) +action($name) -------------- Get an CrudAction object by it's action name .. code-block:: phpinline - $this->_action() - $this->_action($name) + $this->action() + $this->action($name) -_trigger($eventName, $data = []) +trigger($eventName, $data = []) -------------------------------- Trigger a :doc:`Crud Event` .. code-block:: phpinline - $this->_trigger('beforeSave') - $this->_trigger('beforeSave', ['data' => 'keys']) - $this->_trigger('beforeSave', $this->_subject(['data' => 'keys'])) + $this->trigger('beforeSave') + $this->trigger('beforeSave', ['data' => 'keys']) + $this->trigger('beforeSave', $this->subject(['data' => 'keys'])) -_listener($name) +listener($name) ---------------- Get a :doc:`Listener` by its name .. code-block:: phpinline - $this->_listener('Api') + $this->listener('Api') -_subject($additional = []) +subject($additional = []) -------------------------- -Create a Crud Subject - used in ``$this->_trigger`` +Create a Crud Subject - used in ``$this->trigger`` .. code-block:: phpinline - $this->_subject() - $this->_subject(['data' => 'keys']) + $this->subject() + $this->subject(['data' => 'keys']) -_session() +session() ---------- Get the Session Component instance .. code-block:: phpinline - $this->_session() + $this->session() -_controller() +controller() ------------- Get the controller for the current request .. code-block:: phpinline - $this->_controller() + $this->controller() -_request() +request() ---------- -Get the current ``Cake\Network\Request`` for this HTTP Request +Get the current ``Cake\Http\ServerRequest`` for this HTTP Request .. code-block:: phpinline - $this->_request() + $this->request() -_response() +response() ----------- -Get the current ``Cake\Network\Response`` for this HTTP Request +Get the current ``Cake\Http\Response`` for this HTTP Request .. code-block:: phpinline - $this->_response() + $this->response() -_entity() +entity() --------- Get the entity instance that is created from ``Controller::$modelClass`` .. code-block:: phpinline - $this->_entity() + $this->entity() -_table() --------- +model() +------- -Get the table instance that is created from ``Controller::$modelClass`` +Get the table instance for the current request .. code-block:: phpinline - $this->_table() + $this->model() diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 59a1f665d..8a7f8966e 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,5 +1,5 @@ - + tests/ diff --git a/src/Action/AddAction.php b/src/Action/AddAction.php index debc659c4..74bd3bb53 100644 --- a/src/Action/AddAction.php +++ b/src/Action/AddAction.php @@ -43,7 +43,7 @@ class AddAction extends BaseAction * * @var array */ - protected array $_defaultConfig = [ + protected array $defaultConfig = [ 'enabled' => true, 'scope' => 'entity', 'inflection' => 'singular', @@ -96,17 +96,17 @@ class AddAction extends BaseAction * * @return void */ - protected function _get(): void + protected function handleGet(): void { - $subject = $this->_subject([ + $subject = $this->subject([ 'success' => true, - 'entity' => $this->_entity( - $this->_request()->getQueryParams(), + 'entity' => $this->entity( + $this->request()->getQueryParams(), ['validate' => false] + $this->saveOptions(), ), ]); - $this->_trigger('beforeRender', $subject); + $this->trigger('beforeRender', $subject); } /** @@ -114,26 +114,26 @@ protected function _get(): void * * @return \Cake\Http\Response|null */ - protected function _post(): ?Response + protected function handlePost(): ?Response { - $subject = $this->_subject([ - 'entity' => $this->_entity($this->_request()->getData(), $this->saveOptions()), + $subject = $this->subject([ + 'entity' => $this->entity($this->request()->getData(), $this->saveOptions()), 'saveMethod' => $this->saveMethod(), 'saveOptions' => $this->saveOptions(), ]); - $event = $this->_trigger('beforeSave', $subject); + $event = $this->trigger('beforeSave', $subject); if ($event->isStopped()) { - return $this->_stopped($subject); + return $this->stopped($subject); } - $saveCallback = [$this->_model(), $subject->saveMethod]; + $saveCallback = [$this->model(), $subject->saveMethod]; /** @phpstan-ignore argument.type */ if (call_user_func($saveCallback, $subject->entity, $subject->saveOptions)) { - return $this->_success($subject); + return $this->success($subject); } - $this->_error($subject); + $this->error($subject); return null; } @@ -143,9 +143,9 @@ protected function _post(): ?Response * * @return \Cake\Http\Response|null */ - protected function _put(): ?Response + protected function handlePut(): ?Response { - return $this->_post(); + return $this->handlePost(); } /** @@ -154,14 +154,14 @@ protected function _put(): ?Response * @param \Crud\Event\Subject $subject Event subject * @return \Cake\Http\Response|null */ - protected function _success(Subject $subject): ?Response + protected function success(Subject $subject): ?Response { $subject->set(['success' => true, 'created' => true]); - $this->_trigger('afterSave', $subject); + $this->trigger('afterSave', $subject); $this->setFlash('success', $subject); - return $this->_redirect($subject, ['action' => 'index']); + return $this->redirect($subject, ['action' => 'index']); } /** @@ -170,13 +170,13 @@ protected function _success(Subject $subject): ?Response * @param \Crud\Event\Subject $subject Event subject * @return void */ - protected function _error(Subject $subject): void + protected function error(Subject $subject): void { $subject->set(['success' => false, 'created' => false]); - $this->_trigger('afterSave', $subject); + $this->trigger('afterSave', $subject); $this->setFlash('error', $subject); - $this->_trigger('beforeRender', $subject); + $this->trigger('beforeRender', $subject); } /** @@ -185,19 +185,19 @@ protected function _error(Subject $subject): void * @param \Crud\Event\Subject $subject Event subject * @return \Cake\Http\Response|null */ - protected function _stopped(Subject $subject): ?Response + protected function stopped(Subject $subject): ?Response { if (!isset($subject->success)) { $subject->success = false; } if ($subject->success) { - return $this->_success($subject); + return $this->success($subject); } $subject->set(['success' => false]); $this->setFlash('error', $subject); - return $this->_redirect($subject, ['action' => 'index']); + return $this->redirect($subject, ['action' => 'index']); } } diff --git a/src/Action/BaseAction.php b/src/Action/BaseAction.php index ac83cfc94..5fe8b4757 100644 --- a/src/Action/BaseAction.php +++ b/src/Action/BaseAction.php @@ -27,14 +27,14 @@ abstract class BaseAction extends BaseObject * * @var bool */ - protected bool $_responding = false; + protected bool $responding = false; /** * Default configuration * * @var array */ - protected array $_defaultConfig = []; + protected array $defaultConfig = []; /** * Handle callback @@ -56,14 +56,14 @@ public function handle(array $args = []): mixed } $methods = [ - '_' . strtolower($this->_request()->getMethod()), - '_handle', + 'handle' . strtolower($this->request()->getMethod()), + 'handleRequest', ]; foreach ($methods as $method) { if (method_exists($this, $method)) { - $this->_responding = true; - $this->_controller()->getEventManager()->on($this); + $this->responding = true; + $this->controller()->getEventManager()->on($this); $closure = $this->$method(...); @@ -79,13 +79,13 @@ public function handle(array $args = []): mixed } /** - * Getter for $_responding + * Getter for $responding * * @return bool */ public function responding(): bool { - return $this->_responding; + return $this->responding; } /** @@ -128,7 +128,7 @@ public function disable(): void */ public function message(string $type, array $replacements = []): array { - $crud = $this->_crud(); + $crud = $this->crud(); $config = $this->getConfig('messages.' . $type); if (!$config) { @@ -185,16 +185,16 @@ public function message(string $type, array $replacements = []): array public function setFlash(string $type, Subject $subject): void { $subject->set($this->message($type)); - $event = $this->_trigger('setFlash', $subject); + $event = $this->trigger('setFlash', $subject); if ($event->isStopped()) { return; } - if (!$this->_controller()->components()->has('Flash')) { + if (!$this->controller()->components()->has('Flash')) { throw new RuntimeException('FlashComponent not loaded in controller.'); } - $this->_controller()->Flash->set($subject->text, [ + $this->controller()->Flash->set($subject->text, [ 'element' => $subject->element, 'params' => $subject->params, 'key' => $subject->key, @@ -260,7 +260,7 @@ public function publishSuccess(EventInterface $event): ?bool return false; } - $this->_controller()->set('success', $event->getSubject()->success); + $this->controller()->set('success', $event->getSubject()->success); return null; } @@ -281,7 +281,7 @@ public function resourceName(?string $value = null) } if (!$this->getConfig('name')) { - $this->setConfig('name', $this->_deriveResourceName()); + $this->setConfig('name', $this->deriveResourceName()); } return $this->getConfig('name'); @@ -292,7 +292,7 @@ public function resourceName(?string $value = null) * * @return string */ - protected function _deriveResourceName(): string + protected function deriveResourceName(): string { $inflectionType = $this->getConfig('inflection'); @@ -302,11 +302,11 @@ protected function _deriveResourceName(): string if ($inflectionType === 'singular') { return strtolower(Inflector::humanize( - Inflector::singularize(Inflector::underscore($this->_model()->getAlias())), + Inflector::singularize(Inflector::underscore($this->model()->getAlias())), )); } - return strtolower(Inflector::humanize(Inflector::underscore($this->_model()->getAlias()))); + return strtolower(Inflector::humanize(Inflector::underscore($this->model()->getAlias()))); } /** diff --git a/src/Action/Bulk/BaseAction.php b/src/Action/Bulk/BaseAction.php index 1c6401114..864ea37d3 100644 --- a/src/Action/Bulk/BaseAction.php +++ b/src/Action/Bulk/BaseAction.php @@ -29,7 +29,7 @@ abstract class BaseAction extends CrudBaseAction * * @var array */ - protected array $_defaultConfig = [ + protected array $defaultConfig = [ 'enabled' => true, 'scope' => 'bulk', 'queryType' => Query::TYPE_UPDATE, @@ -48,23 +48,23 @@ abstract class BaseAction extends CrudBaseAction * * @return \Cake\Http\Response|null */ - protected function _handle(): ?Response + protected function handleRequest(): ?Response { - $ids = $this->_processIds(); - $subject = $this->_constructSubject($ids); + $ids = $this->processIds(); + $subject = $this->constructSubject($ids); - $event = $this->_trigger('beforeBulk', $subject); + $event = $this->trigger('beforeBulk', $subject); if ($event->isStopped()) { - return $this->_stopped($subject); + return $this->stopped($subject); } - if ($this->_bulk($subject->query)) { - $this->_success($subject); + if ($this->bulk($subject->query)) { + $this->success($subject); } else { - $this->_error($subject); + $this->error($subject); } - return $this->_redirect($subject, ['action' => 'index']); + return $this->redirect($subject, ['action' => 'index']); } /** @@ -72,9 +72,9 @@ protected function _handle(): ?Response * * @return array */ - protected function _processIds(): array + protected function processIds(): array { - $ids = $this->_controller()->getRequest()->getData('id'); + $ids = $this->controller()->getRequest()->getData('id'); if (!is_array($ids)) { throw new BadRequestException('Bad request data'); @@ -99,9 +99,9 @@ protected function _processIds(): array * @param array $ids An array of ids to retrieve * @return \Crud\Event\Subject */ - protected function _constructSubject(array $ids): Subject + protected function constructSubject(array $ids): Subject { - $repository = $this->_model(); + $repository = $this->model(); assert($repository instanceof Table); $method = strtolower($this->getConfig('queryType')) . 'Query'; @@ -110,7 +110,7 @@ protected function _constructSubject(array $ids): Subject $query = $repository->{$method}() ->where(fn($exp) => $exp->in($primaryKey, $ids)); - $subject = $this->_subject(); + $subject = $this->subject(); $subject->set([ 'ids' => $ids, 'query' => $query, @@ -126,10 +126,10 @@ protected function _constructSubject(array $ids): Subject * @param \Crud\Event\Subject $subject Event subject * @return void */ - protected function _success(Subject $subject): void + protected function success(Subject $subject): void { $subject->set(['success' => true]); - $this->_trigger('afterBulk', $subject); + $this->trigger('afterBulk', $subject); $this->setFlash('success', $subject); } @@ -140,10 +140,10 @@ protected function _success(Subject $subject): void * @param \Crud\Event\Subject $subject Event subject * @return void */ - protected function _error(Subject $subject): void + protected function error(Subject $subject): void { $subject->set(['success' => false]); - $this->_trigger('afterBulk', $subject); + $this->trigger('afterBulk', $subject); $this->setFlash('error', $subject); } @@ -154,12 +154,12 @@ protected function _error(Subject $subject): void * @param \Crud\Event\Subject $subject Event subject * @return \Cake\Http\Response|null */ - protected function _stopped(Subject $subject): ?Response + protected function stopped(Subject $subject): ?Response { $subject->set(['success' => false]); $this->setFlash('error', $subject); - return $this->_redirect($subject, ['action' => 'index']); + return $this->redirect($subject, ['action' => 'index']); } /** @@ -168,5 +168,5 @@ protected function _stopped(Subject $subject): ?Response * @param \Cake\Database\Query $query The query to act upon * @return bool */ - abstract protected function _bulk(Query $query): bool; + abstract protected function bulk(Query $query): bool; } diff --git a/src/Action/Bulk/DeleteAction.php b/src/Action/Bulk/DeleteAction.php index 8180378ca..e41977dde 100644 --- a/src/Action/Bulk/DeleteAction.php +++ b/src/Action/Bulk/DeleteAction.php @@ -24,9 +24,9 @@ class DeleteAction extends BaseAction */ public function __construct(Controller $Controller, array $config = []) { - $this->_defaultConfig['queryType'] = Query::TYPE_DELETE; + $this->defaultConfig['queryType'] = Query::TYPE_DELETE; - $this->_defaultConfig['messages'] = [ + $this->defaultConfig['messages'] = [ 'success' => [ 'text' => 'Delete completed successfully', ], @@ -44,7 +44,7 @@ public function __construct(Controller $Controller, array $config = []) * @param \Cake\Database\Query $query The query to act upon * @return bool */ - protected function _bulk(Query $query): bool + protected function bulk(Query $query): bool { assert($query instanceof DeleteQuery); diff --git a/src/Action/Bulk/SetValueAction.php b/src/Action/Bulk/SetValueAction.php index c6d0bd17f..5041832c3 100644 --- a/src/Action/Bulk/SetValueAction.php +++ b/src/Action/Bulk/SetValueAction.php @@ -26,7 +26,7 @@ class SetValueAction extends BaseAction */ public function __construct(Controller $Controller, array $config = []) { - $this->_defaultConfig['messages'] = [ + $this->defaultConfig['messages'] = [ 'success' => [ 'text' => 'Set value successfully', ], @@ -34,7 +34,7 @@ public function __construct(Controller $Controller, array $config = []) 'text' => 'Could not set value', ], ]; - $this->_defaultConfig['value'] = null; + $this->defaultConfig['value'] = null; parent::__construct($Controller, $config); } @@ -45,13 +45,13 @@ public function __construct(Controller $Controller, array $config = []) * @return \Cake\Http\Response|null * @throws \Crud\Error\Exception\ActionNotConfiguredException */ - protected function _handle(): ?Response + protected function handleRequest(): ?Response { if (!$this->getConfig('field')) { throw new ActionNotConfiguredException('No field value specified'); } - return parent::_handle(); + return parent::handleRequest(); } /** @@ -60,7 +60,7 @@ protected function _handle(): ?Response * @param \Cake\Database\Query $query The query to act upon * @return bool */ - protected function _bulk(Query $query): bool + protected function bulk(Query $query): bool { assert($query instanceof UpdateQuery); diff --git a/src/Action/Bulk/ToggleAction.php b/src/Action/Bulk/ToggleAction.php index db95c9c6d..7d6ba13f2 100644 --- a/src/Action/Bulk/ToggleAction.php +++ b/src/Action/Bulk/ToggleAction.php @@ -27,7 +27,7 @@ class ToggleAction extends BaseAction */ public function __construct(Controller $Controller, array $config = []) { - $this->_defaultConfig['messages'] = [ + $this->defaultConfig['messages'] = [ 'success' => [ 'text' => 'Value toggled successfully', ], @@ -45,13 +45,13 @@ public function __construct(Controller $Controller, array $config = []) * @return \Cake\Http\Response|null * @throws \Crud\Error\Exception\ActionNotConfiguredException */ - protected function _handle(): ?Response + protected function handleRequest(): ?Response { if (!$this->getConfig('field')) { throw new ActionNotConfiguredException('No field value specified'); } - return parent::_handle(); + return parent::handleRequest(); } /** @@ -60,7 +60,7 @@ protected function _handle(): ?Response * @param \Cake\Database\Query $query The query to act upon * @return bool */ - protected function _bulk(Query $query): bool + protected function bulk(Query $query): bool { assert($query instanceof UpdateQuery); diff --git a/src/Action/DeleteAction.php b/src/Action/DeleteAction.php index c88c5f771..b9c4dd7d7 100644 --- a/src/Action/DeleteAction.php +++ b/src/Action/DeleteAction.php @@ -30,7 +30,7 @@ class DeleteAction extends BaseAction * * @var array */ - protected array $_defaultConfig = [ + protected array $defaultConfig = [ 'enabled' => true, 'scope' => 'entity', 'findMethod' => 'all', @@ -59,26 +59,26 @@ class DeleteAction extends BaseAction * @param string|int|null $id Record id * @return \Cake\Http\Response|null */ - protected function _post(string|int|null $id = null): ?Response + protected function handlePost(string|int|null $id = null): ?Response { - $subject = $this->_subject(); + $subject = $this->subject(); $subject->set(['id' => $id]); - $entity = $this->_findRecord($id, $subject); + $entity = $this->findRecord($id, $subject); - $event = $this->_trigger('beforeDelete', $subject); + $event = $this->trigger('beforeDelete', $subject); if ($event->isStopped()) { - return $this->_stopped($subject); + return $this->stopped($subject); } $method = $this->getConfig('deleteMethod'); - if ($this->_model()->$method($entity)) { - $this->_success($subject); + if ($this->model()->$method($entity)) { + $this->success($subject); } else { - $this->_error($subject); + $this->error($subject); } - return $this->_redirect($subject, ['action' => 'index']); + return $this->redirect($subject, ['action' => 'index']); } /** @@ -87,9 +87,9 @@ protected function _post(string|int|null $id = null): ?Response * @param string|int|null $id Record id * @return \Cake\Http\Response|null */ - protected function _delete(string|int|null $id = null): ?Response + protected function handleDelete(string|int|null $id = null): ?Response { - return $this->_post($id); + return $this->handlePost($id); } /** @@ -98,10 +98,10 @@ protected function _delete(string|int|null $id = null): ?Response * @param \Crud\Event\Subject $subject Event subject * @return void */ - protected function _success(Subject $subject): void + protected function success(Subject $subject): void { $subject->set(['success' => true]); - $this->_trigger('afterDelete', $subject); + $this->trigger('afterDelete', $subject); $this->setFlash('success', $subject); } @@ -112,10 +112,10 @@ protected function _success(Subject $subject): void * @param \Crud\Event\Subject $subject Event subject * @return void */ - protected function _error(Subject $subject): void + protected function error(Subject $subject): void { $subject->set(['success' => false]); - $this->_trigger('afterDelete', $subject); + $this->trigger('afterDelete', $subject); $this->setFlash('error', $subject); } @@ -126,11 +126,11 @@ protected function _error(Subject $subject): void * @param \Crud\Event\Subject $subject Event subject * @return \Cake\Http\Response|null */ - protected function _stopped(Subject $subject): ?Response + protected function stopped(Subject $subject): ?Response { $subject->set(['success' => false]); $this->setFlash('error', $subject); - return $this->_redirect($subject, ['action' => 'index']); + return $this->redirect($subject, ['action' => 'index']); } } diff --git a/src/Action/EditAction.php b/src/Action/EditAction.php index 22cf638a6..2af994d5a 100644 --- a/src/Action/EditAction.php +++ b/src/Action/EditAction.php @@ -47,7 +47,7 @@ class EditAction extends BaseAction * * @var array */ - protected array $_defaultConfig = [ + protected array $defaultConfig = [ 'enabled' => true, 'scope' => 'entity', 'findMethod' => 'all', @@ -97,13 +97,13 @@ class EditAction extends BaseAction * @return void * @throws \Cake\Http\Exception\NotFoundException If record not found */ - protected function _get(string|int|null $id = null): void + protected function handleGet(string|int|null $id = null): void { - $subject = $this->_subject(); + $subject = $this->subject(); $subject->set(['id' => $id]); - $subject->set(['entity' => $this->_findRecord($id, $subject)]); + $subject->set(['entity' => $this->findRecord($id, $subject)]); - $this->_trigger('beforeRender', $subject); + $this->trigger('beforeRender', $subject); } /** @@ -112,24 +112,24 @@ protected function _get(string|int|null $id = null): void * @param string|int|null $id Record id * @return \Cake\Http\Response|null */ - protected function _put(string|int|null $id = null): ?Response + protected function handlePut(string|int|null $id = null): ?Response { - $subject = $this->_subject(); + $subject = $this->subject(); $subject->set(['id' => $id]); - $entity = $this->_model()->patchEntity( - $this->_findRecord($id, $subject), - $this->_request()->getData(), + $entity = $this->model()->patchEntity( + $this->findRecord($id, $subject), + $this->request()->getData(), $this->saveOptions(), ); - $this->_trigger('beforeSave', $subject); + $this->trigger('beforeSave', $subject); /** @phpstan-ignore argument.type */ - if (call_user_func([$this->_model(), $this->saveMethod()], $entity, $this->saveOptions())) { - return $this->_success($subject); + if (call_user_func([$this->model(), $this->saveMethod()], $entity, $this->saveOptions())) { + return $this->success($subject); } - $this->_error($subject); + $this->error($subject); return null; } @@ -137,27 +137,27 @@ protected function _put(string|int|null $id = null): ?Response /** * HTTP POST handler * - * Thin proxy for _put + * Thin proxy for handlePut * * @param string|int|null $id Record id * @return \Cake\Http\Response|null */ - protected function _post(string|int|null $id = null): ?Response + protected function handlePost(string|int|null $id = null): ?Response { - return $this->_put($id); + return $this->handlePut($id); } /** * HTTP PATCH handler * - * Thin proxy for _put + * Thin proxy for handlePut * * @param string|int|null $id Record id * @return \Cake\Http\Response|null */ - protected function _patch(string|int|null $id = null): ?Response + protected function handlePatch(string|int|null $id = null): ?Response { - return $this->_put($id); + return $this->handlePut($id); } /** @@ -166,14 +166,14 @@ protected function _patch(string|int|null $id = null): ?Response * @param \Crud\Event\Subject $subject Event subject * @return \Cake\Http\Response|null */ - protected function _success(Subject $subject): ?Response + protected function success(Subject $subject): ?Response { $subject->set(['success' => true, 'created' => false]); - $this->_trigger('afterSave', $subject); + $this->trigger('afterSave', $subject); $this->setFlash('success', $subject); - return $this->_redirect($subject, ['action' => 'index']); + return $this->redirect($subject, ['action' => 'index']); } /** @@ -182,13 +182,13 @@ protected function _success(Subject $subject): ?Response * @param \Crud\Event\Subject $subject Event subject * @return void */ - protected function _error(Subject $subject): void + protected function error(Subject $subject): void { $subject->set(['success' => false, 'created' => false]); - $this->_trigger('afterSave', $subject); + $this->trigger('afterSave', $subject); $this->setFlash('error', $subject); - $this->_trigger('beforeRender', $subject); + $this->trigger('beforeRender', $subject); } } diff --git a/src/Action/IndexAction.php b/src/Action/IndexAction.php index e3710ce4f..85e4f6698 100644 --- a/src/Action/IndexAction.php +++ b/src/Action/IndexAction.php @@ -29,7 +29,7 @@ class IndexAction extends BaseAction * * @var array */ - protected array $_defaultConfig = [ + protected array $defaultConfig = [ 'enabled' => true, 'scope' => 'table', 'findMethod' => 'all', @@ -51,30 +51,30 @@ class IndexAction extends BaseAction * * @return \Cake\Http\Response|null */ - protected function _handle(): ?Response + protected function handleRequest(): ?Response { - [$finder, $options] = $this->_extractFinder(); - $query = $this->_model()->find($finder, ...$options); - $subject = $this->_subject(['success' => true, 'query' => $query]); + [$finder, $options] = $this->extractFinder(); + $query = $this->model()->find($finder, ...$options); + $subject = $this->subject(['success' => true, 'query' => $query]); - $this->_trigger('beforePaginate', $subject); + $this->trigger('beforePaginate', $subject); try { - $items = $this->_controller()->paginate($subject->query); + $items = $this->controller()->paginate($subject->query); } catch (NotFoundException $e) { /** @var \Cake\Core\Exception\CakeException $previous */ $previous = $e->getPrevious(); $pagingParams = $previous->getAttributes()['pagingParams']; - $url = Router::reverseToArray($this->_request()); + $url = Router::reverseToArray($this->request()); $url['?']['page'] = $pagingParams['pageCount']; - return $this->_controller()->redirect($url); + return $this->controller()->redirect($url); } $subject->set(['entities' => $items]); - $this->_trigger('afterPaginate', $subject); - $this->_trigger('beforeRender', $subject); + $this->trigger('afterPaginate', $subject); + $this->trigger('beforeRender', $subject); return null; } diff --git a/src/Action/LookupAction.php b/src/Action/LookupAction.php index 188e7ed3f..9e539b3cb 100644 --- a/src/Action/LookupAction.php +++ b/src/Action/LookupAction.php @@ -27,7 +27,7 @@ class LookupAction extends BaseAction * * @var array */ - protected array $_defaultConfig = [ + protected array $defaultConfig = [ 'enabled' => true, 'scope' => 'table', 'findMethod' => 'list', @@ -38,18 +38,18 @@ class LookupAction extends BaseAction * * @return void */ - protected function _handle(): void + protected function handleRequest(): void { - [$finder, $options] = $this->_extractFinder(); - $options = array_merge($options, $this->_getFindConfig()); - $query = $this->_model()->find($finder, ...$options); - $subject = $this->_subject(['success' => true, 'query' => $query]); + [$finder, $options] = $this->extractFinder(); + $options = array_merge($options, $this->getFindConfig()); + $query = $this->model()->find($finder, ...$options); + $subject = $this->subject(['success' => true, 'query' => $query]); - $this->_trigger('beforeLookup', $subject); - $subject->set(['entities' => $this->_controller()->paginate($subject->query)]); - $this->_trigger('afterLookup', $subject); + $this->trigger('beforeLookup', $subject); + $subject->set(['entities' => $this->controller()->paginate($subject->query)]); + $this->trigger('afterLookup', $subject); - $this->_trigger('beforeRender', $subject); + $this->trigger('beforeRender', $subject); } /** @@ -57,10 +57,10 @@ protected function _handle(): void * * @return array */ - protected function _getFindConfig(): array + protected function getFindConfig(): array { - $request = $this->_request(); - $model = $this->_model(); + $request = $this->request(); + $model = $this->model(); assert($model instanceof Table); $columns = $model->getSchema()->columns(); diff --git a/src/Action/ViewAction.php b/src/Action/ViewAction.php index bdd2a1e9e..d8fa90c31 100644 --- a/src/Action/ViewAction.php +++ b/src/Action/ViewAction.php @@ -33,7 +33,7 @@ class ViewAction extends BaseAction * * @var array */ - protected array $_defaultConfig = [ + protected array $defaultConfig = [ 'enabled' => true, 'scope' => 'entity', 'findMethod' => 'all', @@ -48,12 +48,12 @@ class ViewAction extends BaseAction * @param string|int|null $id Record id * @return void */ - protected function _handle(string|int|null $id = null): void + protected function handleRequest(string|int|null $id = null): void { - $subject = $this->_subject(); + $subject = $this->subject(); $subject->set(['id' => $id]); - $this->_findRecord($id, $subject); - $this->_trigger('beforeRender', $subject); + $this->findRecord($id, $subject); + $this->trigger('beforeRender', $subject); } } diff --git a/src/Controller/Component/CrudComponent.php b/src/Controller/Component/CrudComponent.php index 1ae29714c..23ced063a 100644 --- a/src/Controller/Component/CrudComponent.php +++ b/src/Controller/Component/CrudComponent.php @@ -42,56 +42,56 @@ class CrudComponent extends Component * * @var string */ - protected string $_action; + protected string $action; /** * Reference to the current controller. * * @var \Cake\Controller\Controller */ - protected Controller $_controller; + protected Controller $controller; /** * Reference to the current request. * * @var \Cake\Http\ServerRequest */ - protected ServerRequest $_request; + protected ServerRequest $request; /** * A flat array of the events triggered. * * @var array */ - protected array $_eventLog = []; + protected array $eventLog = []; /** * Reference to the current event manager. * * @var \Cake\Event\EventManagerInterface */ - protected EventManagerInterface $_eventManager; + protected EventManagerInterface $eventManager; /** * This is the model name of the current model. * * @var string|null */ - protected ?string $_modelName = null; + protected ?string $modelName = null; /** * List of listener objects attached to Crud. * * @var array<\Crud\Listener\BaseListener> */ - protected array $_listenerInstances = []; + protected array $listenerInstances = []; /** * List of crud actions. * * @var array<\Crud\Action\BaseAction> */ - protected array $_actionInstances = []; + protected array $actionInstances = []; /** * Components settings. @@ -111,7 +111,7 @@ class CrudComponent extends Component * * @var array */ - protected array $_defaultConfig = [ + protected array $defaultConfig = [ 'actions' => [], 'eventPrefix' => 'Crud', 'listeners' => [], @@ -146,9 +146,9 @@ public function initialize(array $config): void { parent::initialize($config); - $this->_controller ??= $this->getController(); - $this->_eventManager ??= $this->_controller->getEventManager(); - $this->_action ??= $this->_controller->getRequest()->getParam('action'); + $this->controller ??= $this->getController(); + $this->eventManager ??= $this->controller->getEventManager(); + $this->action ??= $this->controller->getRequest()->getParam('action'); } /** @@ -161,7 +161,7 @@ public function initialize(array $config): void * @param bool $merge Whether to recursively merge or overwrite existing config, defaults to true. * @return $this */ - public function setConfig(array|string $key, mixed $value = null, bool $merge = true) + public function setConfig(array|string $key, mixed $value = null, bool $merge = true): static { if (is_array($key)) { if (isset($key['actions'])) { @@ -216,7 +216,7 @@ public function normalizeArray(array $array): array */ public function beforeFilter(EventInterface $event): void { - $this->_loadListeners(); + $this->loadListeners(); $this->trigger('beforeFilter'); } @@ -229,7 +229,7 @@ public function beforeFilter(EventInterface $event): void */ public function startup(EventInterface $event): void { - $this->_loadListeners(); + $this->loadListeners(); $this->trigger('startup'); } @@ -243,19 +243,20 @@ public function startup(EventInterface $event): void */ public function execute(?string $controllerAction = null, array $args = []): ResponseInterface { - $this->_loadListeners(); + $this->loadListeners(); - $this->_action = $controllerAction ?? $this->_action; + $this->action = $controllerAction ?? $this->action; - $action = $this->_action; + $action = $this->action; if ($args === []) { $args = $this->getController()->getRequest()->getParam('pass'); } try { - $event = $this->trigger('beforeHandle', $this->getSubject(compact('args', 'action'))); + $subject = $this->getSubject(compact('args', 'action')); + $this->trigger('beforeHandle', $subject); - $response = $this->action($event->getSubject()->action)->handle($event->getSubject()->args); + $response = $this->action($subject->action)->handle($subject->args); if ($response instanceof ResponseInterface) { return $response; } @@ -274,7 +275,7 @@ public function execute(?string $controllerAction = null, array $args = []): Res $view = $crudAction->view(); } - return $this->_controller->render($view); + return $this->controller->render($view); } /** @@ -288,12 +289,12 @@ public function execute(?string $controllerAction = null, array $args = []): Res public function action(?string $name = null): BaseAction { if ($name === null) { - $name = $this->_action; + $name = $this->action; } $name = Inflector::variable($name); - return $this->_loadAction($name); + return $this->loadAction($name); } /** @@ -432,7 +433,7 @@ public function mapAction(string $action, array|string $config = [], bool $enabl public function isActionMapped(?string $action = null): bool { if ($action === null) { - $action = $this->_action; + $action = $this->action; } $action = Inflector::variable($action); @@ -448,17 +449,17 @@ public function isActionMapped(?string $action = null): bool * * @param array|string $events Name of the Crud Event you want to attach to controller. * @param callable $callback Callable method or closure to be executed on event. - * @param array $options Used to set the `priority` and `passParams` flags to the listener. + * @param array $options Used to set the `priority` flag for the listener. * @return void */ public function on(array|string $events, callable $callback, array $options = []): void { foreach ((array)$events as $event) { if (!str_contains($event, '.')) { - $event = $this->_config['eventPrefix'] . '.' . $event; + $event = $this->config['eventPrefix'] . '.' . $event; } - $this->_eventManager->on($event, $options, $callback); + $this->eventManager->on($event, $callback, $options); } } @@ -472,7 +473,7 @@ public function on(array|string $events, callable $callback, array $options = [] */ public function listener(string $name): BaseListener { - return $this->_loadListener($name); + return $this->loadListener($name); } /** @@ -516,13 +517,13 @@ public function removeListener(string $name): bool return false; } - if (isset($this->_listenerInstances[$name])) { - $this->_eventManager->off($this->_listenerInstances[$name]); - unset($this->_listenerInstances[$name]); + if (isset($this->listenerInstances[$name])) { + $this->eventManager->off($this->listenerInstances[$name]); + unset($this->listenerInstances[$name]); } unset($listeners[$name]); - $this->_config['listeners'] = $listeners; + $this->config['listeners'] = $listeners; return true; } @@ -543,7 +544,7 @@ public function removeListener(string $name): bool */ public function trigger(string $eventName, Subject|array|null $data = null): EventInterface { - $eventName = $this->_config['eventPrefix'] . '.' . $eventName; + $eventName = $this->config['eventPrefix'] . '.' . $eventName; $Subject = $data instanceof Subject ? $data : $this->getSubject($data ?? []); $Subject->addEvent($eventName); @@ -553,7 +554,7 @@ public function trigger(string $eventName, Subject|array|null $data = null): Eve } $Event = new Event($eventName, $Subject); - $Event = $this->_eventManager->dispatch($Event); + $Event = $this->eventManager->dispatch($Event); if ($Event->getResult() instanceof ResponseInterface) { $Exception = new CrudException(); @@ -573,7 +574,7 @@ public function trigger(string $eventName, Subject|array|null $data = null): Eve */ public function logEvent(string $eventName, Subject $subject): void { - $this->_eventLog[] = [$eventName, $subject]; + $this->eventLog[] = [$eventName, $subject]; } /** @@ -613,7 +614,7 @@ public function defaults(string $type, array|string $name, mixed $config = null) */ public function eventLog(): array { - return $this->_eventLog; + return $this->eventLog; } /** @@ -624,7 +625,7 @@ public function eventLog(): array */ public function useModel(string $modelName): void { - $this->_modelName = $modelName; + $this->modelName = $modelName; } /** @@ -634,11 +635,11 @@ public function useModel(string $modelName): void */ public function model(): RepositoryInterface { - if (method_exists($this->_controller, 'fetchModel')) { - return $this->_controller->fetchModel($this->_modelName); + if (method_exists($this->controller, 'fetchModel')) { + return $this->controller->fetchModel($this->modelName); } - return $this->_controller->fetchTable($this->_modelName); + return $this->controller->fetchTable($this->modelName); } /** @@ -660,7 +661,7 @@ public function entity(array $data = []): EntityInterface */ public function controller(): Controller { - return $this->_controller; + return $this->controller; } /** @@ -684,11 +685,11 @@ public function getSubject(array $additional = []): Subject * @throws \Crud\Error\Exception\ListenerNotConfiguredException * @throws \Crud\Error\Exception\MissingListenerException */ - protected function _loadListeners(): void + protected function loadListeners(): void { /** @var string $name */ foreach (array_keys($this->getConfig('listeners')) as $name) { - $this->_loadListener($name); + $this->loadListener($name); } } @@ -700,9 +701,9 @@ protected function _loadListeners(): void * @throws \Crud\Error\Exception\ListenerNotConfiguredException * @throws \Crud\Error\Exception\MissingListenerException */ - protected function _loadListener(string $name): BaseListener + protected function loadListener(string $name): BaseListener { - if (!isset($this->_listenerInstances[$name])) { + if (!isset($this->listenerInstances[$name])) { $config = $this->getConfig('listeners.' . $name); if (!$config) { @@ -715,18 +716,18 @@ protected function _loadListener(string $name): BaseListener throw new MissingListenerException('Could not find listener class: ' . $config['className']); } - $this->_listenerInstances[$name] = new $className($this->_controller); + $this->listenerInstances[$name] = new $className($this->controller); unset($config['className']); - $this->_listenerInstances[$name]->setConfig($config); + $this->listenerInstances[$name]->setConfig($config); - $this->_eventManager->on($this->_listenerInstances[$name]); + $this->eventManager->on($this->listenerInstances[$name]); - if (is_callable([$this->_listenerInstances[$name], 'setup'])) { - $this->_listenerInstances[$name]->setup(); + if (is_callable([$this->listenerInstances[$name], 'setup'])) { + $this->listenerInstances[$name]->setup(); } } - return $this->_listenerInstances[$name]; + return $this->listenerInstances[$name]; } /** @@ -737,9 +738,9 @@ protected function _loadListener(string $name): BaseListener * @throws \Crud\Error\Exception\ActionNotConfiguredException * @throws \Crud\Error\Exception\MissingActionException */ - protected function _loadAction(string $name): BaseAction + protected function loadAction(string $name): BaseAction { - if (!isset($this->_actionInstances[$name])) { + if (!isset($this->actionInstances[$name])) { $config = $this->getConfig('actions.' . $name); if (!$config) { @@ -752,11 +753,11 @@ protected function _loadAction(string $name): BaseAction throw new MissingActionException('Could not find action class: ' . $config['className']); } - $this->_actionInstances[$name] = new $className($this->_controller); + $this->actionInstances[$name] = new $className($this->controller); unset($config['className']); - $this->_actionInstances[$name]->setConfig($config); + $this->actionInstances[$name]->setConfig($config); } - return $this->_actionInstances[$name]; + return $this->actionInstances[$name]; } } diff --git a/src/Core/BaseObject.php b/src/Core/BaseObject.php index 0e9347856..8c70d587f 100644 --- a/src/Core/BaseObject.php +++ b/src/Core/BaseObject.php @@ -26,14 +26,14 @@ abstract class BaseObject implements EventListenerInterface * * @var \Cake\Controller\Controller */ - protected Controller $_controller; + protected Controller $controller; /** * Default configuration * * @var array */ - protected array $_defaultConfig = []; + protected array $defaultConfig = []; /** * Constructor @@ -43,7 +43,7 @@ abstract class BaseObject implements EventListenerInterface */ public function __construct(Controller $Controller, array $config = []) { - $this->_controller = $Controller; + $this->controller = $Controller; $this->setConfig($config); } @@ -63,8 +63,8 @@ public function implementedEvents(): array * @param list|string $method Method(s) to check for * @return bool */ - protected function _checkRequestType(array|string $method): bool + protected function checkRequestType(array|string $method): bool { - return $this->_request()->is($method); + return $this->request()->is($method); } } diff --git a/src/Core/ProxyTrait.php b/src/Core/ProxyTrait.php index 753793b82..2d63918d0 100644 --- a/src/Core/ProxyTrait.php +++ b/src/Core/ProxyTrait.php @@ -20,10 +20,10 @@ trait ProxyTrait /** * @var \Cake\Datasource\EntityInterface|null */ - protected ?EntityInterface $_entity = null; + protected ?EntityInterface $entity = null; /** - * Proxy method for `$this->_crud()->action()` + * Proxy method for `$this->crud()->action()` * * Primarily here to ease unit testing * @@ -31,13 +31,13 @@ trait ProxyTrait * @return \Crud\Action\BaseAction * @codeCoverageIgnore */ - protected function _action(?string $name = null): BaseAction + protected function action(?string $name = null): BaseAction { - return $this->_crud()->action($name); + return $this->crud()->action($name); } /** - * Proxy method for `$this->_crud()->trigger()` + * Proxy method for `$this->crud()->trigger()` * * Primarily here to ease unit testing * @@ -47,13 +47,13 @@ protected function _action(?string $name = null): BaseAction * @throws \Exception * @codeCoverageIgnore */ - protected function _trigger(string $eventName, ?Subject $data = null): EventInterface + protected function trigger(string $eventName, ?Subject $data = null): EventInterface { - return $this->_crud()->trigger($eventName, $data); + return $this->crud()->trigger($eventName, $data); } /** - * Proxy method for `$this->_crud()->listener()` + * Proxy method for `$this->crud()->listener()` * * Primarily here to ease unit testing * @@ -63,9 +63,9 @@ protected function _trigger(string $eventName, ?Subject $data = null): EventInte * @throws \Crud\Error\Exception\MissingListenerException * @codeCoverageIgnore */ - protected function _listener(string $name): BaseListener + protected function listener(string $name): BaseListener { - return $this->_crud()->listener($name); + return $this->crud()->listener($name); } /** @@ -76,48 +76,48 @@ protected function _listener(string $name): BaseListener * @return \Cake\Http\Session * @codeCoverageIgnore */ - protected function _session(): Session + protected function session(): Session { - return $this->_request()->getSession(); + return $this->request()->getSession(); } /** - * Proxy method for `$this->_container->_controller` + * Proxy method for `$this->_container->controller` * * Primarily here to ease unit testing * * @return \Cake\Controller\Controller * @codeCoverageIgnore */ - protected function _controller(): Controller + protected function controller(): Controller { - return $this->_controller; + return $this->controller; } /** - * Proxy method for `$this->_container->_request` + * Proxy method for `$this->_container->request` * * Primarily here to ease unit testing * * @return \Cake\Http\ServerRequest * @codeCoverageIgnore */ - protected function _request(): ServerRequest + protected function request(): ServerRequest { - return $this->_controller()->getRequest(); + return $this->controller()->getRequest(); } /** - * Proxy method for `$this->_controller()->getResponse()` + * Proxy method for `$this->controller()->getResponse()` * * Primarily here to ease unit testing * * @return \Cake\Http\Response * @codeCoverageIgnore */ - protected function _response(): Response + protected function response(): Response { - return $this->_controller()->getResponse(); + return $this->controller()->getResponse(); } /** @@ -125,9 +125,9 @@ protected function _response(): Response * * @return \Cake\Datasource\RepositoryInterface */ - protected function _model(): RepositoryInterface + protected function model(): RepositoryInterface { - return $this->_crud()->model(); + return $this->crud()->model(); } /** @@ -137,33 +137,33 @@ protected function _model(): RepositoryInterface * @param array $options A list of options for the object hydration. * @return \Cake\Datasource\EntityInterface */ - protected function _entity(array $data = [], array $options = []): EntityInterface + protected function entity(array $data = [], array $options = []): EntityInterface { - if ($this->_entity && $data === []) { - return $this->_entity; + if ($this->entity && $data === []) { + return $this->entity; } - return $this->_model()->newEntity($data, $options); + return $this->model()->newEntity($data, $options); } /** - * Proxy method for `$this->_crud()->getSubject()` + * Proxy method for `$this->crud()->getSubject()` * * @param array $additional Array of subject properties to set * @return \Crud\Event\Subject */ - protected function _subject(array $additional = []): Subject + protected function subject(array $additional = []): Subject { return new Subject($additional); } /** - * Proxy method for `$this->_controller->Crud` + * Proxy method for `$this->controller->Crud` * * @return \Crud\Controller\Component\CrudComponent */ - protected function _crud(): CrudComponent + protected function crud(): CrudComponent { - return $this->_controller->Crud; + return $this->controller->Crud; } } diff --git a/src/Error/Exception/ValidationException.php b/src/Error/Exception/ValidationException.php index 555b39a9e..8752eceb9 100644 --- a/src/Error/Exception/ValidationException.php +++ b/src/Error/Exception/ValidationException.php @@ -20,14 +20,14 @@ class ValidationException extends BadRequestException * * @var array */ - protected array $_validationErrors = []; + protected array $validationErrors = []; /** * How many validation errors are there? * * @var int */ - protected int $_validationErrorCount = 0; + protected int $validationErrorCount = 0; /** * Constructor @@ -38,10 +38,10 @@ class ValidationException extends BadRequestException */ public function __construct(EntityInterface $entity, int $code = 422, ?Throwable $previous = null) { - $this->_validationErrors = array_filter($entity->getErrors()); - $flat = Hash::flatten($this->_validationErrors); + $this->validationErrors = array_filter($entity->getErrors()); + $flat = Hash::flatten($this->validationErrors); - $errorCount = $this->_validationErrorCount = count($flat); + $errorCount = $this->validationErrorCount = count($flat); $this->message = __dn( 'crud', 'A validation error occurred', @@ -60,7 +60,7 @@ public function __construct(EntityInterface $entity, int $code = 422, ?Throwable */ public function getValidationErrors(): array { - return $this->_validationErrors; + return $this->validationErrors; } /** @@ -70,6 +70,6 @@ public function getValidationErrors(): array */ public function getValidationErrorCount(): int { - return $this->_validationErrorCount; + return $this->validationErrorCount; } } diff --git a/src/Error/ExceptionRenderer.php b/src/Error/ExceptionRenderer.php index 3c66d8f29..f64970479 100644 --- a/src/Error/ExceptionRenderer.php +++ b/src/Error/ExceptionRenderer.php @@ -54,7 +54,7 @@ public function validation(ValidationException $error): Response ['code', 'url', 'message', 'errorCount', 'errors'], ); - return $this->_outputMessage('error400'); + return $this->outputMessage('error400'); } /** @@ -70,13 +70,13 @@ public function validation(ValidationException $error): Response * method matching the exception name. * @return \Cake\Http\Response A response object that can be sent. */ - protected function _outputMessage(string $template, bool $skipControllerCheck = false): Response + protected function outputMessage(string $template, bool $skipControllerCheck = false): Response { $viewVars = ['success', 'data']; $this->controller->set('success', false); - $this->controller->set('data', $this->_getErrorData()); + $this->controller->set('data', $this->getErrorData()); if (Configure::read('debug')) { - $queryLog = $this->_getQueryLog(); + $queryLog = $this->getQueryLog(); if ($queryLog) { $this->controller->set(compact('queryLog')); $viewVars[] = 'queryLog'; @@ -84,7 +84,7 @@ protected function _outputMessage(string $template, bool $skipControllerCheck = } $this->controller->viewBuilder()->setOption('serialize', $viewVars); - return parent::_outputMessage($template, $skipControllerCheck); + return parent::outputMessage($template, $skipControllerCheck); } /** @@ -92,7 +92,7 @@ protected function _outputMessage(string $template, bool $skipControllerCheck = * * @return array debugging data */ - protected function _getErrorData(): array + protected function getErrorData(): array { $data = []; diff --git a/src/Event/Subject.php b/src/Event/Subject.php index a617fca07..44080b421 100644 --- a/src/Event/Subject.php +++ b/src/Event/Subject.php @@ -22,7 +22,7 @@ class Subject * * @var array */ - protected array $_events = []; + protected array $events = []; /** * Constructor @@ -42,7 +42,7 @@ public function __construct(array $fields = []) */ public function addEvent(string $name): void { - $this->_events[] = $name; + $this->events[] = $name; } /** @@ -52,7 +52,7 @@ public function addEvent(string $name): void */ public function getEvents(): array { - return $this->_events; + return $this->events; } /** @@ -64,7 +64,7 @@ public function getEvents(): array */ public function hasEvent(string $name): bool { - return in_array($name, $this->_events); + return in_array($name, $this->events); } /** @@ -73,7 +73,7 @@ public function hasEvent(string $name): bool * @param array $fields Fields * @return $this */ - public function set(array $fields) + public function set(array $fields): static { foreach ($fields as $k => $v) { $this->{$k} = $v; diff --git a/src/Listener/ApiListener.php b/src/Listener/ApiListener.php index d9a363bc6..7f6862379 100644 --- a/src/Listener/ApiListener.php +++ b/src/Listener/ApiListener.php @@ -30,7 +30,7 @@ class ApiListener extends BaseListener * * @var array */ - protected array $_defaultConfig = [ + protected array $defaultConfig = [ 'viewClasses' => [ 'json' => JsonView::class, 'xml' => XmlView::class, @@ -65,7 +65,7 @@ public function implementedEvents(): array { $this->setupDetectors(); - if (!$this->_checkRequestType('api')) { + if (!$this->checkRequestType('api')) { return []; } @@ -88,7 +88,7 @@ public function implementedEvents(): array */ public function beforeHandle(EventInterface $event): void { - $this->_checkRequestMethods(); + $this->checkRequestMethods(); } /** @@ -100,16 +100,19 @@ public function beforeHandle(EventInterface $event): void */ public function respond(EventInterface $event): ?Response { - $key = $event->getSubject()->success ? 'success' : 'error'; - $apiConfig = $this->_action()->getConfig('api.' . $key); + $subject = $event->getSubject(); + assert($subject instanceof Subject); + + $key = $subject->success ? 'success' : 'error'; + $apiConfig = $this->action()->getConfig('api.' . $key); if (isset($apiConfig['exception'])) { - $this->_exceptionResponse($event, $apiConfig['exception']); + $this->exceptionResponse($event, $apiConfig['exception']); return null; } - $response = $this->render($event->getSubject()); + $response = $this->render($subject); if (!empty($apiConfig['code'])) { $response = $response->withStatus($apiConfig['code']); @@ -126,16 +129,16 @@ public function respond(EventInterface $event): ?Response * @return void * @throws \Cake\Http\Exception\MethodNotAllowedException */ - protected function _checkRequestMethods(): void + protected function checkRequestMethods(): void { - $action = $this->_action(); + $action = $this->action(); $apiConfig = $action->getConfig('api'); if (!isset($apiConfig['methods'])) { return; } - $request = $this->_request(); + $request = $this->request(); foreach ($apiConfig['methods'] as $method) { if ($request->is($method)) { return; @@ -153,15 +156,18 @@ protected function _checkRequestMethods(): void * @return void * @throws \Exception */ - protected function _exceptionResponse(EventInterface $Event, array $exceptionConfig): void + protected function exceptionResponse(EventInterface $Event, array $exceptionConfig): void { $exceptionConfig = array_merge($this->getConfig('exception'), $exceptionConfig); $class = $exceptionConfig['class']; if ($exceptionConfig['type'] === 'validate') { + $subject = $Event->getSubject(); + assert($subject instanceof Subject); + /** @var \Exception $exception */ - $exception = new $class($Event->getSubject()->entity); + $exception = new $class($subject->entity); throw $exception; } @@ -179,11 +185,11 @@ protected function _exceptionResponse(EventInterface $Event, array $exceptionCon public function render(Subject $subject): Response { $this->injectViewClasses(); - $this->_ensureSuccess($subject); - $this->_ensureData($subject); - $this->_ensureSerialize(); + $this->ensureSuccess($subject); + $this->ensureData($subject); + $this->ensureSerialize(); - return $this->_controller()->render(); + return $this->controller()->render(); } /** @@ -191,9 +197,9 @@ public function render(Subject $subject): Response * * @return void */ - protected function _ensureSerialize(): void + protected function ensureSerialize(): void { - $controller = $this->_controller(); + $controller = $this->controller(); if ($controller->viewBuilder()->getOption('serialize') !== null) { return; @@ -202,7 +208,7 @@ protected function _ensureSerialize(): void $serialize = []; $serialize[] = 'success'; - $action = $this->_action(); + $action = $this->action(); if (method_exists($action, 'viewVar')) { $serialize['data'] = $action->viewVar(); } else { @@ -219,9 +225,9 @@ protected function _ensureSerialize(): void * @param \Crud\Event\Subject $subject Subject * @return void */ - protected function _ensureSuccess(Subject $subject): void + protected function ensureSuccess(Subject $subject): void { - $controller = $this->_controller(); + $controller = $this->controller(); if ($controller->viewBuilder()->getVar('success') !== null) { return; @@ -236,10 +242,10 @@ protected function _ensureSuccess(Subject $subject): void * @param \Crud\Event\Subject $subject Subject * @return void */ - protected function _ensureData(Subject $subject): void + protected function ensureData(Subject $subject): void { - $controller = $this->_controller(); - $action = $this->_action(); + $controller = $this->controller(); + $action = $this->action(); if (method_exists($action, 'viewVar')) { $viewVar = $action->viewVar(); @@ -266,8 +272,8 @@ protected function _ensureData(Subject $subject): void $valuePath = $keyPath; } - $keyPath = $this->_expandPath($subject, $keyPath); - $valuePath = $this->_expandPath($subject, $valuePath); + $keyPath = $this->expandPath($subject, $keyPath); + $valuePath = $this->expandPath($subject, $valuePath); $data = Hash::insert($data, $keyPath, Hash::get($subjectArray, $valuePath)); } @@ -292,7 +298,7 @@ protected function _ensureData(Subject $subject): void if (isset($config['data']['raw'])) { foreach ($config['data']['raw'] as $path => $value) { - $path = $this->_expandPath($subject, $path); + $path = $this->expandPath($subject, $path); $data = Hash::insert($data, $path, $value); } } @@ -315,7 +321,7 @@ protected function _ensureData(Subject $subject): void * @param string $path Path * @return string */ - protected function _expandPath(Subject $subject, string $path): string + protected function expandPath(Subject $subject, string $path): string { $keys = []; $subjectArray = (array)$subject; @@ -338,7 +344,7 @@ protected function _expandPath(Subject $subject, string $path): string */ public function injectViewClasses(): void { - $this->_controller()->addViewClasses($this->getConfig('viewClasses')); + $this->controller()->addViewClasses($this->getConfig('viewClasses')); } /** @@ -391,7 +397,7 @@ public function setFlash(EventInterface $event): void */ public function setupDetectors(): void { - $request = $this->_request(); + $request = $this->request(); $detectors = $this->getConfig('detectors'); foreach ($detectors as $name => $config) { diff --git a/src/Listener/ApiPaginationListener.php b/src/Listener/ApiPaginationListener.php index c527c1025..fc45ff04a 100644 --- a/src/Listener/ApiPaginationListener.php +++ b/src/Listener/ApiPaginationListener.php @@ -25,7 +25,7 @@ class ApiPaginationListener extends BaseListener */ public function implementedEvents(): array { - if (!$this->_checkRequestType('api')) { + if (!$this->checkRequestType('api')) { return []; } @@ -44,12 +44,12 @@ public function beforeRender(EventInterface $event): void { $viewVar = 'data'; - $action = $this->_action(); + $action = $this->action(); if (method_exists($action, 'viewVar')) { $viewVar = $action->viewVar(); } - $paginatedResultset = $this->_controller()->viewBuilder()->getVar($viewVar); + $paginatedResultset = $this->controller()->viewBuilder()->getVar($viewVar); if (!$paginatedResultset instanceof PaginatedInterface) { return; @@ -65,7 +65,7 @@ public function beforeRender(EventInterface $event): void 'per_page' => $paginatedResultset->perPage(), ]; - $this->_controller()->set('pagination', $paginationResponse); - $this->_action()->setConfig('serialize.pagination', 'pagination'); + $this->controller()->set('pagination', $paginationResponse); + $this->action()->setConfig('serialize.pagination', 'pagination'); } } diff --git a/src/Listener/ApiQueryLogListener.php b/src/Listener/ApiQueryLogListener.php index 379384af3..b2c245481 100644 --- a/src/Listener/ApiQueryLogListener.php +++ b/src/Listener/ApiQueryLogListener.php @@ -30,7 +30,7 @@ class ApiQueryLogListener extends BaseListener * * `connections` List of connection names to log. Empty means all defined connections. */ - protected array $_defaultConfig = [ + protected array $defaultConfig = [ 'connections' => [], ]; @@ -44,7 +44,7 @@ class ApiQueryLogListener extends BaseListener */ public function implementedEvents(): array { - if (!$this->_checkRequestType('api')) { + if (!$this->checkRequestType('api')) { return []; } @@ -88,8 +88,8 @@ public function beforeRender(EventInterface $event): void return; } - $this->_action()->setConfig('serialize.queryLog', 'queryLog'); - $this->_controller()->set('queryLog', $this->getQueryLogs()); + $this->action()->setConfig('serialize.queryLog', 'queryLog'); + $this->controller()->set('queryLog', $this->getQueryLogs()); } /** @@ -99,6 +99,6 @@ public function beforeRender(EventInterface $event): void */ public function getQueryLogs(): array { - return $this->_getQueryLog(); + return $this->getQueryLog(); } } diff --git a/src/Listener/BaseListener.php b/src/Listener/BaseListener.php index 0211c5d6f..994db566c 100644 --- a/src/Listener/BaseListener.php +++ b/src/Listener/BaseListener.php @@ -81,12 +81,12 @@ public function implementedEvents(): array public function resourceName(?string $value = null) { if ($value === null) { - $this->_action()->resourceName(); + $this->action()->resourceName(); return $this; } /** @var string */ - return $this->_action()->resourceName($value); + return $this->action()->resourceName($value); } } diff --git a/src/Listener/RedirectListener.php b/src/Listener/RedirectListener.php index 08845bbaa..97c858616 100644 --- a/src/Listener/RedirectListener.php +++ b/src/Listener/RedirectListener.php @@ -22,7 +22,7 @@ class RedirectListener extends BaseListener * * @var array */ - protected array $_defaultConfig = [ + protected array $defaultConfig = [ 'readers' => [], ]; @@ -51,19 +51,19 @@ public function implementedEvents(): array public function setup(): void { $this->reader('request.key', function (Subject $subject, $key = null) { - $request = $this->_request(); + $request = $this->request(); return $request->getParam($key, null); }); $this->reader('request.data', function (Subject $subject, $key = null) { - $request = $this->_request(); + $request = $this->request(); return $request->getData($key); }); $this->reader('request.query', function (Subject $subject, $key = null) { - $request = $this->_request(); + $request = $this->request(); return $request->getQuery($key); }); @@ -112,17 +112,17 @@ public function beforeRedirect(EventInterface $event): void /** @var \Crud\Event\Subject $subject */ $subject = $event->getSubject(); - $redirects = $this->_action()->redirectConfig(); + $redirects = $this->action()->redirectConfig(); if (!$redirects) { return; } foreach ($redirects as $redirect) { - if (!$this->_getKey($subject, $redirect['reader'], $redirect['key'])) { + if (!$this->getKey($subject, $redirect['reader'], $redirect['key'])) { continue; } - $subject->url = $this->_getUrl($subject, $redirect['url']); + $subject->url = $this->getUrl($subject, $redirect['url']); break; } } @@ -138,7 +138,7 @@ public function beforeRedirect(EventInterface $event): void * @return array * @throws \Exception */ - protected function _getUrl(Subject $subject, array $url): array + protected function getUrl(Subject $subject, array $url): array { foreach ($url as $key => $value) { if (!is_array($value)) { @@ -146,11 +146,11 @@ protected function _getUrl(Subject $subject, array $url): array } if ($key === '?') { - $url[$key] = $this->_getUrl($subject, $value); + $url[$key] = $this->getUrl($subject, $value); continue; } - $url[$key] = $this->_getKey($subject, $value[0], $value[1]); + $url[$key] = $this->getKey($subject, $value[0], $value[1]); } return $url; @@ -165,7 +165,7 @@ protected function _getUrl(Subject $subject, array $url): array * @return mixed * @throws \Exception if the reader is invalid */ - protected function _getKey(Subject $subject, string $reader, string $key): mixed + protected function getKey(Subject $subject, string $reader, string $key): mixed { $callable = $this->reader($reader); diff --git a/src/Listener/RelatedModelsListener.php b/src/Listener/RelatedModelsListener.php index 01f5e60b3..7466cd238 100644 --- a/src/Listener/RelatedModelsListener.php +++ b/src/Listener/RelatedModelsListener.php @@ -8,6 +8,7 @@ use Cake\ORM\Association; use Cake\ORM\Table; use Cake\Utility\Inflector; +use Crud\Event\Subject; use RuntimeException; use function Cake\Core\pluginSplit; @@ -41,7 +42,10 @@ public function implementedEvents(): array */ public function beforePaginate(EventInterface $event): void { - $contained = $event->getSubject()->query->getContain(); + $subject = $event->getSubject(); + assert($subject instanceof Subject); + + $contained = $subject->query->getContain(); if ($contained !== []) { return; } @@ -51,7 +55,7 @@ public function beforePaginate(EventInterface $event): void return; } - $event->getSubject()->query->contain(array_keys($models)); + $subject->query->contain(array_keys($models)); } /** @@ -86,7 +90,7 @@ public function publishRelatedModels(?string $action = null, ?EntityInterface $e return; } - $controller = $this->_controller(); + $controller = $this->controller(); foreach ($models as $name => $association) { [, $associationName] = pluginSplit($association->getName()); @@ -96,11 +100,11 @@ public function publishRelatedModels(?string $action = null, ?EntityInterface $e } $finder = $this->finder($association); - $query = $association->find($finder, ...$this->_findOptions($association)); - $subject = $this->_subject(compact('name', 'viewVar', 'query', 'association', 'entity')); - $event = $this->_trigger('relatedModel', $subject); + $query = $association->find($finder, ...$this->findOptions($association)); + $subject = $this->subject(compact('name', 'viewVar', 'query', 'association', 'entity')); + $this->trigger('relatedModel', $subject); - $controller->set($event->getSubject()->viewVar, $event->getSubject()->query->toArray()); + $controller->set($subject->viewVar, $subject->query->toArray()); } } @@ -113,7 +117,7 @@ public function publishRelatedModels(?string $action = null, ?EntityInterface $e * @param \Cake\ORM\Association $association The association that we process * @return array */ - protected function _findOptions(Association $association): array + protected function findOptions(Association $association): array { return [ 'keyField' => $association->getBindingKey(), @@ -171,10 +175,10 @@ public function models(?string $action = null): array public function relatedModels(mixed $related = null, ?string $action = null): mixed { if ($related === null) { - return $this->_action($action)->getConfig('relatedModels'); + return $this->action($action)->getConfig('relatedModels'); } - return $this->_action($action)->setConfig('relatedModels', $related, false); + return $this->action($action)->setConfig('relatedModels', $related, false); } /** @@ -188,7 +192,7 @@ public function getAssociatedByType(array $types = []): array { $return = []; - $table = $this->_model(); + $table = $this->model(); assert($table instanceof Table); foreach ($table->associations()->keys() as $association) { @@ -216,7 +220,7 @@ public function getAssociatedByName(array $names): array { $return = []; - $table = $this->_model(); + $table = $this->model(); assert($table instanceof Table); foreach ($names as $association) { $associationClass = $table->associations()->get($association); diff --git a/src/Listener/SearchListener.php b/src/Listener/SearchListener.php index 15d90d632..d990aac05 100644 --- a/src/Listener/SearchListener.php +++ b/src/Listener/SearchListener.php @@ -5,6 +5,7 @@ use Cake\Event\EventInterface; use Cake\ORM\Table; +use Crud\Event\Subject; use RuntimeException; class SearchListener extends BaseListener @@ -14,7 +15,7 @@ class SearchListener extends BaseListener * * @var array */ - protected array $_defaultConfig = [ + protected array $defaultConfig = [ 'enabled' => [ 'Crud.beforeLookup', 'Crud.beforePaginate', @@ -48,7 +49,7 @@ public function injectSearch(EventInterface $event): void return; } - $repository = $this->_model(); + $repository = $this->model(); assert($repository instanceof Table); if (!$repository->behaviors()->has('Search')) { @@ -58,9 +59,12 @@ public function injectSearch(EventInterface $event): void )); } - $event->getSubject()->query->find( + $subject = $event->getSubject(); + assert($subject instanceof Subject); + + $subject->query->find( 'search', - search: $this->_request()->getQuery(), + search: $this->request()->getQuery(), collection: $this->getConfig('collection'), ); } diff --git a/src/Log/QueryLogger.php b/src/Log/QueryLogger.php index af67e14fc..20f8c712d 100644 --- a/src/Log/QueryLogger.php +++ b/src/Log/QueryLogger.php @@ -13,7 +13,7 @@ class QueryLogger extends CakeQueryLogger * * @var array */ - protected array $_logs = []; + protected array $logs = []; /** * Get logs @@ -22,7 +22,7 @@ class QueryLogger extends CakeQueryLogger */ public function getLogs(): array { - return $this->_logs; + return $this->logs; } /** @@ -30,7 +30,7 @@ public function getLogs(): array */ public function log($level, string|Stringable $message, array $context = []): void { - $this->_logs[] = $context['query']; + $this->logs[] = $context['query']; parent::log($level, $message, $context); } diff --git a/src/TestSuite/IntegrationTestCase.php b/src/TestSuite/IntegrationTestCase.php index e76c080a5..210312187 100644 --- a/src/TestSuite/IntegrationTestCase.php +++ b/src/TestSuite/IntegrationTestCase.php @@ -25,7 +25,7 @@ abstract class IntegrationTestCase extends TestCase /** * @var \Cake\Event\EventManagerInterface */ - protected EventManagerInterface $_eventManager; + protected EventManagerInterface $eventManager; /** * [setUp description] @@ -38,7 +38,7 @@ protected function setUp(): void $this->resetReflectionCache(); - $this->_eventManager = EventManager::instance(); + $this->eventManager = EventManager::instance(); $existing = Configure::read('App.paths.templates'); $existing[] = Plugin::path('Crud') . 'tests/test_app/templates/'; diff --git a/src/TestSuite/Traits/CrudTestTrait.php b/src/TestSuite/Traits/CrudTestTrait.php index c9cb0eea6..b5a038787 100644 --- a/src/TestSuite/Traits/CrudTestTrait.php +++ b/src/TestSuite/Traits/CrudTestTrait.php @@ -21,7 +21,7 @@ trait CrudTestTrait * * @var \Crud\Event\Subject */ - protected Subject $_subject; + protected Subject $subject; /** * Subscribe to Crud.beforeRender and Crud.beforeRedirect events @@ -29,23 +29,23 @@ trait CrudTestTrait * This is the two 'final' emitted events after a CRUD life cycle, * and thus will hold the final object * - * It's stored in the `$this->_subject` property + * It's stored in the `$this->subject` property * * @param \Cake\Controller\Controller|null $controller Controller * @return void */ - protected function _subscribeToEvents(?Controller $controller = null): void + protected function subscribeToEvents(?Controller $controller = null): void { if ($controller === null) { $controller = $this->controller; } $controller->Crud->on('beforeRender', function ($event): void { - $this->_subject = $event->getSubject(); + $this->subject = $event->getSubject(); }); $controller->Crud->on('beforeRedirect', function ($event): void { - $this->_subject = $event->getSubject(); + $this->subject = $event->getSubject(); }); } @@ -63,7 +63,7 @@ protected function _subscribeToEvents(?Controller $controller = null): void public function assertEvents(array $expected, EventInterface|array|null $actual = null): void { if ($actual === null) { - $actual = $this->_subject; + $actual = $this->subject; } if ($actual instanceof EventInterface) { diff --git a/src/Traits/FindMethodTrait.php b/src/Traits/FindMethodTrait.php index b7adbaf67..33d1bc113 100644 --- a/src/Traits/FindMethodTrait.php +++ b/src/Traits/FindMethodTrait.php @@ -36,7 +36,7 @@ public function findMethod(string|array|null $method = null) * @return array An array containing in the first position the finder name * and in the second the options to be passed to it. */ - protected function _extractFinder(): array + protected function extractFinder(): array { $finder = $this->findMethod(); $options = []; @@ -56,12 +56,12 @@ protected function _extractFinder(): array * @return \Cake\Datasource\EntityInterface * @throws \Exception */ - protected function _findRecord(string|int|null $id, Subject $subject): EntityInterface + protected function findRecord(string|int|null $id, Subject $subject): EntityInterface { - $repository = $this->_model(); + $repository = $this->model(); assert($repository instanceof Table); - [$finder, $options] = $this->_extractFinder(); + [$finder, $options] = $this->extractFinder(); $query = $repository->find($finder, ...$options); /** * @phpstan-ignore argument.type @@ -73,15 +73,15 @@ protected function _findRecord(string|int|null $id, Subject $subject): EntityInt 'query' => $query, ]); - $this->_trigger('beforeFind', $subject); + $this->trigger('beforeFind', $subject); $entity = $subject->query->first(); if (!$entity) { - $this->_notFound($id, $subject); + $this->notFound($id, $subject); } $subject->set(['entity' => $entity, 'success' => true]); - $this->_trigger('afterFind', $subject); + $this->trigger('afterFind', $subject); return $entity; } @@ -94,10 +94,10 @@ protected function _findRecord(string|int|null $id, Subject $subject): EntityInt * @return void * @throws \Exception */ - protected function _notFound(string|int|null $id, Subject $subject): void + protected function notFound(string|int|null $id, Subject $subject): void { $subject->set(['success' => false]); - $this->_trigger('recordNotFound', $subject); + $this->trigger('recordNotFound', $subject); $message = $this->message('recordNotFound', compact('id')); /** @var class-string<\Exception> $exceptionClass */ diff --git a/src/Traits/QueryLogTrait.php b/src/Traits/QueryLogTrait.php index 0082953ef..34bbc3bbc 100644 --- a/src/Traits/QueryLogTrait.php +++ b/src/Traits/QueryLogTrait.php @@ -12,7 +12,7 @@ trait QueryLogTrait * * @return array */ - protected function _getQueryLog(): array + protected function getQueryLog(): array { $queryLog = []; diff --git a/src/Traits/RedirectTrait.php b/src/Traits/RedirectTrait.php index 0bad5cfd5..038a6b5e4 100644 --- a/src/Traits/RedirectTrait.php +++ b/src/Traits/RedirectTrait.php @@ -49,9 +49,9 @@ public function redirectConfig(?string $name = null, ?array $config = null): mix * @param array|string|null $default Default URL to use redirect_url is not found in request or data * @return array|string */ - protected function _refererRedirectUrl(array|string|null $default = null): array|string + protected function refererRedirectUrl(array|string|null $default = null): array|string { - return $this->_redirectUrl($this->_controller()->referer($default, true)); + return $this->redirectUrl($this->controller()->referer($default, true)); } /** @@ -60,9 +60,9 @@ protected function _refererRedirectUrl(array|string|null $default = null): array * @param array|string $default Default URL to use if _redirect_url if not found in request or data. * @return array|string */ - protected function _redirectUrl(array|string $default): array|string + protected function redirectUrl(array|string $default): array|string { - $request = $this->_request(); + $request = $this->request(); return $request->getData('_redirect_url') ?? $request->getQuery('_redirect_url') @@ -79,18 +79,18 @@ protected function _redirectUrl(array|string $default): array|string * @param int $status Status code * @return \Cake\Http\Response|null */ - protected function _redirect(Subject $subject, string|array $url, int $status = 302): ?Response + protected function redirect(Subject $subject, string|array $url, int $status = 302): ?Response { - $url = $this->_redirectUrl($url); + $url = $this->redirectUrl($url); $subject->url = $url; $subject->status = $status; - $event = $this->_trigger('beforeRedirect', $subject); + $event = $this->trigger('beforeRedirect', $subject); if ($event->isStopped()) { - return $this->_controller()->getResponse(); + return $this->controller()->getResponse(); } - return $this->_controller()->redirect($subject->url, $subject->status); + return $this->controller()->redirect($subject->url, $subject->status); } } diff --git a/src/Traits/ViewTrait.php b/src/Traits/ViewTrait.php index 2c4c9751e..5937f434a 100644 --- a/src/Traits/ViewTrait.php +++ b/src/Traits/ViewTrait.php @@ -20,7 +20,7 @@ trait ViewTrait public function view(mixed $view = null): mixed { if ($view === null) { - return $this->getConfig('view') ?: $this->_request()->getParam('action'); + return $this->getConfig('view') ?: $this->request()->getParam('action'); } return $this->setConfig('view', $view); diff --git a/src/Traits/ViewVarTrait.php b/src/Traits/ViewVarTrait.php index 3074cd243..0528c4439 100644 --- a/src/Traits/ViewVarTrait.php +++ b/src/Traits/ViewVarTrait.php @@ -24,9 +24,9 @@ public function publishViewVar(EventInterface $event): void } $viewVar = $this->viewVar(); - $controller = $this->_controller(); + $controller = $this->controller(); - $controller->set($viewVar, $this->_deriveViewValue($event)); + $controller->set($viewVar, $this->deriveViewValue($event)); $controller->set('viewVar', $viewVar); } @@ -41,7 +41,7 @@ public function publishViewVar(EventInterface $event): void public function viewVar(mixed $name = null): mixed { if ($name === null) { - return $this->getConfig('viewVar') ?: $this->_deriveViewVar(); + return $this->getConfig('viewVar') ?: $this->deriveViewVar(); } return $this->setConfig('viewVar', $name); @@ -56,14 +56,14 @@ public function viewVar(mixed $name = null): mixed * @throws \Exception * @return string */ - protected function _deriveViewVar(): string + protected function deriveViewVar(): string { if ($this->scope() === 'table') { - return Inflector::variable($this->_controller()->getName()); + return Inflector::variable($this->controller()->getName()); } if ($this->scope() === 'entity') { - return Inflector::variable(Inflector::singularize($this->_controller()->getName())); + return Inflector::variable(Inflector::singularize($this->controller()->getName())); } throw new Exception('Unknown action scope: ' . (string)$this->scope()); @@ -77,9 +77,9 @@ protected function _deriveViewVar(): string * @return mixed * @throws \Exception */ - protected function _deriveViewValue(EventInterface $event): mixed + protected function deriveViewValue(EventInterface $event): mixed { - $key = $this->_action()->subjectEntityKey(); + $key = $this->action()->subjectEntityKey(); return $event->getSubject()->{$key}; } diff --git a/tests/TestCase/Action/AddActionTest.php b/tests/TestCase/Action/AddActionTest.php index 753da78fc..cbcf84d29 100644 --- a/tests/TestCase/Action/AddActionTest.php +++ b/tests/TestCase/Action/AddActionTest.php @@ -7,12 +7,14 @@ use Cake\Core\Configure; use Cake\Routing\Router; use Crud\TestSuite\IntegrationTestCase; +use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations; use PHPUnit\Framework\Attributes\DataProvider; /** * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt */ +#[AllowMockObjectsWithoutExpectations] class AddActionTest extends IntegrationTestCase { /** @@ -30,14 +32,14 @@ class AddActionTest extends IntegrationTestCase public string $tableClass = 'Crud\Test\App\Model\Table\BlogsTable'; /** - * Test the normal HTTP GET flow of _get + * Test the normal HTTP GET flow of handleGet * * @return void */ public function testActionGet() { $this->get('/blogs/add'); - $result = (string)$this->_response->getBody(); + $result = (string)$this->response->getBody(); $expected = 'New Blog'; $this->assertStringContainsString($expected, $result, 'legend do not match the expected value'); @@ -53,7 +55,7 @@ public function testActionGet() } /** - * Test the normal HTTP GET flow of _get with query args + * Test the normal HTTP GET flow of handleGet with query args * * Providing ?name=test should fill out the value in the 'name' input field * @@ -62,7 +64,7 @@ public function testActionGet() public function testActionGetWithQueryArgs() { $this->get('/blogs/add?name=test'); - $result = (string)$this->_response->getBody(); + $result = (string)$this->response->getBody(); $expected = 'New Blog'; $this->assertStringContainsString($expected, $result, 'legend do not match the expected value'); @@ -84,13 +86,12 @@ public function testActionGetWithQueryArgs() */ public function testActionPost() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -105,10 +106,11 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $this->post('/blogs/add', [ @@ -117,8 +119,8 @@ function ($event) { ]); $this->assertEvents(['beforeSave', 'afterSave', 'setFlash', 'beforeRedirect']); - $this->assertTrue($this->_subject->success); - $this->assertTrue($this->_subject->created); + $this->assertTrue($this->subject->success); + $this->assertTrue($this->subject->created); $this->assertRedirect('/blogs'); } @@ -131,13 +133,12 @@ function ($event) { */ public function testActionPostWithAddRedirect() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -152,10 +153,11 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $this->post('/blogs/add', [ @@ -165,8 +167,8 @@ function ($event) { ]); $this->assertEvents(['beforeSave', 'afterSave', 'setFlash', 'beforeRedirect']); - $this->assertTrue($this->_subject->success); - $this->assertTrue($this->_subject->created); + $this->assertTrue($this->subject->success); + $this->assertTrue($this->subject->created); $this->assertRedirect('/blogs/add'); } @@ -178,13 +180,12 @@ function ($event) { */ public function testActionPostWithEditRedirect() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -199,10 +200,11 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $this->post('/blogs/add', [ @@ -212,8 +214,8 @@ function ($event) { ]); $this->assertEvents(['beforeSave', 'afterSave', 'setFlash', 'beforeRedirect']); - $this->assertTrue($this->_subject->success); - $this->assertTrue($this->_subject->created); + $this->assertTrue($this->subject->success); + $this->assertTrue($this->subject->created); $this->assertRedirect('/blogs/edit/6'); } @@ -224,13 +226,12 @@ function ($event) { */ public function testActionPostErrorSave() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -245,9 +246,9 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); $blogs = $this->getMockForModel( $this->tableClass, @@ -261,6 +262,7 @@ function ($event) { $this->getTableLocator()->set('Blogs', $blogs); }, + ['priority' => 11], ); $this->post('/blogs/add', [ @@ -269,8 +271,8 @@ function ($event) { ]); $this->assertEvents(['beforeSave', 'afterSave', 'setFlash', 'beforeRender']); - $this->assertFalse($this->_subject->success); - $this->assertFalse($this->_subject->created); + $this->assertFalse($this->subject->success); + $this->assertFalse($this->subject->created); } /** @@ -280,13 +282,12 @@ function ($event) { */ public function testActionPostValidationErrors() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -301,11 +302,11 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); - $this->_controller->Blogs + $this->controller->Blogs ->getValidator() ->requirePresence('name') ->add('name', [ @@ -315,6 +316,7 @@ function ($event) { ], ]); }, + ['priority' => 11], ); $this->post('/blogs/add', [ @@ -324,8 +326,8 @@ function ($event) { $this->assertEvents(['beforeSave', 'afterSave', 'setFlash', 'beforeRender']); - $this->assertFalse($this->_subject->success); - $this->assertFalse($this->_subject->created); + $this->assertFalse($this->subject->success); + $this->assertFalse($this->subject->created); if (version_compare(Configure::version(), '4.3.0', '>=')) { $expected = '
Name need to be at least 10 characters long
'; @@ -334,7 +336,7 @@ function ($event) { } $this->assertStringContainsString( $expected, - (string)$this->_response->getBody(), + (string)$this->response->getBody(), 'Could not find validation error in HTML', ); } @@ -393,36 +395,36 @@ public static function apiUpdateHttpMethodProvider() #[DataProvider('apiUpdateHttpMethodProvider')] public function testApiCreate($method) { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component ->expects($this->never()) ->method('set'); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); - $this->_controller->Crud->addListener('api', 'Crud.Api'); + $this->controller->Crud->addListener('api', 'Crud.Api'); }, + ['priority' => 11], ); $this->{$method}('/blogs/add.json', [ 'name' => '6th blog post', 'body' => 'Amazing blog post', ]); - $this->assertTrue($this->_subject->success); - $this->assertTrue($this->_subject->created); + $this->assertTrue($this->subject->success); + $this->assertTrue($this->subject->created); $this->assertEquals( ['success' => true, 'data' => ['id' => 6]], - json_decode((string)$this->_response->getBody(), true), + json_decode((string)$this->response->getBody(), true), ); } @@ -436,30 +438,29 @@ function ($event) { #[DataProvider('apiUpdateHttpMethodProvider')] public function testApiCreateError($method) { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { - if (get_class($this->_controller) === 'Cake\Controller\ErrorController') { + if (get_class($this->controller) === 'Cake\Controller\ErrorController') { return; } $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component ->expects($this->never()) ->method('set'); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); - $this->_controller->Crud->addListener('api', 'Crud.Api'); + $this->controller->Crud->addListener('api', 'Crud.Api'); - $this->_controller->Blogs + $this->controller->Blogs ->getValidator() ->requirePresence('name') ->add('name', [ @@ -469,6 +470,7 @@ function ($event) { ], ]); }, + ['priority' => 11], ); $this->{$method}('/blogs/add.json', [ @@ -490,30 +492,29 @@ function ($event) { #[DataProvider('apiUpdateHttpMethodProvider')] public function testApiCreateErrors($method) { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { - if (get_class($this->_controller) === 'Cake\Controller\ErrorController') { + if (get_class($this->controller) === 'Cake\Controller\ErrorController') { return; } $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component ->expects($this->never()) ->method('set'); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); - $this->_controller->Crud->addListener('api', 'Crud.Api'); + $this->controller->Crud->addListener('api', 'Crud.Api'); - $this->_controller->Blogs + $this->controller->Blogs ->getValidator() ->requirePresence('name') ->requirePresence('body') @@ -524,6 +525,7 @@ function ($event) { ], ]); }, + ['priority' => 11], ); $this->{$method}('/blogs/add.json', [ @@ -542,13 +544,12 @@ function ($event) { */ public function testStopAddWithDefaultSubjectSuccess() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -563,11 +564,11 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); - $this->_controller->Crud->on('beforeSave', function ($event) { + $this->controller->Crud->on('beforeSave', function ($event) { $event->stopPropagation(); }); @@ -579,12 +580,13 @@ function ($event) { $this->getTableLocator()->set('Blogs', $model); }, + ['priority' => 11], ); $this->post('/blogs/add'); $this->assertEvents(['beforeSave', 'setFlash', 'beforeRedirect']); - $this->assertFalse($this->_subject->success); + $this->assertFalse($this->subject->success); $this->assertRedirect('/blogs'); } @@ -596,13 +598,12 @@ function ($event) { */ public function testStopAddWithManuallySetSubjectSuccess() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -617,11 +618,11 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); - $this->_controller->Crud->on('beforeSave', function ($event) { + $this->controller->Crud->on('beforeSave', function ($event) { $event->stopPropagation(); $event->getSubject()->success = true; // assert this }); @@ -634,12 +635,13 @@ function ($event) { $this->getTableLocator()->set('Blogs', $model); }, + ['priority' => 11], ); $this->post('/blogs/add'); $this->assertEvents(['beforeSave', 'afterSave', 'setFlash', 'beforeRedirect']); - $this->assertTrue($this->_subject->success); + $this->assertTrue($this->subject->success); $this->assertRedirect('/blogs'); } } diff --git a/tests/TestCase/Action/BaseActionTest.php b/tests/TestCase/Action/BaseActionTest.php index 485e09018..fcd9a5c3c 100644 --- a/tests/TestCase/Action/BaseActionTest.php +++ b/tests/TestCase/Action/BaseActionTest.php @@ -20,11 +20,13 @@ use Crud\Test\App\Action\TestGetAction; use Crud\TestSuite\TestCase; use Exception; +use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations; /** * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt */ +#[AllowMockObjectsWithoutExpectations] class BaseActionTest extends TestCase { protected ServerRequest $Request; @@ -55,11 +57,11 @@ protected function setUp(): void $this->getTableLocator()->get('CrudExamples')->setAlias('MyModel'); $this->actionClassName = $this->getMockBuilder(TestAction::class) - ->onlyMethods(['_handle']) + ->onlyMethods(['handleRequest']) ->disableOriginalConstructor() ->getMock(); $this->ActionClass = new $this->actionClassName($this->Controller); - $this->_configureAction($this->ActionClass); + $this->configureAction($this->ActionClass); } public function tearDown(): void @@ -75,7 +77,7 @@ public function tearDown(): void ); } - protected function _configureAction($action) + protected function configureAction($action) { $action->setConfig([ 'action' => 'add', @@ -140,7 +142,7 @@ public function testImplementedEvents() } /** - * Test that an enabled action will call _handle + * Test that an enabled action will call handleRequest * * @return void */ @@ -156,20 +158,18 @@ public function testEnabledActionWorks() ->willReturn('GET'); $Action = $this->getMockBuilder(TestAction::class) - ->onlyMethods(['_request', '_handle']) + ->onlyMethods(['request', 'handleRequest']) ->setConstructorArgs([$this->Controller]) ->getMock(); $Action - ->expects($this->any()) - ->method('_request') - ->with() + ->method('request') ->willReturn($Request); $Action ->expects($this->once()) - ->method('_handle') + ->method('handleRequest') ->willReturn(true); - $this->_configureAction($Action); + $this->configureAction($Action); $Action->setConfig('action', 'add'); $expected = true; @@ -513,7 +513,7 @@ public function testBadRequestMethodMessage() /** * testHandle * - * Test that calling handle will invoke _handle + * Test that calling handle will invoke handleRequest * when the action is enabbled * * @return void @@ -521,7 +521,7 @@ public function testBadRequestMethodMessage() public function testHandle() { $Action = $this->getMockBuilder(TestGetAction::class) - ->onlyMethods(['_request', 'getConfig', '_get']) + ->onlyMethods(['request', 'getConfig', 'handleGet']) ->setConstructorArgs([$this->Controller]) ->getMock(); @@ -540,11 +540,11 @@ public function testHandle() ->willReturn(true); $Action ->expects($this->once()) - ->method('_request') + ->method('request') ->willReturn($Request); $Action ->expects($this->once()) - ->method('_get'); + ->method('handleGet'); $Action->handle(); } @@ -552,7 +552,7 @@ public function testHandle() /** * testHandleDisabled * - * Test that calling handle will not invoke _handle + * Test that calling handle will not invoke handleRequest * when the action is disabled * * @return void @@ -560,7 +560,7 @@ public function testHandle() public function testHandleDisabled() { $Action = $this->getMockBuilder(TestAction::class) - ->onlyMethods(['getConfig', '_handle']) + ->onlyMethods(['getConfig', 'handleRequest']) ->setConstructorArgs([$this->Controller]) ->getMock(); @@ -571,7 +571,7 @@ public function testHandleDisabled() ->willReturn(false); $Action ->expects($this->never()) - ->method('_handle'); + ->method('handleRequest'); $Action->handle(); } @@ -579,7 +579,7 @@ public function testHandleDisabled() /** * testGenericHandle * - * Test that calling handle will invoke _handle + * Test that calling handle will invoke handleRequest * when the requestType handler is not available * * @return void @@ -587,7 +587,7 @@ public function testHandleDisabled() public function testGenericHandle() { $Action = $this->getMockBuilder(TestAction::class) - ->onlyMethods(['_request', 'getConfig', '_handle']) + ->onlyMethods(['request', 'getConfig', 'handleRequest']) ->setConstructorArgs([$this->Controller]) ->getMock(); @@ -606,11 +606,11 @@ public function testGenericHandle() ->willReturn(true); $Action ->expects($this->once()) - ->method('_request') + ->method('request') ->willReturn($Request); $Action ->expects($this->once()) - ->method('_handle'); + ->method('handleRequest'); $Action->handle(); } @@ -618,7 +618,7 @@ public function testGenericHandle() /** * testHandleException * - * Test that calling handle will not invoke _handle + * Test that calling handle will not invoke handleRequest * when the action is disabled * * @return void @@ -628,7 +628,7 @@ public function testHandleException() $this->expectException(NotImplementedException::class); $Action = $this->getMockBuilder(BaseAction::class) - ->onlyMethods(['_request', 'getConfig']) + ->onlyMethods(['request', 'getConfig']) ->setConstructorArgs([$this->Controller]) ->getMock(); @@ -647,7 +647,7 @@ public function testHandleException() ->willReturn(true); $Action ->expects($this->once()) - ->method('_request') + ->method('request') ->willReturn($Request); $Action->handle(); diff --git a/tests/TestCase/Action/Bulk/DeleteActionTest.php b/tests/TestCase/Action/Bulk/DeleteActionTest.php index e7181770f..1c51b3f5f 100644 --- a/tests/TestCase/Action/Bulk/DeleteActionTest.php +++ b/tests/TestCase/Action/Bulk/DeleteActionTest.php @@ -51,13 +51,12 @@ public static function allHttpMethodProvider() #[DataProvider('allHttpMethodProvider')] public function testAllRequestMethods($method) { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -72,10 +71,11 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $this->{$method}('/blogs/deleteAll', [ @@ -86,7 +86,7 @@ function ($event) { ]); $this->assertEvents(['beforeBulk', 'afterBulk', 'setFlash', 'beforeRedirect']); - $this->assertTrue($this->_subject->success); + $this->assertTrue($this->subject->success); $this->assertRedirect('/blogs'); } @@ -97,13 +97,12 @@ function ($event) { */ public function testStopBeforeBulk() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -118,14 +117,15 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); - $this->_controller->Crud->on('beforeBulk', function ($event) { + $this->controller->Crud->on('beforeBulk', function ($event) { $event->stopPropagation(); }); }, + ['priority' => 11], ); $this->post('/blogs/deleteAll', [ @@ -136,7 +136,7 @@ function ($event) { ]); $this->assertEvents(['beforeBulk', 'setFlash', 'beforeRedirect']); - $this->assertFalse($this->_subject->success); + $this->assertFalse($this->subject->success); $this->assertRedirect('/blogs'); } @@ -147,13 +147,12 @@ function ($event) { */ public function testUuidRequestData() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -168,10 +167,11 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $this->post('/users/deleteAll', [ @@ -182,7 +182,7 @@ function ($event) { ]); $this->assertEvents(['beforeBulk', 'afterBulk', 'setFlash', 'beforeRedirect']); - $this->assertTrue($this->_subject->success); + $this->assertTrue($this->subject->success); $this->assertRedirect('/users'); } } diff --git a/tests/TestCase/Action/Bulk/SetValueActionTest.php b/tests/TestCase/Action/Bulk/SetValueActionTest.php index 5c725c5c2..d0a18db54 100644 --- a/tests/TestCase/Action/Bulk/SetValueActionTest.php +++ b/tests/TestCase/Action/Bulk/SetValueActionTest.php @@ -51,13 +51,12 @@ public static function allHttpMethodProvider() #[DataProvider('allHttpMethodProvider')] public function testAllRequestMethods($method) { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -72,10 +71,11 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $this->{$method}('/blogs/deactivateAll', [ @@ -86,7 +86,7 @@ function ($event) { ]); $this->assertEvents(['beforeBulk', 'afterBulk', 'setFlash', 'beforeRedirect']); - $this->assertTrue($this->_subject->success); + $this->assertTrue($this->subject->success); $this->assertRedirect('/blogs'); } @@ -97,13 +97,12 @@ function ($event) { */ public function testStopBeforeBulk() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -118,14 +117,15 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); - $this->_controller->Crud->on('beforeBulk', function ($event) { + $this->controller->Crud->on('beforeBulk', function ($event) { $event->stopPropagation(); }); }, + ['priority' => 11], ); $this->post('/blogs/deactivateAll', [ @@ -136,7 +136,7 @@ function ($event) { ]); $this->assertEvents(['beforeBulk', 'setFlash', 'beforeRedirect']); - $this->assertFalse($this->_subject->success); + $this->assertFalse($this->subject->success); $this->assertRedirect('/blogs'); } @@ -147,13 +147,12 @@ function ($event) { */ public function testUuidRequestData() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -168,10 +167,11 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $this->post('/users/deactivateAll', [ @@ -182,7 +182,7 @@ function ($event) { ]); $this->assertEvents(['beforeBulk', 'afterBulk', 'setFlash', 'beforeRedirect']); - $this->assertTrue($this->_subject->success); + $this->assertTrue($this->subject->success); $this->assertRedirect('/users'); } } diff --git a/tests/TestCase/Action/Bulk/ToggleActionTest.php b/tests/TestCase/Action/Bulk/ToggleActionTest.php index f8175eb24..c4e7e9392 100644 --- a/tests/TestCase/Action/Bulk/ToggleActionTest.php +++ b/tests/TestCase/Action/Bulk/ToggleActionTest.php @@ -51,13 +51,12 @@ public static function allHttpMethodProvider() #[DataProvider('allHttpMethodProvider')] public function testAllRequestMethods($method) { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -72,10 +71,11 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $this->{$method}('/blogs/toggleActiveAll', [ @@ -86,7 +86,7 @@ function ($event) { ]); $this->assertEvents(['beforeBulk', 'afterBulk', 'setFlash', 'beforeRedirect']); - $this->assertTrue($this->_subject->success); + $this->assertTrue($this->subject->success); $this->assertRedirect('/blogs'); } @@ -97,13 +97,12 @@ function ($event) { */ public function testStopBeforeBulk() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -118,14 +117,15 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); - $this->_controller->Crud->on('beforeBulk', function ($event) { + $this->controller->Crud->on('beforeBulk', function ($event) { $event->stopPropagation(); }); }, + ['priority' => 11], ); $this->post('/blogs/toggleActiveAll', [ @@ -136,7 +136,7 @@ function ($event) { ]); $this->assertEvents(['beforeBulk', 'setFlash', 'beforeRedirect']); - $this->assertFalse($this->_subject->success); + $this->assertFalse($this->subject->success); $this->assertRedirect('/blogs'); } @@ -147,13 +147,12 @@ function ($event) { */ public function testUuidRequestData() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -168,10 +167,11 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $this->post('/users/toggleActiveAll', [ @@ -182,7 +182,7 @@ function ($event) { ]); $this->assertEvents(['beforeBulk', 'afterBulk', 'setFlash', 'beforeRedirect']); - $this->assertTrue($this->_subject->success); + $this->assertTrue($this->subject->success); $this->assertRedirect('/users'); } } diff --git a/tests/TestCase/Action/DeleteActionTest.php b/tests/TestCase/Action/DeleteActionTest.php index 8684db89d..b32c0faf1 100644 --- a/tests/TestCase/Action/DeleteActionTest.php +++ b/tests/TestCase/Action/DeleteActionTest.php @@ -48,13 +48,12 @@ public static function allHttpMethodProvider() #[DataProvider('allHttpMethodProvider')] public function testAllRequestMethods($method) { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -69,9 +68,9 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); $blogs = $this->getMockForModel( $this->tableClass, @@ -85,12 +84,13 @@ function ($event) { $this->getTableLocator()->set('Blogs', $blogs); }, + ['priority' => 11], ); $this->{$method}('/blogs/delete/1'); $this->assertEvents(['beforeFind', 'afterFind', 'beforeDelete', 'afterDelete', 'setFlash', 'beforeRedirect']); - $this->assertTrue($this->_subject->success); + $this->assertTrue($this->subject->success); $this->assertRedirect('/blogs'); } @@ -101,13 +101,12 @@ function ($event) { */ public function testStopDelete() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -122,11 +121,11 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); - $this->_controller->Crud->on('beforeDelete', function ($event) { + $this->controller->Crud->on('beforeDelete', function ($event) { $event->stopPropagation(); }); @@ -141,12 +140,13 @@ function ($event) { $this->getTableLocator()->set('Blogs', $blogs); }, + ['priority' => 11], ); $this->post('/blogs/delete/1'); $this->assertEvents(['beforeFind', 'afterFind', 'beforeDelete', 'setFlash', 'beforeRedirect']); - $this->assertFalse($this->_subject->success); + $this->assertFalse($this->subject->success); $this->assertRedirect('/blogs'); } @@ -157,13 +157,12 @@ function ($event) { */ public function testStopBeforeRedirect() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -178,11 +177,11 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); - $this->_controller->Crud->on('beforeRedirect', function ($event) { + $this->controller->Crud->on('beforeRedirect', function ($event) { $event->stopPropagation(); }); @@ -198,12 +197,13 @@ function ($event) { $this->getTableLocator()->set('Blogs', $blogs); }, + ['priority' => 11], ); $this->delete('/blogs/delete/2'); $this->assertEvents(['beforeFind', 'afterFind', 'beforeDelete', 'afterDelete', 'setFlash', 'beforeRedirect']); - $this->assertTrue($this->_subject->success); + $this->assertTrue($this->subject->success); $this->assertNoRedirect(); } } diff --git a/tests/TestCase/Action/EditActionTest.php b/tests/TestCase/Action/EditActionTest.php index 0140b6f1e..38da99aa8 100644 --- a/tests/TestCase/Action/EditActionTest.php +++ b/tests/TestCase/Action/EditActionTest.php @@ -28,14 +28,14 @@ class EditActionTest extends IntegrationTestCase public string $tableClass = 'Crud\Test\App\Model\Table\BlogsTable'; /** - * Test the normal HTTP GET flow of _get + * Test the normal HTTP GET flow of handleGet * * @return void */ public function testActionGet() { $this->get('/blogs/edit/1'); - $result = (string)$this->_response->getBody(); + $result = (string)$this->response->getBody(); $expected = 'Edit Blog'; $this->assertStringContainsString($expected, $result, 'legend do not match the expected value'); @@ -51,7 +51,7 @@ public function testActionGet() } /** - * Test the normal HTTP GET flow of _get with query args + * Test the normal HTTP GET flow of handleGet with query args * * Providing ?name=test should fill out the value in the 'name' input field * @@ -60,7 +60,7 @@ public function testActionGet() public function testActionGetWithQueryArgs() { $this->get('/blogs/edit/1?name=test'); - $result = (string)$this->_response->getBody(); + $result = (string)$this->response->getBody(); $expected = 'Edit Blog'; $this->assertStringContainsString($expected, $result, 'legend do not match the expected value'); @@ -82,17 +82,17 @@ public function testActionGetWithQueryArgs() */ public function testCustomFinder() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { - $this->_controller->Crud->action('edit') + $this->controller->Crud->action('edit') ->findMethod(['withCustomOptions' => ['foo' => 'bar']]); }, + ['priority' => 11], ); $this->get('/blogs/edit/1'); - $this->assertSame(['foo' => 'bar'], $this->_controller->Blogs->customOptions); + $this->assertSame(['foo' => 'bar'], $this->controller->Blogs->customOptions); } /** @@ -102,13 +102,12 @@ function ($event) { */ public function testActionPost() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -123,10 +122,11 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $this->post('/blogs/edit/1', [ @@ -135,8 +135,8 @@ function ($event) { ]); $this->assertEvents(['beforeFind', 'afterFind', 'beforeSave', 'afterSave', 'setFlash', 'beforeRedirect']); - $this->assertTrue($this->_subject->success); - $this->assertFalse($this->_subject->created); + $this->assertTrue($this->subject->success); + $this->assertFalse($this->subject->created); $this->assertRedirect('/blogs'); } @@ -147,13 +147,12 @@ function ($event) { */ public function testActionPostErrorSave() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -168,9 +167,9 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); $blogs = $this->getMockForModel( $this->tableClass, @@ -184,6 +183,7 @@ function ($event) { $this->getTableLocator()->set('Blogs', $blogs); }, + ['priority' => 11], ); $this->put('/blogs/edit/1', [ @@ -192,8 +192,8 @@ function ($event) { ]); $this->assertEvents(['beforeFind', 'afterFind', 'beforeSave', 'afterSave', 'setFlash', 'beforeRender']); - $this->assertFalse($this->_subject->success); - $this->assertFalse($this->_subject->created); + $this->assertFalse($this->subject->success); + $this->assertFalse($this->subject->created); } /** @@ -203,13 +203,12 @@ function ($event) { */ public function testActionPostValidationErrors() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -224,11 +223,11 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); - $this->_controller->Blogs + $this->controller->Blogs ->getValidator() ->requirePresence('name') ->add('name', [ @@ -238,6 +237,7 @@ function ($event) { ], ]); }, + ['priority' => 11], ); $this->put('/blogs/edit/1', [ @@ -247,8 +247,8 @@ function ($event) { $this->assertEvents(['beforeFind', 'afterFind', 'beforeSave', 'afterSave', 'setFlash', 'beforeRender']); - $this->assertFalse($this->_subject->success); - $this->assertFalse($this->_subject->created); + $this->assertFalse($this->subject->success); + $this->assertFalse($this->subject->created); if (version_compare(Configure::version(), '4.3.0', '>=')) { $expected = '
Name need to be at least 10 characters long
'; @@ -257,7 +257,7 @@ function ($event) { } $this->assertStringContainsString( $expected, - (string)$this->_response->getBody(), + (string)$this->response->getBody(), 'Could not find validation error in HTML', ); } @@ -269,13 +269,12 @@ function ($event) { */ public function testActionPatch() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { $component = $this->getMockBuilder(FlashComponent::class) ->onlyMethods(['set']) - ->setConstructorArgs([$this->_controller->components()]) + ->setConstructorArgs([$this->controller->components()]) ->getMock(); $component @@ -290,10 +289,11 @@ function ($event) { ], ); - $this->_controller->components()->set('Flash', $component); + $this->controller->components()->set('Flash', $component); - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $this->patch('/blogs/edit/1', [ @@ -302,8 +302,8 @@ function ($event) { ]); $this->assertEvents(['beforeFind', 'afterFind', 'beforeSave', 'afterSave', 'setFlash', 'beforeRedirect']); - $this->assertTrue($this->_subject->success); - $this->assertFalse($this->_subject->created); + $this->assertTrue($this->subject->success); + $this->assertFalse($this->subject->created); $this->assertRedirect('/blogs'); } } diff --git a/tests/TestCase/Action/IndexActionTest.php b/tests/TestCase/Action/IndexActionTest.php index 0c12cf5bf..13b5deb5c 100644 --- a/tests/TestCase/Action/IndexActionTest.php +++ b/tests/TestCase/Action/IndexActionTest.php @@ -42,18 +42,18 @@ public static function allHttpMethodProvider() #[DataProvider('allHttpMethodProvider')] public function testGet($method) { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $this->{$method}('/blogs'); $this->assertStringContainsString( 'Page 1 of 2, showing 3 records out of 5 total', - (string)$this->_response->getBody(), + (string)$this->response->getBody(), ); $this->assertEvents(['beforePaginate', 'afterPaginate', 'beforeRender']); $this->assertNotNull($this->viewVariable('viewVar')); @@ -68,20 +68,20 @@ function ($event) { */ public function testGetWithViewVar() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { - $this->_controller->Crud->action('index')->viewVar('items'); - $this->_subscribeToEvents($this->_controller); + $this->controller->Crud->action('index')->viewVar('items'); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $this->get('/blogs'); $this->assertStringContainsString( 'Page 1 of 2, showing 3 records out of 5 total', - (string)$this->_response->getBody(), + (string)$this->response->getBody(), ); $this->assertEvents(['beforePaginate', 'afterPaginate', 'beforeRender']); $this->assertNotNull($this->viewVariable('viewVar')); @@ -96,20 +96,20 @@ function ($event) { */ public function testModifyQueryInEvent() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function () { - $this->_controller->Crud->on('beforePaginate', function ($event) { + $this->controller->Crud->on('beforePaginate', function ($event) { $event->getSubject()->query->where(['id <' => 2]); }); }, + ['priority' => 11], ); $this->get('/blogs'); $this->assertStringContainsString( 'Page 1 of 1, showing 1 records out of 1 total', - (string)$this->_response->getBody(), + (string)$this->response->getBody(), ); } @@ -120,17 +120,17 @@ function () { */ public function testGetWithCustomFinder() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function () { - $this->_controller->Crud->action('index') + $this->controller->Crud->action('index') ->findMethod(['withCustomOptions' => ['foo' => 'bar']]); }, + ['priority' => 11], ); $this->get('/blogs'); - $this->assertSame(['foo' => 'bar'], $this->_controller->Blogs->customOptions); + $this->assertSame(['foo' => 'bar'], $this->controller->Blogs->customOptions); } /** @@ -140,16 +140,16 @@ function () { */ public function testForPageOutOfBounds() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $this->get('/blogs?page=999&foo=bar'); - $this->assertSame(302, $this->_response->getStatusCode()); - $this->assertSame('http://localhost/blogs?page=2&foo=bar', $this->_response->getHeaderLine('Location')); + $this->assertSame(302, $this->response->getStatusCode()); + $this->assertSame('http://localhost/blogs?page=2&foo=bar', $this->response->getHeaderLine('Location')); } } diff --git a/tests/TestCase/Action/LookupActionTest.php b/tests/TestCase/Action/LookupActionTest.php index 1235a2925..ca5a189de 100644 --- a/tests/TestCase/Action/LookupActionTest.php +++ b/tests/TestCase/Action/LookupActionTest.php @@ -25,12 +25,12 @@ class LookupActionTest extends IntegrationTestCase */ public function testGet() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function () { - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $expected = [ @@ -54,12 +54,12 @@ function () { */ public function testGetWithCustomParams() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function () { - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $expected = [ @@ -83,12 +83,12 @@ function () { */ public function testGetWithCustomKeyValueFields() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function () { - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $expected = [ @@ -112,14 +112,14 @@ function () { */ public function testGetWithQueryModification() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function () { - $this->_controller->Crud->on('beforeLookup', function ($event) { + $this->controller->Crud->on('beforeLookup', function ($event) { $event->getSubject()->query->where(['id <' => 2]); }); }, + ['priority' => 11], ); $expected = [ @@ -138,17 +138,17 @@ function () { */ public function testGetWithCustomFinder() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function () { - $this->_subscribeToEvents($this->_controller); - $this->_controller->Crud->action('lookup') + $this->subscribeToEvents($this->controller); + $this->controller->Crud->action('lookup') ->findMethod(['withCustomOptions' => ['foo' => 'bar']]); }, + ['priority' => 11], ); $this->get('/blogs/lookup.json'); - $this->assertSame(['foo' => 'bar'], $this->_controller->Blogs->customOptions); + $this->assertSame(['foo' => 'bar'], $this->controller->Blogs->customOptions); } } diff --git a/tests/TestCase/Action/ViewActionTest.php b/tests/TestCase/Action/ViewActionTest.php index e6f724f69..93a541502 100644 --- a/tests/TestCase/Action/ViewActionTest.php +++ b/tests/TestCase/Action/ViewActionTest.php @@ -42,12 +42,12 @@ public static function allHttpMethodProvider() #[DataProvider('allHttpMethodProvider')] public function testGet($method) { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { - $this->_subscribeToEvents($this->_controller); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $this->{$method}('/blogs/view/1'); @@ -65,13 +65,13 @@ function ($event) { */ public function testGetWithViewVar() { - $this->_eventManager->on( + $this->eventManager->on( 'Controller.initialize', - ['priority' => 11], function ($event) { - $this->_controller->Crud->action('view')->viewVar('item'); - $this->_subscribeToEvents($this->_controller); + $this->controller->Crud->action('view')->viewVar('item'); + $this->subscribeToEvents($this->controller); }, + ['priority' => 11], ); $this->get('/blogs/view/1'); diff --git a/tests/TestCase/Controller/Component/CrudComponentTest.php b/tests/TestCase/Controller/Component/CrudComponentTest.php index e64fe8e32..b8de5d94d 100644 --- a/tests/TestCase/Controller/Component/CrudComponentTest.php +++ b/tests/TestCase/Controller/Component/CrudComponentTest.php @@ -19,10 +19,12 @@ use Crud\Test\App\Listener\TestListener; use Crud\TestSuite\TestCase; use Exception; +use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations; /** * CrudComponentTestCase */ +#[AllowMockObjectsWithoutExpectations] class CrudComponentTest extends TestCase { /** @@ -59,7 +61,7 @@ protected function setUp(): void ->getMock() ->withParam('action', 'index'); - $this->request->expects($this->any())->method('is')->willReturn(true); + $this->request->method('is')->willReturn(true); $this->controller = $this->getMockBuilder(CrudExamplesController::class) ->onlyMethods(['redirect', 'render']) @@ -117,12 +119,12 @@ public function testConfigNormalization() ], ]; $Crud = $this->getMockBuilder(CrudComponent::class) - ->onlyMethods(['_loadListeners', 'trigger']) + ->onlyMethods(['loadListeners', 'trigger']) ->setConstructorArgs([$this->Registry, $config]) ->getMock(); $Crud ->expects($this->once()) - ->method('_loadListeners'); + ->method('loadListeners'); $Crud ->expects($this->once()) ->method('trigger'); @@ -901,7 +903,7 @@ public function testLoadListener() ]); $this->setReflectionClassInstance($this->Crud); - $listener = $this->callProtectedMethod('_loadListener', ['HasSetup'], $this->Crud); + $listener = $this->callProtectedMethod('loadListener', ['HasSetup'], $this->Crud); $this->assertSame(1, $listener->callCount, 'Setup should be called'); } } diff --git a/tests/TestCase/Error/ExceptionRendererTest.php b/tests/TestCase/Error/ExceptionRendererTest.php index b8b203554..9753728eb 100644 --- a/tests/TestCase/Error/ExceptionRendererTest.php +++ b/tests/TestCase/Error/ExceptionRendererTest.php @@ -11,9 +11,11 @@ use Cake\ORM\Entity; use Cake\TestSuite\TestCase; use Crud\Error\Exception\ValidationException; -use Crud\Error\ExceptionRenderer; use Crud\Log\QueryLogger; +use Crud\Test\App\Error\TestExceptionRenderer; +use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations; +#[AllowMockObjectsWithoutExpectations] class ExceptionRendererTest extends TestCase { protected function setUp(): void @@ -31,17 +33,7 @@ public function testNormalExceptionRendering() ->setConstructorArgs([new ServerRequest()]) ->getMock(); - $Renderer = $this->getMockBuilder(ExceptionRenderer::class) - ->onlyMethods(['_getController']) - ->disableOriginalConstructor() - ->getMock(); - $Renderer - ->expects($this->once()) - ->method('_getController') - ->with() - ->willReturn($Controller); - - $Renderer->__construct($Exception); + $Renderer = new TestExceptionRenderer($Exception, null, $Controller); $Renderer->render(); $serialize = $Controller->viewBuilder()->getOption('serialize'); @@ -106,17 +98,7 @@ public function testNormalExceptionRenderingQueryLog() ->setConstructorArgs([new ServerRequest()]) ->getMock(); - $Renderer = $this->getMockBuilder(ExceptionRenderer::class) - ->onlyMethods(['_getController']) - ->disableOriginalConstructor() - ->getMock(); - $Renderer - ->expects($this->once()) - ->method('_getController') - ->with() - ->willReturn($Controller); - - $Renderer->__construct($Exception); + $Renderer = new TestExceptionRenderer($Exception, null, $Controller); $Renderer->render(); $serialize = $Controller->viewBuilder()->getOption('serialize'); @@ -177,17 +159,7 @@ public function testNormalNestedExceptionRendering() ->setConstructorArgs([new ServerRequest()]) ->getMock(); - $Renderer = $this->getMockBuilder(ExceptionRenderer::class) - ->onlyMethods(['_getController']) - ->disableOriginalConstructor() - ->getMock(); - $Renderer - ->expects($this->once()) - ->method('_getController') - ->with() - ->willReturn($Controller); - - $Renderer->__construct($Exception); + $Renderer = new TestExceptionRenderer($Exception, null, $Controller); $Renderer->render(); $serialize = $Controller->viewBuilder()->getOption('serialize'); @@ -238,17 +210,7 @@ public function testMissingViewExceptionDuringRendering() ->setConstructorArgs([new ServerRequest()]) ->getMock(); - $Renderer = $this->getMockBuilder(ExceptionRenderer::class) - ->onlyMethods(['_getController']) - ->disableOriginalConstructor() - ->getMock(); - $Renderer - ->expects($this->once()) - ->method('_getController') - ->with() - ->willReturn($Controller); - - $Renderer->__construct($Exception); + $Renderer = new TestExceptionRenderer($Exception, null, $Controller); $Renderer->render(); $serialize = $Controller->viewBuilder()->getOption('serialize'); @@ -299,17 +261,7 @@ public function testGenericExceptionDuringRendering() ->setConstructorArgs([new ServerRequest()]) ->getMock(); - $Renderer = $this->getMockBuilder(ExceptionRenderer::class) - ->onlyMethods(['_getController']) - ->disableOriginalConstructor() - ->getMock(); - $Renderer - ->expects($this->once()) - ->method('_getController') - ->with() - ->willReturn($Controller); - - $Renderer->__construct($Exception); + $Renderer = new TestExceptionRenderer($Exception, null, $Controller); $Renderer->render(); $serialize = $Controller->viewBuilder()->getOption('serialize'); @@ -364,17 +316,7 @@ public function testValidationErrorSingleKnownError() ->setConstructorArgs([new ServerRequest()]) ->getMock(); - $Renderer = $this->getMockBuilder(ExceptionRenderer::class) - ->onlyMethods(['_getController']) - ->disableOriginalConstructor() - ->getMock(); - $Renderer - ->expects($this->once()) - ->method('_getController') - ->with() - ->willReturn($Controller); - - $Renderer->__construct($Exception); + $Renderer = new TestExceptionRenderer($Exception, null, $Controller); $Renderer->render(); $expected = [ @@ -406,17 +348,7 @@ public function testValidationErrorSingleKnownErrorWithDebug() ->setConstructorArgs([new ServerRequest()]) ->getMock(); - $Renderer = $this->getMockBuilder(ExceptionRenderer::class) - ->onlyMethods(['_getController']) - ->disableOriginalConstructor() - ->getMock(); - $Renderer - ->expects($this->once()) - ->method('_getController') - ->with() - ->willReturn($Controller); - - $Renderer->__construct($Exception); + $Renderer = new TestExceptionRenderer($Exception, null, $Controller); $Renderer->render(); $result = $Controller->viewBuilder()->getVar('data'); @@ -457,17 +389,7 @@ public function testValidationErrorMultipleMessages() ->setConstructorArgs([new ServerRequest()]) ->getMock(); - $Renderer = $this->getMockBuilder(ExceptionRenderer::class) - ->onlyMethods(['_getController']) - ->disableOriginalConstructor() - ->getMock(); - $Renderer - ->expects($this->once()) - ->method('_getController') - ->with() - ->willReturn($Controller); - - $Renderer->__construct($Exception); + $Renderer = new TestExceptionRenderer($Exception, null, $Controller); $Renderer->render(); $expected = [ diff --git a/tests/TestCase/Listener/ApiListenerTest.php b/tests/TestCase/Listener/ApiListenerTest.php index d7c215546..d2e7e5d71 100644 --- a/tests/TestCase/Listener/ApiListenerTest.php +++ b/tests/TestCase/Listener/ApiListenerTest.php @@ -19,6 +19,7 @@ use Crud\Listener\ApiListener; use Crud\Test\App\Controller\BlogsController; use Crud\TestSuite\TestCase; +use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations; use PHPUnit\Framework\Attributes\DataProvider; use StdClass; @@ -26,6 +27,7 @@ * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt */ +#[AllowMockObjectsWithoutExpectations] class ApiListenerTest extends TestCase { /** @@ -37,7 +39,7 @@ public function testImplementedEvents() { $listener = $this ->getMockBuilder(ApiListener::class) - ->onlyMethods(['setupDetectors', '_checkRequestType']) + ->onlyMethods(['setupDetectors', 'checkRequestType']) ->disableOriginalConstructor() ->getMock(); $listener @@ -45,7 +47,7 @@ public function testImplementedEvents() ->method('setupDetectors'); $listener ->expects($this->once()) - ->method('_checkRequestType') + ->method('checkRequestType') ->with('api') ->willReturn(true); @@ -69,7 +71,7 @@ public function testImplementedEventsWithoutApi() { $listener = $this ->getMockBuilder(ApiListener::class) - ->onlyMethods(['setupDetectors', '_checkRequestType']) + ->onlyMethods(['setupDetectors', 'checkRequestType']) ->disableOriginalConstructor() ->getMock(); $listener @@ -77,7 +79,7 @@ public function testImplementedEventsWithoutApi() ->method('setupDetectors'); $listener ->expects($this->once()) - ->method('_checkRequestType') + ->method('checkRequestType') ->with('api') ->willReturn(false); @@ -95,12 +97,12 @@ public function testBeforeHandle() { $listener = $this ->getMockBuilder(ApiListener::class) - ->onlyMethods(['_checkRequestMethods']) + ->onlyMethods(['checkRequestMethods']) ->disableOriginalConstructor() ->getMock(); $listener ->expects($this->once()) - ->method('_checkRequestMethods'); + ->method('checkRequestMethods'); $listener->beforeHandle(new Event('Crud.beforeHandle')); } @@ -133,11 +135,11 @@ public function testResponse() $listener = $this ->getMockBuilder(ApiListener::class) ->disableOriginalConstructor() - ->onlyMethods(['_action', 'render']) + ->onlyMethods(['action', 'render']) ->getMock(); $listener ->expects($this->once()) - ->method('_action') + ->method('action') ->with() ->willReturn($action); $action @@ -185,11 +187,11 @@ public function testResponseDeleteError() $listener = $this ->getMockBuilder(ApiListener::class) ->disableOriginalConstructor() - ->onlyMethods(['_action', 'render']) + ->onlyMethods(['action', 'render']) ->getMock(); $listener ->expects($this->once()) - ->method('_action') + ->method('action') ->with() ->willReturn($action); $listener @@ -234,11 +236,11 @@ public function testResponseWithStatusCodeNotSpecified() $listener = $this ->getMockBuilder(ApiListener::class) ->disableOriginalConstructor() - ->onlyMethods(['_action', 'render']) + ->onlyMethods(['action', 'render']) ->getMock(); $listener ->expects($this->once()) - ->method('_action') + ->method('action') ->with() ->willReturn($action); $action @@ -280,11 +282,11 @@ public function testResponseWithExceptionConfig() $listener = $this ->getMockBuilder(ApiListener::class) ->disableOriginalConstructor() - ->onlyMethods(['_action', 'render', '_exceptionResponse']) + ->onlyMethods(['action', 'render', 'exceptionResponse']) ->getMock(); $listener ->expects($this->once()) - ->method('_action') + ->method('action') ->with() ->willReturn($action); $action @@ -294,7 +296,7 @@ public function testResponseWithExceptionConfig() ->willReturn(['exception' => ['SomethingExceptional']]); $listener ->expects($this->once()) - ->method('_exceptionResponse') + ->method('exceptionResponse') ->with($event, ['SomethingExceptional']); $listener ->expects($this->never()) @@ -404,7 +406,7 @@ public static function dataExceptionResponse() } /** - * Test _exceptionResponse + * Test exceptionResponse * * @param array $apiConfig * @param string $exceptionClass @@ -437,7 +439,6 @@ public function testExceptionResponse( ]); $event->getSubject()->entity - ->expects($this->any()) ->method('getErrors') ->willReturn($validationErrors); } @@ -445,7 +446,7 @@ public function testExceptionResponse( $this->expectException($exceptionClass, $exceptionMessage, $exceptionCode); $this->setReflectionClassInstance($listener); - $this->callProtectedMethod('_exceptionResponse', [$event, $apiConfig], $listener); + $this->callProtectedMethod('exceptionResponse', [$event, $apiConfig], $listener); } /** @@ -457,7 +458,7 @@ public function testEnsureSerializeWithViewVar() { $listener = $this ->getMockBuilder(ApiListener::class) - ->onlyMethods(['_action', '_controller']) + ->onlyMethods(['action', 'controller']) ->disableOriginalConstructor() ->getMock(); @@ -475,11 +476,11 @@ public function testEnsureSerializeWithViewVar() $listener ->expects($this->once()) - ->method('_controller') + ->method('controller') ->willReturn($controller); $listener ->expects($this->once()) - ->method('_action') + ->method('action') ->willReturn($action); $action ->expects($this->once()) @@ -487,7 +488,7 @@ public function testEnsureSerializeWithViewVar() ->willReturn('items'); $this->setReflectionClassInstance($listener); - $this->callProtectedMethod('_ensureSerialize', [], $listener); + $this->callProtectedMethod('ensureSerialize', [], $listener); $this->assertEquals( ['success', 'data' => 'items'], @@ -520,7 +521,7 @@ public function testEnsureSerializeWithSerializeTrait($action) { $listener = $this ->getMockBuilder(ApiListener::class) - ->onlyMethods(['_action', '_controller']) + ->onlyMethods(['action', 'controller']) ->disableOriginalConstructor() ->getMock(); @@ -538,11 +539,11 @@ public function testEnsureSerializeWithSerializeTrait($action) $listener ->expects($this->once()) - ->method('_controller') + ->method('controller') ->willReturn($controller); $listener ->expects($this->once()) - ->method('_action') + ->method('action') ->willReturn($action); $action ->expects($this->once()) @@ -562,7 +563,7 @@ public function testEnsureSerializeWithSerializeTrait($action) $this->callProtectedMethod('serialize', [['something']], $action); $this->setReflectionClassInstance($listener); - $this->callProtectedMethod('_ensureSerialize', [], $listener); + $this->callProtectedMethod('ensureSerialize', [], $listener); $this->assertEquals( ['success', 'something', 'data' => null], @@ -579,7 +580,7 @@ public function testEnsureSerializeAlreadySet() { $listener = $this ->getMockBuilder(ApiListener::class) - ->onlyMethods(['_action', '_controller']) + ->onlyMethods(['action', 'controller']) ->disableOriginalConstructor() ->getMock(); @@ -599,11 +600,11 @@ public function testEnsureSerializeAlreadySet() $listener ->expects($this->once()) - ->method('_controller') + ->method('controller') ->willReturn($controller); $listener ->expects($this->never()) - ->method('_action'); + ->method('action'); $action ->expects($this->never()) ->method('viewVar'); @@ -612,7 +613,7 @@ public function testEnsureSerializeAlreadySet() ->method('set'); $this->setReflectionClassInstance($listener); - $this->callProtectedMethod('_ensureSerialize', [], $listener); + $this->callProtectedMethod('ensureSerialize', [], $listener); $this->assertEquals( 'hello world', @@ -629,7 +630,7 @@ public function testEnsureSerializeWithViewVarChanged() { $listener = $this ->getMockBuilder(ApiListener::class) - ->onlyMethods(['_action', '_controller']) + ->onlyMethods(['action', 'controller']) ->disableOriginalConstructor() ->getMock(); @@ -647,11 +648,11 @@ public function testEnsureSerializeWithViewVarChanged() $listener ->expects($this->once()) - ->method('_controller') + ->method('controller') ->willReturn($controller); $listener ->expects($this->once()) - ->method('_action') + ->method('action') ->willReturn($action); $action ->expects($this->once()) @@ -659,7 +660,7 @@ public function testEnsureSerializeWithViewVarChanged() ->willReturn('helloWorld'); $this->setReflectionClassInstance($listener); - $this->callProtectedMethod('_ensureSerialize', [], $listener); + $this->callProtectedMethod('ensureSerialize', [], $listener); $this->assertEquals( ['success', 'data' => 'helloWorld'], @@ -676,7 +677,7 @@ public function testEnsureSerializeWithoutViewVar() { $listener = $this ->getMockBuilder(ApiListener::class) - ->onlyMethods(['_action', '_controller']) + ->onlyMethods(['action', 'controller']) ->disableOriginalConstructor() ->getMock(); @@ -688,31 +689,30 @@ public function testEnsureSerializeWithoutViewVar() $action = $this ->getMockBuilder(AddAction::class) - ->onlyMethods(['scope', '_controller']) + ->onlyMethods(['scope', 'controller']) ->disableOriginalConstructor() ->getMock(); $listener ->expects($this->once()) - ->method('_controller') + ->method('controller') ->willReturn($controller); $listener ->expects($this->once()) - ->method('_action') + ->method('action') ->willReturn($action); $controller - ->expects($this->any()) ->method('getName') ->willReturn(''); - $action->expects($this->any()) + $action ->method('scope') ->willReturn('table'); - $action->expects($this->any()) - ->method('_controller') + $action + ->method('controller') ->willReturn($controller); $this->setReflectionClassInstance($listener); - $this->callProtectedMethod('_ensureSerialize', [], $listener); + $this->callProtectedMethod('ensureSerialize', [], $listener); $this->assertEquals( ['success', 'data' => ''], @@ -729,7 +729,7 @@ public function testEnsureSuccess() { $listener = $this ->getMockBuilder(ApiListener::class) - ->onlyMethods(['_controller']) + ->onlyMethods(['controller']) ->disableOriginalConstructor() ->getMock(); @@ -743,7 +743,7 @@ public function testEnsureSuccess() $listener ->expects($this->once()) - ->method('_controller') + ->method('controller') ->willReturn($controller); $controller ->expects($this->once()) @@ -751,7 +751,7 @@ public function testEnsureSuccess() ->with('success', true); $this->setReflectionClassInstance($listener); - $this->callProtectedMethod('_ensureSuccess', [$subject], $listener); + $this->callProtectedMethod('ensureSuccess', [$subject], $listener); } /** @@ -763,7 +763,7 @@ public function testEnsureData() { $listener = $this ->getMockBuilder(ApiListener::class) - ->onlyMethods(['_controller', '_action']) + ->onlyMethods(['controller', 'action']) ->disableOriginalConstructor() ->getMock(); @@ -785,11 +785,11 @@ public function testEnsureData() $listener ->expects($this->once()) - ->method('_controller') + ->method('controller') ->willReturn($controller); $listener ->expects($this->once()) - ->method('_action') + ->method('action') ->willReturn($action); $action ->expects($this->once()) @@ -802,7 +802,7 @@ public function testEnsureData() ->with('data', []); $this->setReflectionClassInstance($listener); - $this->callProtectedMethod('_ensureData', [$subject], $listener); + $this->callProtectedMethod('ensureData', [$subject], $listener); } /** @@ -814,7 +814,7 @@ public function testEnsureDataSubject() { $listener = $this ->getMockBuilder(ApiListener::class) - ->onlyMethods(['_controller', '_action']) + ->onlyMethods(['controller', 'action']) ->disableOriginalConstructor() ->getMock(); @@ -841,11 +841,11 @@ public function testEnsureDataSubject() $listener ->expects($this->once()) - ->method('_controller') + ->method('controller') ->willReturn($controller); $listener ->expects($this->once()) - ->method('_action') + ->method('action') ->willReturn($action); $action ->expects($this->once()) @@ -858,7 +858,7 @@ public function testEnsureDataSubject() ->with('data', ['modelClass' => 'MyModel', 'MyModel' => ['id' => 1]]); $this->setReflectionClassInstance($listener); - $this->callProtectedMethod('_ensureData', [$subject], $listener); + $this->callProtectedMethod('ensureData', [$subject], $listener); } /** @@ -870,7 +870,7 @@ public function testEnsureDataRaw() { $listener = $this ->getMockBuilder(ApiListener::class) - ->onlyMethods(['_controller', '_action']) + ->onlyMethods(['controller', 'action']) ->disableOriginalConstructor() ->getMock(); @@ -892,11 +892,11 @@ public function testEnsureDataRaw() $listener ->expects($this->once()) - ->method('_controller') + ->method('controller') ->willReturn($controller); $listener ->expects($this->once()) - ->method('_action') + ->method('action') ->willReturn($action); $action ->expects($this->once()) @@ -909,7 +909,7 @@ public function testEnsureDataRaw() ->with('data', ['MyModel' => ['id' => 1]]); $this->setReflectionClassInstance($listener); - $this->callProtectedMethod('_ensureData', [$subject], $listener); + $this->callProtectedMethod('ensureData', [$subject], $listener); } /** @@ -921,7 +921,7 @@ public function testEnsureDataError() { $listener = $this ->getMockBuilder(ApiListener::class) - ->onlyMethods(['_controller', '_action']) + ->onlyMethods(['controller', 'action']) ->disableOriginalConstructor() ->getMock(); @@ -943,11 +943,11 @@ public function testEnsureDataError() $listener ->expects($this->once()) - ->method('_controller') + ->method('controller') ->willReturn($controller); $listener ->expects($this->once()) - ->method('_action') + ->method('action') ->willReturn($action); $action ->expects($this->once()) @@ -960,7 +960,7 @@ public function testEnsureDataError() ->with('data', []); $this->setReflectionClassInstance($listener); - $this->callProtectedMethod('_ensureData', [$subject], $listener); + $this->callProtectedMethod('ensureData', [$subject], $listener); } /** @@ -972,7 +972,7 @@ public function testEnsureSuccessAlreadySet() { $listener = $this ->getMockBuilder(ApiListener::class) - ->onlyMethods(['_controller']) + ->onlyMethods(['controller']) ->disableOriginalConstructor() ->getMock(); @@ -988,14 +988,14 @@ public function testEnsureSuccessAlreadySet() $listener ->expects($this->once()) - ->method('_controller') + ->method('controller') ->willReturn($controller); $controller ->expects($this->never()) ->method('set'); $this->setReflectionClassInstance($listener); - $this->callProtectedMethod('_ensureSuccess', [$subject], $listener); + $this->callProtectedMethod('ensureSuccess', [$subject], $listener); } /** @@ -1102,7 +1102,7 @@ public function testExpandPath($subject, $path, $expected) ->getMock(); $this->setReflectionClassInstance($listener); - $result = $this->callProtectedMethod('_expandPath', [$subject, $path], $listener); + $result = $this->callProtectedMethod('expandPath', [$subject, $path], $listener); $this->assertSame($expected, $result); } @@ -1126,7 +1126,7 @@ public function testSetupDetectorsIntegration() $listener = $this ->getMockBuilder(ApiListener::class) - ->onlyMethods(['_request', 'getConfig']) + ->onlyMethods(['request', 'getConfig']) ->disableOriginalConstructor() ->getMock(); @@ -1135,7 +1135,7 @@ public function testSetupDetectorsIntegration() $listener ->expects($this->once()) - ->method('_request') + ->method('request') ->willReturn($request); $listener ->expects($this->once()) @@ -1212,7 +1212,7 @@ public function testCheckRequestMethods($apiConfig, $exception, $requestMethods) { $listener = $this ->getMockBuilder(ApiListener::class) - ->onlyMethods(['_action', '_request']) + ->onlyMethods(['action', 'request']) ->disableOriginalConstructor() ->getMock(); @@ -1230,7 +1230,7 @@ public function testCheckRequestMethods($apiConfig, $exception, $requestMethods) $listener ->expects($this->once()) - ->method('_action') + ->method('action') ->willReturn($action); $action ->expects($this->once()) @@ -1241,7 +1241,7 @@ public function testCheckRequestMethods($apiConfig, $exception, $requestMethods) if (!empty($apiConfig['methods'])) { $listener ->expects($this->once()) - ->method('_request') + ->method('request') ->willReturn($request); $withs = $returns = []; @@ -1257,7 +1257,7 @@ public function testCheckRequestMethods($apiConfig, $exception, $requestMethods) } else { $listener ->expects($this->never()) - ->method('_request'); + ->method('request'); } if (is_string($exception)) { @@ -1265,7 +1265,7 @@ public function testCheckRequestMethods($apiConfig, $exception, $requestMethods) } $this->setReflectionClassInstance($listener); - $this->callProtectedMethod('_checkRequestMethods', [], $listener); + $this->callProtectedMethod('checkRequestMethods', [], $listener); } /** @@ -1332,12 +1332,12 @@ public function testInjectViewClasses() $apiListener = $this->getMockBuilder(ApiListener::class) ->disableOriginalConstructor() - ->onlyMethods(['_controller']) + ->onlyMethods(['controller']) ->getMock(); $apiListener ->expects($this->once()) - ->method('_controller') + ->method('controller') ->willReturn($controller); $apiListener->injectViewClasses(); diff --git a/tests/TestCase/Listener/ApiPaginationListenerTest.php b/tests/TestCase/Listener/ApiPaginationListenerTest.php index eae25de84..f7ab08bf9 100644 --- a/tests/TestCase/Listener/ApiPaginationListenerTest.php +++ b/tests/TestCase/Listener/ApiPaginationListenerTest.php @@ -11,11 +11,13 @@ use Crud\Action\BaseAction; use Crud\Listener\ApiPaginationListener; use Crud\TestSuite\TestCase; +use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations; /** * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt */ +#[AllowMockObjectsWithoutExpectations] class ApiPaginationListenerTest extends TestCase { /** @@ -28,11 +30,11 @@ public function testImplementedEvents() $Instance = $this ->getMockBuilder(ApiPaginationListener::class) ->disableOriginalConstructor() - ->onlyMethods(['_checkRequestType']) + ->onlyMethods(['checkRequestType']) ->getMock(); $Instance ->expects($this->once()) - ->method('_checkRequestType') + ->method('checkRequestType') ->willReturn(true); $result = $Instance->implementedEvents(); @@ -65,15 +67,15 @@ public function testBeforeRenderNoPaginationData() $Instance = $this ->getMockBuilder(ApiPaginationListener::class) ->disableOriginalConstructor() - ->onlyMethods(['_request', '_action', '_controller']) + ->onlyMethods(['request', 'action', 'controller']) ->getMock(); $Instance ->expects($this->once()) - ->method('_action') + ->method('action') ->willReturn($Action); $Instance ->expects($this->once()) - ->method('_controller') + ->method('controller') ->willReturn($Controller); $Instance->beforeRender(new Event('something')); @@ -101,15 +103,15 @@ public function testBeforeRenderViewVarNotPaginatedInterface() $Instance = $this ->getMockBuilder(ApiPaginationListener::class) ->disableOriginalConstructor() - ->onlyMethods(['_request', '_action', '_controller']) + ->onlyMethods(['request', 'action', 'controller']) ->getMock(); $Instance ->expects($this->once()) - ->method('_controller') + ->method('controller') ->willReturn($Controller); $Instance ->expects($this->once()) - ->method('_action') + ->method('action') ->willReturn($Action); $Instance->beforeRender(new Event('something')); @@ -155,15 +157,13 @@ public function testBeforeRenderWithPaginationData() $Instance = $this ->getMockBuilder(ApiPaginationListener::class) ->disableOriginalConstructor() - ->onlyMethods(['_request', '_controller', '_action']) + ->onlyMethods(['request', 'controller', 'action']) ->getMock(); $Instance - ->expects($this->any()) - ->method('_controller') + ->method('controller') ->willReturn($Controller); $Instance - ->expects($this->any()) - ->method('_action') + ->method('action') ->willReturn($Action); $Instance->beforeRender(new Event('something')); diff --git a/tests/TestCase/Listener/ApiQueryLogListenerTest.php b/tests/TestCase/Listener/ApiQueryLogListenerTest.php index 6ff3955c2..8e3a3ab11 100644 --- a/tests/TestCase/Listener/ApiQueryLogListenerTest.php +++ b/tests/TestCase/Listener/ApiQueryLogListenerTest.php @@ -17,19 +17,19 @@ */ class ApiQueryLogListenerTest extends TestCase { - protected $_debug; + protected $debug; protected function setUp(): void { parent::setUp(); - $this->_debug = Configure::read('debug'); + $this->debug = Configure::read('debug'); } public function tearDown(): void { parent::tearDown(); - Configure::write('debug', $this->_debug); + Configure::write('debug', $this->debug); } /** @@ -42,11 +42,11 @@ public function testImplementedEvents() $Instance = $this ->getMockBuilder(ApiQueryLogListener::class) ->disableOriginalConstructor() - ->onlyMethods(['_checkRequestType']) + ->onlyMethods(['checkRequestType']) ->getMock(); $Instance ->expects($this->once()) - ->method('_checkRequestType') + ->method('checkRequestType') ->with('api') ->willReturn(true); @@ -69,11 +69,11 @@ public function testImplementedEventsNotApiRequest() $Instance = $this ->getMockBuilder(ApiQueryLogListener::class) ->disableOriginalConstructor() - ->onlyMethods(['_checkRequestType']) + ->onlyMethods(['checkRequestType']) ->getMock(); $Instance ->expects($this->once()) - ->method('_checkRequestType') + ->method('checkRequestType') ->with('api') ->willReturn(false); @@ -139,15 +139,15 @@ public function testBeforeRenderDebugTrue() $Instance = $this ->getMockBuilder(ApiQueryLogListener::class) ->disableOriginalConstructor() - ->onlyMethods(['getQueryLogs', '_action', '_controller']) + ->onlyMethods(['getQueryLogs', 'action', 'controller']) ->getMock(); $Instance ->expects($this->once()) - ->method('_action') + ->method('action') ->willReturn($Action); $Instance ->expects($this->once()) - ->method('_controller') + ->method('controller') ->willReturn($Controller); $Instance ->expects($this->once()) diff --git a/tests/TestCase/Listener/RedirectListenerTest.php b/tests/TestCase/Listener/RedirectListenerTest.php index 9f1325b3b..df8aadda8 100644 --- a/tests/TestCase/Listener/RedirectListenerTest.php +++ b/tests/TestCase/Listener/RedirectListenerTest.php @@ -10,12 +10,14 @@ use Crud\Event\Subject; use Crud\Listener\RedirectListener; use Crud\TestSuite\TestCase; +use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations; use PHPUnit\Framework\Attributes\DataProvider; /** * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt */ +#[AllowMockObjectsWithoutExpectations] class RedirectListenerTest extends TestCase { /** @@ -150,7 +152,7 @@ public function testReaderRequestKey() { $listener = $this ->getMockBuilder(RedirectListener::class) - ->onlyMethods(['_request']) + ->onlyMethods(['request']) ->disableoriginalConstructor() ->getMock(); @@ -159,7 +161,7 @@ public function testReaderRequestKey() $subject = new Subject(); $request = (new ServerRequest())->withParam('action', 'index'); - $listener->expects($this->any())->method('_request')->willReturn($request); + $listener->method('request')->willReturn($request); $reader = $listener->reader('request.key'); $result = $reader($subject, 'action'); @@ -178,7 +180,7 @@ public function testReaderRequestData() { $listener = $this ->getMockBuilder(RedirectListener::class) - ->onlyMethods(['_request']) + ->onlyMethods(['request']) ->disableoriginalConstructor() ->getMock(); @@ -187,7 +189,7 @@ public function testReaderRequestData() $subject = new Subject(); $request = (new ServerRequest())->withData('hello', 'world'); - $listener->expects($this->any())->method('_request')->willReturn($request); + $listener->method('request')->willReturn($request); $reader = $listener->reader('request.data'); $result = $reader($subject, 'hello'); @@ -206,7 +208,7 @@ public function testReaderRequestQuery() { $listener = $this ->getMockBuilder(RedirectListener::class) - ->onlyMethods(['_request']) + ->onlyMethods(['request']) ->disableoriginalConstructor() ->getMock(); @@ -215,7 +217,7 @@ public function testReaderRequestQuery() $subject = new Subject(); $request = (new ServerRequest())->withQueryParams(['hello' => 'world']); - $listener->expects($this->any())->method('_request')->willReturn($request); + $listener->method('request')->willReturn($request); $reader = $listener->reader('request.query'); $result = $reader($subject, 'hello'); @@ -299,16 +301,16 @@ public function testRedirectWithNoConfig() $listener = $this ->getMockBuilder(RedirectListener::class) - ->onlyMethods(['_action', '_getKey']) + ->onlyMethods(['action', 'getKey']) ->disableoriginalConstructor() ->getMock(); $listener ->expects($this->once()) - ->method('_action') + ->method('action') ->willReturn($action); $listener ->expects($this->never()) - ->method('_getKey'); + ->method('getKey'); $subject = new Subject(); @@ -335,21 +337,21 @@ public function testRedirectWithConfigButNoValidKey() $listener = $this ->getMockBuilder(RedirectListener::class) - ->onlyMethods(['_action', '_getKey', '_getUrl']) + ->onlyMethods(['action', 'getKey', 'getUrl']) ->disableoriginalConstructor() ->getMock(); $listener ->expects($this->once()) - ->method('_action') + ->method('action') ->willReturn($action); $listener ->expects($this->once()) - ->method('_getKey') + ->method('getKey') ->with($subject, 'request.key', 'hello') ->willReturn(false); $listener ->expects($this->never()) - ->method('_getUrl'); + ->method('getUrl'); $listener->beforeRedirect(new Event('Crud.beforeRedirect', $subject)); } @@ -378,21 +380,21 @@ public function testRedirectWithConfigAndValidKey() $listener = $this ->getMockBuilder(RedirectListener::class) - ->onlyMethods(['_action', '_getKey', '_getUrl']) + ->onlyMethods(['action', 'getKey', 'getUrl']) ->disableoriginalConstructor() ->getMock(); $listener ->expects($this->once()) - ->method('_action') + ->method('action') ->willReturn($action); $listener ->expects($this->once()) - ->method('_getKey') + ->method('getKey') ->with($subject, 'request.key', 'hello') ->willReturn(true); $listener ->expects($this->once()) - ->method('_getUrl') + ->method('getUrl') ->with($subject, ['action' => 'index']) ->willReturn(['action' => 'index']); @@ -453,7 +455,7 @@ public static function dataProviderGetUrl() } /** - * Test _getUrl + * Test getUrl * * @return void */ @@ -462,7 +464,7 @@ public function testGetUrl(Subject $subject, $url, $expected) { $listener = $this ->getMockBuilder(RedirectListener::class) - ->onlyMethods(['_request']) + ->onlyMethods(['request']) ->disableoriginalConstructor() ->getMock(); @@ -473,15 +475,13 @@ public function testGetUrl(Subject $subject, $url, $expected) } $listener - ->expects($this->any()) - ->method('_request') - ->with() + ->method('request') ->willReturn($request); $listener->setup(); $this->setReflectionClassInstance($listener); - $result = $this->callProtectedMethod('_getUrl', [$subject, $url], $listener); + $result = $this->callProtectedMethod('getUrl', [$subject, $url], $listener); $this->assertEquals($expected, $result); } } diff --git a/tests/TestCase/Listener/RelatedModelsListenerTest.php b/tests/TestCase/Listener/RelatedModelsListenerTest.php index 217d47d85..5c483dc17 100644 --- a/tests/TestCase/Listener/RelatedModelsListenerTest.php +++ b/tests/TestCase/Listener/RelatedModelsListenerTest.php @@ -13,11 +13,13 @@ use Crud\Event\Subject; use Crud\Listener\RelatedModelsListener; use Crud\TestSuite\TestCase; +use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations; /** * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt */ +#[AllowMockObjectsWithoutExpectations] class RelatedModelsListenerTest extends TestCase { protected array $fixtures = ['core.NumberTrees']; @@ -138,7 +140,7 @@ public function testGetAssociatedByTypeReturnValue() $listener = $this ->getMockBuilder(RelatedModelsListener::class) ->disableOriginalConstructor() - ->onlyMethods(['relatedModels', '_model']) + ->onlyMethods(['relatedModels', 'model']) ->getMock(); $table = $this ->getMockBuilder(Table::class) @@ -158,7 +160,7 @@ public function testGetAssociatedByTypeReturnValue() $listener ->expects($this->once()) - ->method('_model') + ->method('model') ->withAnyParameters() ->willReturn($table); $table @@ -201,7 +203,7 @@ public function testGetAssociatedByNameReturnValue() $listener = $this ->getMockBuilder(RelatedModelsListener::class) ->disableOriginalConstructor() - ->onlyMethods(['relatedModels', '_model']) + ->onlyMethods(['relatedModels', 'model']) ->getMock(); $table = $this ->getMockBuilder(Table::class) @@ -221,7 +223,7 @@ public function testGetAssociatedByNameReturnValue() $listener ->expects($this->once()) - ->method('_model') + ->method('model') ->withAnyParameters() ->willReturn($table); $table @@ -261,7 +263,6 @@ public function testListFinder() ->getMock(); $association - ->expects($this->any()) ->method('getTarget') ->willReturn($model); @@ -294,7 +295,6 @@ public function testbeforePaginate() ->getMock(); $table - ->expects($this->any()) ->method('getSchema') ->willReturn(new TableSchema('Users')); diff --git a/tests/TestCase/Listener/SearchListenerTest.php b/tests/TestCase/Listener/SearchListenerTest.php index ad4add7fe..53fb24ab9 100644 --- a/tests/TestCase/Listener/SearchListenerTest.php +++ b/tests/TestCase/Listener/SearchListenerTest.php @@ -15,12 +15,14 @@ use Crud\Listener\SearchListener; use Crud\TestSuite\TestCase; use Muffin\Webservice\Model\EndpointRegistry; +use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations; use RuntimeException; /** * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt */ +#[AllowMockObjectsWithoutExpectations] class SearchListenerTest extends TestCase { protected function setUp(): void @@ -83,7 +85,7 @@ public function testInjectSearchException() ->setMockClassName('SearchesTable') ->onlyMethods(['behaviors']) ->getMock(); - $tableMock->expects($this->any()) + $tableMock ->method('behaviors') ->willReturn($behaviorRegistryMock); @@ -141,7 +143,7 @@ public function testInjectSearch() ->setMockClassName('SearchTables') ->onlyMethods(['behaviors']) ->getMock(); - $tableMock->expects($this->any()) + $tableMock ->method('behaviors') ->willReturn($behaviorRegistryMock); diff --git a/tests/test_app/src/Action/TestAction.php b/tests/test_app/src/Action/TestAction.php index 2d250bdd0..95a65c44e 100644 --- a/tests/test_app/src/Action/TestAction.php +++ b/tests/test_app/src/Action/TestAction.php @@ -7,7 +7,7 @@ class TestAction extends BaseAction { - protected function _handle() + protected function handleRequest() { } } diff --git a/tests/test_app/src/Action/TestGetAction.php b/tests/test_app/src/Action/TestGetAction.php index 622404d59..97f4f911f 100644 --- a/tests/test_app/src/Action/TestGetAction.php +++ b/tests/test_app/src/Action/TestGetAction.php @@ -7,7 +7,7 @@ class TestGetAction extends BaseAction { - protected function _get() + protected function handleGet() { } } diff --git a/tests/test_app/src/Controller/Component/TestCrudComponent.php b/tests/test_app/src/Controller/Component/TestCrudComponent.php index 99d29f785..98074acc7 100644 --- a/tests/test_app/src/Controller/Component/TestCrudComponent.php +++ b/tests/test_app/src/Controller/Component/TestCrudComponent.php @@ -13,11 +13,11 @@ class TestCrudComponent extends CrudComponent { /** - * test visibility wrapper - access protected _modelName property + * test visibility wrapper - access protected modelName property */ public function getModelName() { - return $this->_modelName; + return $this->modelName; } /** @@ -25,6 +25,6 @@ public function getModelName() */ public function setAction($name) { - $this->_action = $name; + $this->action = $name; } } diff --git a/tests/test_app/src/Error/TestExceptionRenderer.php b/tests/test_app/src/Error/TestExceptionRenderer.php new file mode 100644 index 000000000..fed76709c --- /dev/null +++ b/tests/test_app/src/Error/TestExceptionRenderer.php @@ -0,0 +1,45 @@ +testController = $controller; + + parent::__construct($error, $request); + } + + /** + * @inheritDoc + */ + protected function getController(): Controller + { + return $this->testController; + } +} diff --git a/tests/test_app/src/Event/TestCrudEventManager.php b/tests/test_app/src/Event/TestCrudEventManager.php index d2d313966..1c2dec7e0 100644 --- a/tests/test_app/src/Event/TestCrudEventManager.php +++ b/tests/test_app/src/Event/TestCrudEventManager.php @@ -15,11 +15,11 @@ */ class TestCrudEventManager extends EventManager { - protected $_log = []; + protected $log = []; public function dispatch($event): EventInterface { - $this->_log[] = [ + $this->log[] = [ 'name' => $event->getName(), 'subject' => $event->getSubject(), ]; @@ -31,7 +31,7 @@ public function getLog($params = []) { $params += ['clear' => true, 'format' => 'names']; - $log = $this->_log; + $log = $this->log; if ($params['format'] === 'names') { $return = []; @@ -42,7 +42,7 @@ public function getLog($params = []) } if ($params['clear']) { - $this->_log = []; + $this->log = []; } return $log; diff --git a/tests/test_app/src/Model/Table/CrudExamplesTable.php b/tests/test_app/src/Model/Table/CrudExamplesTable.php index 053934c43..dc0d4dcff 100644 --- a/tests/test_app/src/Model/Table/CrudExamplesTable.php +++ b/tests/test_app/src/Model/Table/CrudExamplesTable.php @@ -14,7 +14,7 @@ */ class CrudExamplesTable extends Table { - protected ?string $_alias = 'CrudExamples'; + protected ?string $alias = 'CrudExamples'; /** * @param array $config Config @@ -30,7 +30,7 @@ public function initialize(array $config): void * @param array $options Options * @return void */ - protected function _findPublished(SelectQuery $query, array $options): void + protected function findPublished(SelectQuery $query, array $options): void { $query->where(['published' => 'Y']); } @@ -40,7 +40,7 @@ protected function _findPublished(SelectQuery $query, array $options): void * @param array $options Options * @return void */ - protected function _findUnpublished(SelectQuery $query, array $options): void + protected function findUnpublished(SelectQuery $query, array $options): void { $query->where(['published' => 'N']); }