From 9adf547f5843bc3e6532de14909cce0f2e11f4bf Mon Sep 17 00:00:00 2001 From: Kevin Pfeifer Date: Sat, 26 Aug 2023 09:55:04 +0200 Subject: [PATCH 01/68] use hasValue instead of has --- en/appendices/4-5-migration-guide.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/en/appendices/4-5-migration-guide.rst b/en/appendices/4-5-migration-guide.rst index 1a655916ba..e663c04578 100644 --- a/en/appendices/4-5-migration-guide.rst +++ b/en/appendices/4-5-migration-guide.rst @@ -80,6 +80,9 @@ Log ORM --- +- In CakePHP 5 ``EntityTrait::has()`` will return true when an attribute exists + and is set to null. To keep the old behavior it is recommended to + change ``EntityTrait::has()`` to ``EntityTrait::hasValue()``. - ``Table::_initializeSchema()`` is deprecated. Override ``getSchema()`` instead, or re-map columns in ``initialize()``. - ``QueryInterface::repository()`` is deprecated. Use ``setRepository()`` From f8ca6db69b7b298d8b733d02af881095d67759d2 Mon Sep 17 00:00:00 2001 From: Kevin Pfeifer Date: Wed, 6 Sep 2023 20:58:30 +0200 Subject: [PATCH 02/68] clarify EntityTrait::has() --- en/appendices/4-5-migration-guide.rst | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/en/appendices/4-5-migration-guide.rst b/en/appendices/4-5-migration-guide.rst index e663c04578..b1f9345a2e 100644 --- a/en/appendices/4-5-migration-guide.rst +++ b/en/appendices/4-5-migration-guide.rst @@ -81,8 +81,9 @@ ORM --- - In CakePHP 5 ``EntityTrait::has()`` will return true when an attribute exists - and is set to null. To keep the old behavior it is recommended to - change ``EntityTrait::has()`` to ``EntityTrait::hasValue()``. + and is set to null. Depending on your application this can lead to unexpected + behavior with your already present code. Use ``EntityTrait::hasValue()`` to + check if a field contains a 'non-empty' value. - ``Table::_initializeSchema()`` is deprecated. Override ``getSchema()`` instead, or re-map columns in ``initialize()``. - ``QueryInterface::repository()`` is deprecated. Use ``setRepository()`` From 6613fe158cf8c4832ebcd03dfb788154904df8b7 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Wed, 6 Sep 2023 22:19:20 -0400 Subject: [PATCH 03/68] Update en/appendices/4-5-migration-guide.rst --- en/appendices/4-5-migration-guide.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/appendices/4-5-migration-guide.rst b/en/appendices/4-5-migration-guide.rst index b1f9345a2e..bcbc1486af 100644 --- a/en/appendices/4-5-migration-guide.rst +++ b/en/appendices/4-5-migration-guide.rst @@ -82,7 +82,7 @@ ORM - In CakePHP 5 ``EntityTrait::has()`` will return true when an attribute exists and is set to null. Depending on your application this can lead to unexpected - behavior with your already present code. Use ``EntityTrait::hasValue()`` to + behavior with your existing code. Use ``EntityTrait::hasValue()`` to check if a field contains a 'non-empty' value. - ``Table::_initializeSchema()`` is deprecated. Override ``getSchema()`` instead, or re-map columns in ``initialize()``. From 544519bf014083c1b5919b98922dc55d8ea7fb9c Mon Sep 17 00:00:00 2001 From: Mark Story Date: Thu, 7 Sep 2023 00:28:54 -0400 Subject: [PATCH 04/68] Add docs for cakephp/cakephp#17252 --- en/appendices/4-5-migration-guide.rst | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/en/appendices/4-5-migration-guide.rst b/en/appendices/4-5-migration-guide.rst index 9e79d83aa3..ce90c93d52 100644 --- a/en/appendices/4-5-migration-guide.rst +++ b/en/appendices/4-5-migration-guide.rst @@ -201,6 +201,23 @@ I18n reference additional translation domains with `plugin_name.domain`. For example ``__d('DebugKit.errors', 'oh no')``. +ORM +--- + +``EntityTrait::$_hasAllowsNull`` was added. This property allows you to +incrementally opt-in to a breaking change present in 5.x for ``EntityTrait::has()`` +When set to true, this property will result in ``has()`` and related methods use +``array_key_exists`` instead of ``isset`` to decide if fields are 'defined' in an +entity. The semantic change is that usage like:: + + if ($user->has('name')) { + // More logic + } + +In 4.x this condition would **fail** if ``name`` was ``null``. However, in 5.0, +this will condition will now **pass**. You can prepare your application for this +change by incrementally setting ``$_hasAllowsNull``. + TestSuite --------- From 3f2507e8df518699e7fddfe546ab9ec907efe995 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Thu, 7 Sep 2023 08:24:51 -0700 Subject: [PATCH 05/68] Apply suggestions from code review Co-authored-by: othercorey --- en/appendices/4-5-migration-guide.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/en/appendices/4-5-migration-guide.rst b/en/appendices/4-5-migration-guide.rst index ce90c93d52..381174adc9 100644 --- a/en/appendices/4-5-migration-guide.rst +++ b/en/appendices/4-5-migration-guide.rst @@ -206,9 +206,9 @@ ORM ``EntityTrait::$_hasAllowsNull`` was added. This property allows you to incrementally opt-in to a breaking change present in 5.x for ``EntityTrait::has()`` -When set to true, this property will result in ``has()`` and related methods use +When set to true, this property will make ``has()`` and related methods use ``array_key_exists`` instead of ``isset`` to decide if fields are 'defined' in an -entity. The semantic change is that usage like:: +entity. This will affect code like:: if ($user->has('name')) { // More logic From 848ba18875206aba3bd47831d1cac4ba5e5eff39 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Thu, 7 Sep 2023 08:29:10 -0700 Subject: [PATCH 06/68] Apply suggestions from code review Co-authored-by: othercorey --- en/appendices/4-5-migration-guide.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/appendices/4-5-migration-guide.rst b/en/appendices/4-5-migration-guide.rst index 381174adc9..21bda320ba 100644 --- a/en/appendices/4-5-migration-guide.rst +++ b/en/appendices/4-5-migration-guide.rst @@ -205,7 +205,7 @@ ORM --- ``EntityTrait::$_hasAllowsNull`` was added. This property allows you to -incrementally opt-in to a breaking change present in 5.x for ``EntityTrait::has()`` +incrementally opt-in to a breaking change present in 5.x for ``EntityTrait::has()``. When set to true, this property will make ``has()`` and related methods use ``array_key_exists`` instead of ``isset`` to decide if fields are 'defined' in an entity. This will affect code like:: From 4cb42c5bd4428eb58ccd7789994eb22a59af5889 Mon Sep 17 00:00:00 2001 From: Kevin Pfeifer Date: Sun, 10 Sep 2023 13:17:24 +0200 Subject: [PATCH 07/68] add 5.x book link to 4.x --- config/conf.py | 1 + 1 file changed, 1 insertion(+) diff --git a/config/conf.py b/config/conf.py index 92922b87fd..9cfdb8bc6c 100644 --- a/config/conf.py +++ b/config/conf.py @@ -23,6 +23,7 @@ # Other versions that display in the version picker menu. version_list = [ + {'name': '5.x', 'number': '5', 'title': '5.x Book'}, {'name': '4.x', 'number': '4', 'current': True, 'title': '4.x Book'}, {'name': '3.x', 'number': '3', 'title': '3.x Book'}, {'name': '2.x', 'number': '2', 'title': '2.x Book'}, From 74ef6eb1a4e1fb45e84647370c35502d5febabbb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 11 Sep 2023 11:13:14 +0000 Subject: [PATCH 08/68] Bump actions/checkout from 3 to 4 Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v3...v4) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/ci.yml | 2 +- .github/workflows/deploy_4x.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6927263441..0f28774129 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,7 +21,7 @@ jobs: doc-type: ['HTML', 'EPUB', 'PDF'] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-python@v4 with: diff --git a/.github/workflows/deploy_4x.yml b/.github/workflows/deploy_4x.yml index 85187576da..2ed737b567 100644 --- a/.github/workflows/deploy_4x.yml +++ b/.github/workflows/deploy_4x.yml @@ -17,7 +17,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Cloning repo - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 From ad5c39087fe7e980145cbeee82e514574fce1bec Mon Sep 17 00:00:00 2001 From: MarwanSalim <45453458+MarwanSalim@users.noreply.github.com> Date: Mon, 11 Sep 2023 22:51:06 +0800 Subject: [PATCH 09/68] Update query-builder.rst Remove typos i.e. extra semi colon. --- en/orm/query-builder.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/en/orm/query-builder.rst b/en/orm/query-builder.rst index b1bebc9473..6f8f73f6f3 100644 --- a/en/orm/query-builder.rst +++ b/en/orm/query-builder.rst @@ -574,7 +574,7 @@ You can create ``if ... then ... else`` conditions by using ``else()``:: $published = $query->newExpr() ->case() ->when(['published' => true]) - ->then('Y'); + ->then('Y') ->else('N'); # CASE WHEN published = true THEN 'Y' ELSE 'N' END; @@ -584,7 +584,7 @@ Also, it's possible to create the simple variant by passing a value to ``case()` $published = $query->newExpr() ->case($query->identifier('published')) ->when(true) - ->then('Y'); + ->then('Y') ->else('N'); # CASE published WHEN true THEN 'Y' ELSE 'N' END; From 772a9b2818fb386f22a14ddee4f655b7be8e0539 Mon Sep 17 00:00:00 2001 From: NISHIMURA Daisuke Date: Wed, 20 Sep 2023 18:33:48 +0900 Subject: [PATCH 10/68] Update 4-4-migration-guide.rst (#7718) typo in deprecated component class name --- en/appendices/4-4-migration-guide.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/en/appendices/4-4-migration-guide.rst b/en/appendices/4-4-migration-guide.rst index 5098bbface..16d1f265b5 100644 --- a/en/appendices/4-4-migration-guide.rst +++ b/en/appendices/4-4-migration-guide.rst @@ -97,10 +97,10 @@ be removed in 5.0. ``RequestHandlerComponent``. -PaginationComponent -------------------- +PaginatorComponent +------------------ -The ``PaginationComponent`` is deprecated and will be removed in 5.0. +The ``PaginatorComponent`` is deprecated and will be removed in 5.0. Use the ``Controller::$paginate`` property or the ``$settings`` parameter of ``Controller::paginate()`` method to specify required paging settings. From 03669fa042ebcc31f0e1981d8391dfd6bd712780 Mon Sep 17 00:00:00 2001 From: Alex Mayer Date: Thu, 21 Sep 2023 12:17:18 -0400 Subject: [PATCH 11/68] Add Space Before In-line Code to Fix Rendering --- en/development/errors.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/development/errors.rst b/en/development/errors.rst index 243f0a8ad0..2448f3cb9d 100644 --- a/en/development/errors.rst +++ b/en/development/errors.rst @@ -369,7 +369,7 @@ Prior to CakePHP 4.4.0, you should implement ``logMessage()`` and ``log()``:: ErrorLoggerInterface was added. .. versionchanged:: 4.4.0 - ``ErrorLoggerInterface::logException()`` and``ErrorLoggerInterface::logError()`` were added. + ``ErrorLoggerInterface::logException()`` and ``ErrorLoggerInterface::logError()`` were added. Custom Error Rendering From 822543755fdfd86142350421a4352a66a1e9288b Mon Sep 17 00:00:00 2001 From: Alex Mayer Date: Thu, 21 Sep 2023 11:52:26 -0400 Subject: [PATCH 12/68] Remove Double Slash From AbstractTransport Class Name --- en/core-libraries/email.rst | 2 +- fr/core-libraries/email.rst | 2 +- pt/core-libraries/email.rst | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/en/core-libraries/email.rst b/en/core-libraries/email.rst index 63a29f3d80..2fa04b26ba 100644 --- a/en/core-libraries/email.rst +++ b/en/core-libraries/email.rst @@ -561,7 +561,7 @@ Sending emails without using Mailer =================================== The ``Mailer`` is a higher level abstraction class which acts as a bridge between -the ``Cake\Mailer\Message``, ``Cake\Mailer\Renderer`` and ``Cake\Mailer\\AbstractTransport`` +the ``Cake\Mailer\Message``, ``Cake\Mailer\Renderer`` and ``Cake\Mailer\AbstractTransport`` classes to configure emails with a fluent interface. If you want you can use these classes directly with the ``Mailer`` too. diff --git a/fr/core-libraries/email.rst b/fr/core-libraries/email.rst index 7711a1cbb4..b28dad2cf6 100644 --- a/fr/core-libraries/email.rst +++ b/fr/core-libraries/email.rst @@ -601,7 +601,7 @@ Envoyer des Emails sans utiliser Mailer Le ``Mailer`` est une classe à haut niveau d'abstraction, qui agit commme un pont entre les classes ``Cake\Mailer\Message``, ``Cake\Mailer\Renderer`` et -``Cake\Mailer\\AbstractTransport`` pour configuer les emails avec une interface +``Cake\Mailer\AbstractTransport`` pour configuer les emails avec une interface fluide. Si vous voulez, vous pouvez aussi utiliser ces classes directement avec le diff --git a/pt/core-libraries/email.rst b/pt/core-libraries/email.rst index 5ff3b7bba0..2dce0dcc7f 100644 --- a/pt/core-libraries/email.rst +++ b/pt/core-libraries/email.rst @@ -553,7 +553,7 @@ Enviar Emails sem Usar o Mailer =============================== O ``Mailer`` é uma classe de abstração de nível superior que atua como uma ponte entre as -classes ``Cake\Mailer\Message``, ``Cake\Mailer\Renderer`` e ``Cake\Mailer\\AbstractTransport`` +classes ``Cake\Mailer\Message``, ``Cake\Mailer\Renderer`` e ``Cake\Mailer\AbstractTransport`` para facilitar a configuração e entrega do e-mail. Se você quiser, pode usar essas classes diretamente com o ``Mailer`` também. From fab799fc9d87a819c5290f49db15ec48d36d3bb9 Mon Sep 17 00:00:00 2001 From: Bernat Date: Thu, 28 Sep 2023 12:35:45 +0200 Subject: [PATCH 13/68] Update PHP requirement for upgrading --- en/appendices/4-0-upgrade-guide.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/en/appendices/4-0-upgrade-guide.rst b/en/appendices/4-0-upgrade-guide.rst index 28cbd6cf89..982c36cfc3 100644 --- a/en/appendices/4-0-upgrade-guide.rst +++ b/en/appendices/4-0-upgrade-guide.rst @@ -20,10 +20,10 @@ Now that you can see all the warnings, make sure these are fixed before proceedi Upgrade to PHP 7.2 ================== -If you are not running on **PHP 7.2 or higher**, you will need to upgrade PHP before updating CakePHP. +If you are not running on **PHP 8.0 or higher**, you will need to upgrade PHP before updating CakePHP. .. note:: - CakePHP 4.0 requires **a minimum of PHP 7.2**. + Although CakePHP 4.0 requires **a minimum of PHP 7.2**, the upgrade tool requires **a minimum of PHP 8.0**. .. _upgrade-tool-use: From e8e79a471b806202bc9ab5d70ca7608f7e3cb306 Mon Sep 17 00:00:00 2001 From: Bernat Date: Thu, 28 Sep 2023 20:27:03 +0200 Subject: [PATCH 14/68] Update header for PHP requirement --- en/appendices/4-0-upgrade-guide.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/appendices/4-0-upgrade-guide.rst b/en/appendices/4-0-upgrade-guide.rst index 982c36cfc3..5904d1f002 100644 --- a/en/appendices/4-0-upgrade-guide.rst +++ b/en/appendices/4-0-upgrade-guide.rst @@ -17,7 +17,7 @@ Once your application is running on latest CakePHP 3.x, enable deprecation warni Now that you can see all the warnings, make sure these are fixed before proceeding with the upgrade. -Upgrade to PHP 7.2 +Upgrade to PHP 8.0 ================== If you are not running on **PHP 8.0 or higher**, you will need to upgrade PHP before updating CakePHP. From 7d7048b68b091eeff3b272fcaf3ad82f92afc20a Mon Sep 17 00:00:00 2001 From: pascaldaugeron <38015197+pascaldaugeron@users.noreply.github.com> Date: Wed, 4 Oct 2023 17:58:37 +0200 Subject: [PATCH 15/68] Update internationalization-and-localization.rst --- .../internationalization-and-localization.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/fr/core-libraries/internationalization-and-localization.rst b/fr/core-libraries/internationalization-and-localization.rst index a65fe8d8c6..b063d9b926 100644 --- a/fr/core-libraries/internationalization-and-localization.rst +++ b/fr/core-libraries/internationalization-and-localization.rst @@ -45,8 +45,8 @@ Ces fichiers doivent être placés dans **src/Locale/** et dans ce répertoire, devrait y avoir un sous-dossier par langue que l'application doit prendre en charge:: - /src - /Locale + /resources + /locales /en_US default.po /en_GB @@ -74,8 +74,8 @@ est d'utiliser la version ``under_scored`` du nom du plugin comme domaine de la traduction des messages:: MyPlugin - /src - /Locale + /resources + /locales /fr my_plugin.po /de From 190db5924e72a4ebc7146e846b367cc84e83a717 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sat, 14 Oct 2023 22:36:35 -0400 Subject: [PATCH 16/68] Update config file --- config/conf.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/config/conf.py b/config/conf.py index 873f0ab2af..3d6a94b8e6 100644 --- a/config/conf.py +++ b/config/conf.py @@ -10,13 +10,13 @@ # built documents. # # The short X.Y version. -version = '4.next' +version = '4.x' # The full version, including alpha/beta/rc tags. -release = '4.next' +release = '4.x' # The search index version. -search_version = '4-next' +search_version = '4' # The marketing diplay name for the book. version_name = 'Strawberry' From 445f314fa8b57e8d499b21fcf9453f9b9d7e6d71 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sat, 14 Oct 2023 22:57:07 -0400 Subject: [PATCH 17/68] Fix wrapping --- en/appendices/4-5-migration-guide.rst | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/en/appendices/4-5-migration-guide.rst b/en/appendices/4-5-migration-guide.rst index 21bda320ba..79f8a44161 100644 --- a/en/appendices/4-5-migration-guide.rst +++ b/en/appendices/4-5-migration-guide.rst @@ -20,9 +20,8 @@ Deprecations 4.5 introduces a few deprecations. All of these features will continue for the duration of 4.x but will be removed in 5.0. -You can use the -:ref:`upgrade tool ` to automate updating usage of deprecated -features:: +You can use the :ref:`upgrade tool ` to automate updating +usage of deprecated features:: bin/cake upgrade rector --rules cakephp45 @@ -109,7 +108,8 @@ Validation View ---- -- It is recommended to replace ``loadHelper()`` with new ``addHelper()`` method to add helpers in ``View::initialize()``. +- It is recommended to replace ``loadHelper()`` with new ``addHelper()`` method + to add helpers in ``View::initialize()``. New Features @@ -153,11 +153,13 @@ Core Database -------- -- ``ConnectionManager`` now supports read and write connection roles. Roles can be configured - with ``read`` and ``write`` keys in the connection config that override the shared config. +- ``ConnectionManager`` now supports read and write connection roles. Roles can + be configured with ``read`` and ``write`` keys in the connection config that + override the shared config. - ``ConnectionManager::aliases()`` was added. -- ``SelectQuery::setConnectionRole()``, ``SelectQuery::useReadRole()``, and ``SelectQuery::useWriteRole()`` - were added to let you switch a query to a specific connection role. +- ``SelectQuery::setConnectionRole()``, ``SelectQuery::useReadRole()``, and + ``SelectQuery::useWriteRole()`` were added to let you switch a query to + a specific connection role. Datasource ---------- From 4fc6aed52f8bbd8df96a17ee0f2d3dee72c7c34f Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sat, 14 Oct 2023 22:57:30 -0400 Subject: [PATCH 18/68] Fix deploy target. --- .github/workflows/deploy_4x.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy_4x.yml b/.github/workflows/deploy_4x.yml index 264dac0ca4..2ed737b567 100644 --- a/.github/workflows/deploy_4x.yml +++ b/.github/workflows/deploy_4x.yml @@ -24,6 +24,6 @@ jobs: - name: Push to dokku uses: dokku/github-action@master with: - git_remote_url: 'ssh://dokku@apps.cakephp.org:22/book-4next' + git_remote_url: 'ssh://dokku@apps.cakephp.org:22/book-4' git_push_flags: '-f' ssh_private_key: ${{ secrets.DOKKU_SSH_PRIVATE_KEY }} From 592165e34a885f26251fe3c06f78211670599a48 Mon Sep 17 00:00:00 2001 From: Chris Nizzardini Date: Wed, 18 Oct 2023 08:35:41 -0400 Subject: [PATCH 19/68] Fix syntax error in code sample Sample is missing closing bracket. --- en/orm/database-basics.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/orm/database-basics.rst b/en/orm/database-basics.rst index 3481982a77..5632dc356c 100644 --- a/en/orm/database-basics.rst +++ b/en/orm/database-basics.rst @@ -583,7 +583,7 @@ used:: $data = $schema->getColumn($column); $sql = $driver->quoteIdentifier($column); $sql .= ' JSON'; - if (isset($data['null') && $data['null'] === false) { + if (isset($data['null']) && $data['null'] === false) { $sql .= ' NOT NULL'; } return $sql; From 42d60e88e7ef67611a00c84c5485e2f20c31cf84 Mon Sep 17 00:00:00 2001 From: nmaya <5668936+nmaya@users.noreply.github.com> Date: Tue, 24 Oct 2023 07:56:01 +0900 Subject: [PATCH 20/68] ORM proxy method isEmpty() is deprecated add explanation to Retrieving Data sample code calling ResultSetInterface methods from Query object is deprecated from 4.3.0 mentioned in 4.3 migration guide, added at PR #7064 --- en/orm/retrieving-data-and-resultsets.rst | 1 + ja/orm/retrieving-data-and-resultsets.rst | 1 + 2 files changed, 2 insertions(+) diff --git a/en/orm/retrieving-data-and-resultsets.rst b/en/orm/retrieving-data-and-resultsets.rst index 16abab7b70..2c97c0b6b2 100644 --- a/en/orm/retrieving-data-and-resultsets.rst +++ b/en/orm/retrieving-data-and-resultsets.rst @@ -1053,6 +1053,7 @@ has any rows in it. Calling ``isEmpty()`` on a Query object will evaluate the query:: // Check a query. + // deprecated from CakePHP 4.3.0 $query->isEmpty(); // Check results diff --git a/ja/orm/retrieving-data-and-resultsets.rst b/ja/orm/retrieving-data-and-resultsets.rst index 1726a3b298..4832b89bb8 100644 --- a/ja/orm/retrieving-data-and-resultsets.rst +++ b/ja/orm/retrieving-data-and-resultsets.rst @@ -971,6 +971,7 @@ Query や ResultSet オブジェクトの ``isEmpty()`` メソッドを使うこ Query オブジェクトで ``isEmpty()`` メソッドを呼び出した場合はクエリーが評価されます。 :: // クエリーをチェックします + // CakePHP 4.3.0 からは非推奨 $query->isEmpty(); // 結果をチェックします From a876aabdae7676f2f7d8fd0f1483df53f9ce84cf Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sun, 29 Oct 2023 13:38:22 -0400 Subject: [PATCH 21/68] Expand request docs to cover proxy setup. Refs cakephp/cakephp#17354 --- en/controllers/request-response.rst | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/en/controllers/request-response.rst b/en/controllers/request-response.rst index 32ad7b89d6..103ae0ff15 100644 --- a/en/controllers/request-response.rst +++ b/en/controllers/request-response.rst @@ -545,6 +545,11 @@ have the request object use these headers set the ``trustProxy`` property to $scheme = $this->request->scheme(); $clientIp = $this->request->clientIp(); +In addition to trusting proxy headers, applications operating behind +a loadbalancer should define ``App.fullBaseUrl`` configuration value with the +public facing domain name and protocol so that URLs generated by the application +use the public facing domain name. + Once proxies are trusted the ``clientIp()`` method will use the *last* IP address in the ``X-Forwarded-For`` header. If your application is behind multiple proxies, you can use ``setTrustedProxies()`` to define the IP addresses @@ -553,8 +558,8 @@ of proxies in your control:: $request->setTrustedProxies(['127.1.1.1', '127.8.1.3']); After proxies are trusted ``clientIp()`` will use the first IP address in the -``X-Forwarded-For`` header providing it is the only value that isn't from a trusted -proxy. +``X-Forwarded-For`` header providing it is the only value that isn't from +a trusted proxy. Checking Accept Headers ----------------------- From 6691dc46721bbc9168f25567725102e14cc5d513 Mon Sep 17 00:00:00 2001 From: mscherer Date: Thu, 2 Nov 2023 03:54:11 +0100 Subject: [PATCH 22/68] Fix docs about plugin class name --- en/plugins.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/en/plugins.rst b/en/plugins.rst index 724cbe2c35..0dc914f377 100644 --- a/en/plugins.rst +++ b/en/plugins.rst @@ -94,7 +94,7 @@ Loading a Plugin ================ If you want to use a plugin's routes, console commands, middlewares, event -listeners, templates or webroot assets you will need to load the plugin. +listeners, templates or webroot assets you will need to load the plugin. Plugins are loaded in your application's ``bootstrap()`` function:: // In src/Application.php @@ -291,7 +291,7 @@ Plugin Objects Plugin Objects allow a plugin author to define set-up logic, define default hooks, load routes, middleware and console commands. Plugin objects live in -**src/Plugin.php**. For our ContactManager plugin, our plugin class could look +**src/{PluginName}Plugin.php**. For our ContactManager plugin, our plugin class could look like:: namespace ContactManager; From 3d593614f742605bad04882313793fa570a09169 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sun, 12 Nov 2023 22:47:38 -0500 Subject: [PATCH 23/68] Update docs for requesthandler replacement. I'll backport this to 4.x so that the 5.x migration guide docs provide the solution discussed as part of cakephp/cakephp#17415 --- en/controllers.rst | 16 ++++++++++++++++ en/views.rst | 6 +++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/en/controllers.rst b/en/controllers.rst index ee4d43a158..fa116587e5 100644 --- a/en/controllers.rst +++ b/en/controllers.rst @@ -358,6 +358,22 @@ content-type negotiation is attempted. Prior to 4.4 you must use :doc:`/controllers/components/request-handling` instead of ``viewClasses()``. +Using AjaxView +============== + +In applications that use hypermedia or AJAX clients, you often need to render +view contents without the wrapping layout. You can use the ``AjaxView`` that +is bundled with the application skeleton:: + + // In a controller action, or in beforeRender. + if ($this->request->is('ajax')) { + $this->viewBuilder()->setClassName('Ajax'); + } + +``AjaxView`` will respond as ``text/html`` and use the ``ajax`` layout. +Generally this layout is minimal or contains client specific markup. This +replaces usage of ``RequestHandlerComponent`` automatically using the +``AjaxView``. Redirecting to Other Pages ========================== diff --git a/en/views.rst b/en/views.rst index dc5662c95a..fe765e8d1a 100644 --- a/en/views.rst +++ b/en/views.rst @@ -117,9 +117,9 @@ Another example, using if/elseif/else. Notice the colons:

Hi unknown user

-If you'd prefer using a templating language like -`Twig `_, a subclass of View will bridge your -templating language and CakePHP. +If you'd prefer to use a templating language like +`Twig `_, checkout the `CakePHP Twig Plugin +`__ Template files are stored in **templates/**, in a folder named after the controller that uses the files, and named after the action it corresponds to. From 9232df57908f88dee626b4e1f12ee2bddb43fa5d Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sun, 12 Nov 2023 23:31:24 -0500 Subject: [PATCH 24/68] Update migration guide in 4.x --- en/appendices/4-4-migration-guide.rst | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/en/appendices/4-4-migration-guide.rst b/en/appendices/4-4-migration-guide.rst index 16d1f265b5..5ded1bca4b 100644 --- a/en/appendices/4-4-migration-guide.rst +++ b/en/appendices/4-4-migration-guide.rst @@ -96,6 +96,18 @@ be removed in 5.0. - Use :ref:`controller-viewclasses` instead of defining view class mappings in ``RequestHandlerComponent``. +The automatic view switching for 'ajax' requests offered by +``RequestHandlerComponent`` is no longer available. Instead you can either +handle this in a controller action or ``Controller.beforeRender`` callback +with:: + + // In a controller action, or in beforeRender. + if ($this->request->is('ajax')) { + $this->viewBuilder()->setClassName('Ajax'); + } + +Alternatively, you can have the HTML view class switch to the ``ajax`` layout as +required in your controller actions or view templates. PaginatorComponent ------------------ From c879ad6ede57e4fe7139675a356df6952f6132b3 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Tue, 14 Nov 2023 00:17:43 -0500 Subject: [PATCH 25/68] Switch removed to deprecated --- en/appendices/4-4-migration-guide.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/appendices/4-4-migration-guide.rst b/en/appendices/4-4-migration-guide.rst index 5ded1bca4b..9b45fa5ed5 100644 --- a/en/appendices/4-4-migration-guide.rst +++ b/en/appendices/4-4-migration-guide.rst @@ -97,7 +97,7 @@ be removed in 5.0. ``RequestHandlerComponent``. The automatic view switching for 'ajax' requests offered by -``RequestHandlerComponent`` is no longer available. Instead you can either +``RequestHandlerComponent`` is deprecated. Instead you can either handle this in a controller action or ``Controller.beforeRender`` callback with:: From 4cbe1591a2e69df3aa50fe8048c94ddf0818b4c5 Mon Sep 17 00:00:00 2001 From: Al <7813306+mehov@users.noreply.github.com> Date: Fri, 1 Dec 2023 10:42:32 +0100 Subject: [PATCH 26/68] =?UTF-8?q?Address=20`WITH=20RECURSIVE=20=E2=80=A6`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- en/orm/query-builder.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/en/orm/query-builder.rst b/en/orm/query-builder.rst index dc49aa0ca3..ba1f5d28f7 100644 --- a/en/orm/query-builder.rst +++ b/en/orm/query-builder.rst @@ -1904,6 +1904,8 @@ To build that query with the ORM query builder we would use:: ] ]); +If you need to build a recursive query (`WITH RECURSIVE …`), chain `->recursive()` onto `return $cte`. + .. versionadded:: 4.1.0 Common table expression support was added. From 7e71303b920ed4624bb492e69d8a483f0eca03db Mon Sep 17 00:00:00 2001 From: Al <7813306+mehov@users.noreply.github.com> Date: Wed, 6 Dec 2023 17:28:01 +0100 Subject: [PATCH 27/68] Commit suggestion by @markstory in en/orm/query-builder.rst Co-authored-by: Mark Story --- en/orm/query-builder.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/orm/query-builder.rst b/en/orm/query-builder.rst index ba1f5d28f7..394da91fdb 100644 --- a/en/orm/query-builder.rst +++ b/en/orm/query-builder.rst @@ -1904,7 +1904,7 @@ To build that query with the ORM query builder we would use:: ] ]); -If you need to build a recursive query (`WITH RECURSIVE …`), chain `->recursive()` onto `return $cte`. +If you need to build a recursive query (``WITH RECURSIVE …``), chain ``->recursive()`` onto ``return $cte``. .. versionadded:: 4.1.0 Common table expression support was added. From 9bdcd5e04f95e5d1bad29f5f5f3ed1c392a8103d Mon Sep 17 00:00:00 2001 From: othercorey Date: Sat, 6 Jan 2024 18:13:25 -0600 Subject: [PATCH 28/68] Use 4.5.x package dependency when upgrading --- en/appendices/4-5-migration-guide.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/appendices/4-5-migration-guide.rst b/en/appendices/4-5-migration-guide.rst index 79f8a44161..109fbade13 100644 --- a/en/appendices/4-5-migration-guide.rst +++ b/en/appendices/4-5-migration-guide.rst @@ -9,7 +9,7 @@ Upgrading to 4.5.0 You can can use composer to upgrade to CakePHP 4.5.0:: - php composer.phar require --update-with-dependencies "cakephp/cakephp:^4.5" + php composer.phar require --update-with-dependencies "cakephp/cakephp:4.5.x" .. note:: CakePHP 4.5 requires PHP 7.4 or greater. From 0a7d5c9e72085a06435c1ffd676379c901ec856b Mon Sep 17 00:00:00 2001 From: Mark Story Date: Tue, 9 Jan 2024 10:32:25 -0500 Subject: [PATCH 29/68] Add deprecations for setAction. Refs #7794 --- en/appendices/4-2-migration-guide.rst | 11 ++++++++--- en/controllers.rst | 4 ++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/en/appendices/4-2-migration-guide.rst b/en/appendices/4-2-migration-guide.rst index dfcbebb8ce..b67a0a168d 100644 --- a/en/appendices/4-2-migration-guide.rst +++ b/en/appendices/4-2-migration-guide.rst @@ -36,6 +36,11 @@ Core - ``Cake\Core\Exception\Exception`` was renamed to ``Cake\Core\Exception\CakeException``. +Controller +---------- + +- ``Controller::setAction()`` is deprecated. Either update your code to use + redirects, or call the required action as a method. Database -------- @@ -106,9 +111,9 @@ Validation - ``Validation::time()`` will now reject a string if minutes are missing. Previously, this would accept hours-only digits although the api documentation showed minutes were required. -- ``Validation::comparison()`` (and as a result other comparison methods which use it) - now only work for numeric string. Earlier it relied on pretty brittle behavior - of casting any given value to float for comparison which could lead of incorrect +- ``Validation::comparison()`` (and as a result other comparison methods which use it) + now only work for numeric string. Earlier it relied on pretty brittle behavior + of casting any given value to float for comparison which could lead of incorrect results for non-numeric strings. Breaking Changes diff --git a/en/controllers.rst b/en/controllers.rst index fa116587e5..bfa7207201 100644 --- a/en/controllers.rst +++ b/en/controllers.rst @@ -432,6 +432,10 @@ the named action:: // list page. $this->setAction('index'); + +.. deprecated:: 4.2.0 + Use redirects or call the other action as a method. + Loading Additional Models ========================= From 136071e1dff22a0b9882997ee82d923acdee3e3b Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sat, 13 Jan 2024 16:44:18 -0500 Subject: [PATCH 30/68] Add TLS options to redis docs Refs cakephp/cakephp#17144 --- en/core-libraries/caching.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/en/core-libraries/caching.rst b/en/core-libraries/caching.rst index 97aa15fd7e..9921c84700 100644 --- a/en/core-libraries/caching.rst +++ b/en/core-libraries/caching.rst @@ -172,6 +172,13 @@ RedisEngine uses the following engine specific options: * ``persistent`` Should a persistent connection be made to Redis. * ``timeout`` Connection timeout for Redis. * ``unix_socket`` Path to a unix socket for Redis. +* ``tls`` Connect to redis over TLS. +* ``ssl_key`` The ssl private key used for TLS connections. +* ``ssl_ca`` The ssl certificate authority file for TLS connections. +* ``ssl_cert`` The ssl certificate used for TLS connections. + +.. versionadded:: 4.6.0 + TLS connections were added in 4.6 MemcacheEngine Options ---------------------- From 2a01959b0c7db54fc82757f49e68c9730206166b Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sat, 13 Jan 2024 16:44:35 -0500 Subject: [PATCH 31/68] Start 4.6 migration guide --- en/appendices/4-6-migration-guide.rst | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 en/appendices/4-6-migration-guide.rst diff --git a/en/appendices/4-6-migration-guide.rst b/en/appendices/4-6-migration-guide.rst new file mode 100644 index 0000000000..d616c786f6 --- /dev/null +++ b/en/appendices/4-6-migration-guide.rst @@ -0,0 +1,25 @@ +4.6 Migration Guide +################### + +CakePHP 4.6 is an API compatible upgrade from 4.0. This page outlines the +deprecations and features added in 4.6. + +Upgrading to 4.6.0 +================== + +You can can use composer to upgrade to CakePHP 4.6.0:: + + php composer.phar require --update-with-dependencies "cakephp/cakephp:^4.6" + +.. note:: + CakePHP 4.6 requires PHP 7.4 or greater. + +New Features +============ + +Cache +----- + +- ``RedisEngine`` now supports a ``tls`` option that enables connecting to redis + over a TLS connection. You can use the ``ssl_ca``, ``ssl_cert`` and + ``ssl_key`` options to define the TLS context for redis. From b1e380c7d31ffe8fbafdb852d569d7a53d293690 Mon Sep 17 00:00:00 2001 From: Anurag Raghuvanshi <59005831+raghuvanshi65@users.noreply.github.com> Date: Mon, 15 Jan 2024 21:38:40 +0530 Subject: [PATCH 32/68] Update configuration.rst Just a small Typo Correction --- en/development/configuration.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/development/configuration.rst b/en/development/configuration.rst index cd79f8e4fa..88ac417d31 100644 --- a/en/development/configuration.rst +++ b/en/development/configuration.rst @@ -26,7 +26,7 @@ configuration that doesn't vary across the various environments your application is deployed in. The **config/app_local.php** file should contain the configuration data that varies between environments and should be managed by configuration management, or your deployment tooling. Both of these files reference environment variables -through the ``env()`` function that enables configuration values to set though +through the ``env()`` function that enables configuration values to set through the server environment. Loading Additional Configuration Files From 69b632ab25efb49789b5b3960989234a17d2928a Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sat, 20 Jan 2024 21:34:12 -0500 Subject: [PATCH 33/68] Add notes to docs for roundingMode Refs cakephp/cakephp#17548 --- en/appendices/4-6-migration-guide.rst | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/en/appendices/4-6-migration-guide.rst b/en/appendices/4-6-migration-guide.rst index d616c786f6..4175d4249d 100644 --- a/en/appendices/4-6-migration-guide.rst +++ b/en/appendices/4-6-migration-guide.rst @@ -23,3 +23,16 @@ Cache - ``RedisEngine`` now supports a ``tls`` option that enables connecting to redis over a TLS connection. You can use the ``ssl_ca``, ``ssl_cert`` and ``ssl_key`` options to define the TLS context for redis. + +I18n +---- + +- ``Number::formatter()`` and ``currency()`` now accept a ``roundingMode`` + option to override how rounding is done. + + +View +---- + +- ``NumberHelper::format()`` now accepts a ``roundingMode`` option to override how + rounding is done. From d811294b86ad7667035b871b9c4cbf83c0575bdf Mon Sep 17 00:00:00 2001 From: "@zuborawka" Date: Wed, 24 Jan 2024 16:17:14 +0900 Subject: [PATCH 34/68] =?UTF-8?q?change=20"=E3=81=9D=E3=81=AE"=20to=20"?= =?UTF-8?q?=E3=81=9D=E3=82=8C=E3=81=9E=E3=82=8C=E3=81=AE"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I believe the phrase "which table" should be translated as "それぞれのテーブル" rather than "どのテーブル." --- ja/orm/table-objects.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ja/orm/table-objects.rst b/ja/orm/table-objects.rst index 3835b0430f..2250945e51 100644 --- a/ja/orm/table-objects.rst +++ b/ja/orm/table-objects.rst @@ -451,7 +451,7 @@ CakePHP によって提供されるビヘイビアーを含む、ビヘイビア ======== デフォルトでは、全てのテーブルインスタンスは ``default`` データベース接続を使用します。 -もし、複数のデータベース接続を使用している場合、どのコネクションを使用してテーブルを +もし、複数のデータベース接続を使用している場合、それぞれのコネクションを使用してテーブルを 設定したくなるでしょう。これは、 ``defaultConnectionName()`` メソッドで出来ます。 :: namespace App\Model\Table; From 9f0e8e507e03b7a90d20aedc9882441b0f364865 Mon Sep 17 00:00:00 2001 From: Mauro Date: Wed, 31 Jan 2024 14:11:54 -0300 Subject: [PATCH 35/68] Clarify error logging configuration (#7804) --- en/development/errors.rst | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/en/development/errors.rst b/en/development/errors.rst index aa2385dda8..24f92d1c66 100644 --- a/en/development/errors.rst +++ b/en/development/errors.rst @@ -312,7 +312,7 @@ Custom Error Logging Error handlers use instances of ``Cake\Error\ErrorLoggingInterface`` to create log messages and log them to the appropriate place. You can replace the error -logger using the ``Error.errorLogger`` configure value. An example error +logger using the ``Error.logger`` configure value. An example error logger:: namespace App\Error; @@ -349,7 +349,8 @@ logger:: } } -Prior to CakePHP 4.4.0, you should implement ``logMessage()`` and ``log()``:: +Prior to CakePHP 4.4.0, you should implement ``logMessage()`` and ``log()``, and then +replace the error logger using the ``Error.errorLogger`` configure value:: namespace App\Error; From 28e7f1040cadb9b15b6e276cebc8a64bf8357db7 Mon Sep 17 00:00:00 2001 From: MarwanSalim <45453458+MarwanSalim@users.noreply.github.com> Date: Mon, 5 Feb 2024 10:05:04 +0800 Subject: [PATCH 36/68] Update form.rst The `notEmpty()` validator already deprecated since 3.7.0. Need to use `notEmptyString()` instead. Refer [#1](https://github.com/cakephp/cakephp/blob/9cb11c941566cae80a825889a2c007e1860abbd3/src/Validation/Validator.php#L1185-L1193) and [#2](https://github.com/cakephp/cakephp/blob/9cb11c941566cae80a825889a2c007e1860abbd3/src/Validation/Validator.php#L1197-L1201) --- en/views/helpers/form.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/en/views/helpers/form.rst b/en/views/helpers/form.rst index 4e9078bf9b..8859cc0c78 100644 --- a/en/views/helpers/form.rst +++ b/en/views/helpers/form.rst @@ -1814,12 +1814,12 @@ error messages per field. Example:: - // If in TicketsTable you have a 'notEmpty' validation rule: + // If in TicketsTable you have a 'notEmptyString' validation rule: public function validationDefault(Validator $validator): Validator { $validator ->requirePresence('ticket', 'create') - ->notEmpty('ticket'); + ->notEmptyString('ticket'); } // And inside templates/Tickets/add.php you have: From 1a7f059fc54f9862116ac1a35d87ead9e53e350f Mon Sep 17 00:00:00 2001 From: Noel da Costa Date: Tue, 19 Mar 2024 09:57:26 +0000 Subject: [PATCH 37/68] Update errors.rst - code shown won't compile The extension class doesn't match the used class --- en/development/errors.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/development/errors.rst b/en/development/errors.rst index 24f92d1c66..64d1ee6a71 100644 --- a/en/development/errors.rst +++ b/en/development/errors.rst @@ -447,7 +447,7 @@ provide more context around your errors:: use Cake\Core\Exception\CakeException; - class MissingWidgetException extends Exception + class MissingWidgetException extends CakeException { // Context data is interpolated into this format string. protected $_messageTemplate = 'Seems that %s is missing.'; From ebdc79f261326147cb8d88663a910b9da6c34cf2 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Wed, 27 Mar 2024 08:46:24 +0100 Subject: [PATCH 38/68] Add DDEV section to docs after cakephp type has been released --- en/installation.rst | 30 +++++++++++++++++++++++------- es/installation.rst | 30 ++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 7 deletions(-) diff --git a/en/installation.rst b/en/installation.rst index 135af3ed48..2da2b1f86b 100644 --- a/en/installation.rst +++ b/en/installation.rst @@ -117,19 +117,35 @@ Each time you run ``php composer.phar update`` you will receive patch releases for this minor version. You can instead change this to ``^4.4`` to also receive the latest stable minor releases of the ``4.x`` branch. -Installation using Oven +Installation using DDEV ----------------------- -Another quick way to install CakePHP is via `Oven `_. -It is a small PHP script which checks the necessary system requirements, -and creates a new CakePHP application. +Another quick way to install CakePHP is via `DDEV `_. +It is an open source tool for launching local web development environments. + +If you want to configure a new project, you just need:: + + mkdir my-cakephp-app + cd my-cakephp-app + ddev config --project-type=cakephp --docroot=webroot + ddev composer create --prefer-dist cakephp/app:~4.0 + ddev launch + +If you have an existing project:: + + git clone + cd + ddev config --project-type=cakephp --docroot=webroot + ddev composer install + ddev launch + +Please check `DDEV Docs `_ for details on how to install / update DDEV. .. note:: IMPORTANT: This is not a deployment script. It is aimed to help developers - install CakePHP for the first time and set up a development environment - quickly. Production environments should consider several other factors, like - file permissions, virtualhost configuration, etc. + to set up a development environment quickly. It is not intended for + production environments. Permissions =========== diff --git a/es/installation.rst b/es/installation.rst index a3cb5d76b9..6829efbbe3 100644 --- a/es/installation.rst +++ b/es/installation.rst @@ -91,6 +91,36 @@ Donde ```` es el nombre del branch que quieres seguir. Cada vez que ejecutes ``php composer.phar update`` recibirás las últimas actualizaciones del branch seleccionado. +Instalación usando DDEV +----------------------- + +Otra manera rápida de instalar CakePHP es via `DDEV `_. +DDEV es una herramienta de código abierto para lanzar ambientes de desarrollo web en local. + +Si quieres configurar un nuevo proyecto, sólo necesitas ejecutar:: + + mkdir my-cakephp-app + cd my-cakephp-app + ddev config --project-type=cakephp --docroot=webroot + ddev composer create --prefer-dist cakephp/app:~4.0 + ddev launch + +Si tienes un proyecto existente:: + + git clone + cd + ddev config --project-type=cakephp --docroot=webroot + ddev composer install + ddev launch + +Por favor revisa la `Documentación de DDEV `_ para más detalles de cómo instalar / actualizar DDEV. + +.. note:: + + IMPORTANTE: Ésto no es un script de despliegue. Su objetivo es ayudar desarrolladores a + configurar ambientes de desarrollo rápidamente. En ningún caso su intención es que sea utilizado + en ambientes de producción. + Permisos ======== From 147ece6eee530b6bda728b57a685baae0dae8df0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc=20W=C3=BCrth?= Date: Thu, 11 Apr 2024 16:30:24 +0200 Subject: [PATCH 39/68] CakePHP not in lower case --- en/development/testing.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/development/testing.rst b/en/development/testing.rst index a9c6703def..af530916e4 100644 --- a/en/development/testing.rst +++ b/en/development/testing.rst @@ -776,7 +776,7 @@ create 5 articles each with 2 authors:: Note that the fixture factories do not require any fixture creation or declaration. Still, they are fully compatible with the fixtures that come with -cakephp. You will find additional insights and documentation `here +CakePHP. You will find additional insights and documentation `here `_. Loading Routes in Tests From 14b4dd44ea6161576df297db229898f5b3de96e0 Mon Sep 17 00:00:00 2001 From: othercorey Date: Sun, 14 Apr 2024 01:43:31 -0500 Subject: [PATCH 40/68] Add notes for https://github.com/cakephp/cakephp/pull/17642 --- en/appendices/4-6-migration-guide.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/en/appendices/4-6-migration-guide.rst b/en/appendices/4-6-migration-guide.rst index 4175d4249d..a7587b4040 100644 --- a/en/appendices/4-6-migration-guide.rst +++ b/en/appendices/4-6-migration-guide.rst @@ -24,6 +24,11 @@ Cache over a TLS connection. You can use the ``ssl_ca``, ``ssl_cert`` and ``ssl_key`` options to define the TLS context for redis. +Console +------- + +- Optional ``Command`` arguments can now have a ``default`` value. + I18n ---- From 092b106a0cdf41d30a8c6a349103b3a9def5027d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc=20W=C3=BCrth?= Date: Thu, 2 May 2024 14:22:30 +0200 Subject: [PATCH 41/68] Grammar --- en/orm/validation.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/orm/validation.rst b/en/orm/validation.rst index a3693a0e02..cd66f4c407 100644 --- a/en/orm/validation.rst +++ b/en/orm/validation.rst @@ -580,7 +580,7 @@ those rules into re-usable classes:: $rules->add(new CustomRule(...), 'ruleName'); -By creating custom rule classes you can keep your code DRY and tests your domain +By creating custom rule classes you can keep your code DRY and test your domain rules in isolation. Disabling Rules From 1f55ebd0fe3f42c24d2e2b04ebc3ae312a9696a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc=20W=C3=BCrth?= Date: Thu, 2 May 2024 14:25:04 +0200 Subject: [PATCH 42/68] Add clarifying comment about usage of custom rule This should clear up questions like these: https://discourse.cakephp.org/t/rule-isunique-and-allowmultiplenulls/9004 --- en/orm/validation.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/en/orm/validation.rst b/en/orm/validation.rst index cd66f4c407..603c4174f4 100644 --- a/en/orm/validation.rst +++ b/en/orm/validation.rst @@ -540,6 +540,7 @@ Creating Custom re-usable Rules You may want to re-use custom domain rules. You can do so by creating your own invokable rule:: + // Using a custom rule of the application use App\ORM\Rule\IsUniqueWithNulls; // ... public function buildRules(RulesChecker $rules): RulesChecker From e76cdcca38ba30ab9635d3e7d7075b4f78ef2c39 Mon Sep 17 00:00:00 2001 From: "marc.wuerth" Date: Thu, 2 May 2024 17:01:09 +0200 Subject: [PATCH 43/68] Add blank line before return statements in examples This brings the examples in line with the CakePHP coding conventions / code style standard, respectively: https://book.cakephp.org/4/en/contributing/cakephp-coding-conventions.html#method-definition https://github.com/cakephp/cakephp-codesniffer/blob/b12f9307475a74f8ee7625c7741fe2f54598cb0b/docs/README.md#L14 https://github.com/cakephp/cakephp-codesniffer/blob/b12f9307475a74f8ee7625c7741fe2f54598cb0b/CakePHP/Sniffs/Formatting/BlankLineBeforeReturnSniff.php --- en/console-commands/commands.rst | 15 +- en/console-commands/shells.rst | 2 + en/controllers/components.rst | 2 + en/controllers/components/authentication.rst | 3 + en/core-libraries/events.rst | 3 + en/core-libraries/hash.rst | 1 + en/core-libraries/logging.rst | 2 + en/development/sessions.rst | 2 + en/development/testing.rst | 5 +- en/installation.rst | 1 + en/orm/behaviors.rst | 1 + en/orm/behaviors/tree.rst | 7 +- en/orm/query-builder.rst | 10 +- en/orm/retrieving-data-and-resultsets.rst | 8 +- en/orm/table-objects.rst | 11 +- en/orm/validation.rst | 5 + en/security/csrf.rst | 5 +- .../blog-auth-example/auth.rst | 2 + en/tutorials-and-examples/blog/part-three.rst | 1 + en/tutorials-and-examples/blog/part-two.rst | 3 + en/tutorials-and-examples/bookmarks/intro.rst | 1 + .../bookmarks/part-two.rst | 5 + .../cms/articles-controller.rst | 3 + .../cms/authentication.rst | 3 +- .../cms/authorization.rst | 2 + .../cms/tags-and-users.rst | 3 + en/views/helpers/breadcrumbs.rst | 1 + en/views/helpers/form.rst | 5 +- es/controllers/components.rst | 32 ++-- es/orm/behaviors/tree.rst | 1 + .../blog-auth-example/auth.rst | 3 + es/tutorials-and-examples/blog/part-three.rst | 1 + es/tutorials-and-examples/blog/part-two.rst | 3 + es/tutorials-and-examples/bookmarks/intro.rst | 1 + .../bookmarks/part-two.rst | 5 + fr/console-commands/commands.rst | 13 +- fr/console-commands/shells.rst | 2 + fr/controllers/components.rst | 2 + fr/controllers/components/authentication.rst | 3 + fr/controllers/middleware.rst | 3 +- fr/controllers/request-response.rst | 1 + fr/core-libraries/caching.rst | 1 + fr/core-libraries/events.rst | 2 + fr/core-libraries/hash.rst | 1 + fr/core-libraries/logging.rst | 2 + fr/development/sessions.rst | 2 + fr/development/testing.rst | 11 +- fr/installation.rst | 1 + fr/orm/behaviors.rst | 1 + fr/orm/behaviors/tree.rst | 1 + fr/orm/query-builder.rst | 9 +- fr/orm/retrieving-data-and-resultsets.rst | 12 +- fr/orm/table-objects.rst | 9 +- fr/orm/validation.rst | 6 + fr/security/csrf.rst | 1 + .../blog-auth-example/auth.rst | 2 + fr/tutorials-and-examples/blog/part-three.rst | 1 + fr/tutorials-and-examples/blog/part-two.rst | 3 + fr/tutorials-and-examples/bookmarks/intro.rst | 1 + .../bookmarks/part-two.rst | 5 + .../cms/articles-controller.rst | 3 + .../cms/authentication.rst | 1 + .../cms/authorization.rst | 2 + .../cms/tags-and-users.rst | 3 + fr/views/helpers/breadcrumbs.rst | 1 + fr/views/helpers/form.rst | 1 + ja/console-commands/commands.rst | 1 + ja/console-commands/shells.rst | 2 + ja/controllers/components.rst | 2 + ja/controllers/components/authentication.rst | 3 + ja/controllers/middleware.rst | 3 +- ja/core-libraries/events.rst | 1 + ja/core-libraries/logging.rst | 2 + ja/development/errors.rst | 1 + ja/development/sessions.rst | 2 + ja/development/testing.rst | 2 + ja/orm/behaviors.rst | 1 + ja/orm/query-builder.rst | 6 + ja/orm/retrieving-data-and-resultsets.rst | 2 + ja/orm/validation.rst | 2 + ja/security/csrf.rst | 1 + .../blog-auth-example/auth.rst | 2 + ja/tutorials-and-examples/blog/part-three.rst | 1 + ja/tutorials-and-examples/blog/part-two.rst | 3 + ja/tutorials-and-examples/bookmarks/intro.rst | 1 + .../bookmarks/part-two.rst | 5 + .../cms/articles-controller.rst | 3 + .../cms/authentication.rst | 1 + .../cms/tags-and-users.rst | 1 + ja/views/helpers/breadcrumbs.rst | 1 + ja/views/helpers/form.rst | 1 + pt/console-and-shells.rst | 4 + pt/controllers/components.rst | 97 ++++++------ pt/controllers/components/authentication.rst | 3 + pt/controllers/middleware.rst | 144 +++++++++--------- pt/core-libraries/events.rst | 2 + pt/development/configuration.rst | 1 + pt/development/sessions.rst | 4 +- pt/development/testing.rst | 3 + pt/orm/behaviors.rst | 1 + pt/orm/behaviors/tree.rst | 1 + pt/orm/query-builder.rst | 7 + pt/orm/retrieving-data-and-resultsets.rst | 2 + .../blog-auth-example/auth.rst | 3 + pt/tutorials-and-examples/blog/part-three.rst | 1 + pt/tutorials-and-examples/blog/part-two.rst | 3 + pt/tutorials-and-examples/bookmarks/intro.rst | 1 + .../bookmarks/part-two.rst | 7 +- 108 files changed, 415 insertions(+), 183 deletions(-) diff --git a/en/console-commands/commands.rst b/en/console-commands/commands.rst index 8f5fac2ec7..0976e382c9 100644 --- a/en/console-commands/commands.rst +++ b/en/console-commands/commands.rst @@ -27,7 +27,7 @@ simple Hello world command. In your application's **src/Command** directory crea public function execute(Arguments $args, ConsoleIo $io): int { $io->out('Hello world.'); - + return static::CODE_SUCCESS; } } @@ -62,6 +62,7 @@ command line:: $parser->addArgument('name', [ 'help' => 'What is your name' ]); + return $parser; } @@ -69,7 +70,7 @@ command line:: { $name = $args->getArgument('name'); $io->out("Hello {$name}."); - + return static::CODE_SUCCESS; } } @@ -128,7 +129,7 @@ add a ``yell`` option to our ``HelloCommand``:: $name = mb_strtoupper($name); } $io->out("Hello {$name}."); - + return static::CODE_SUCCESS; } @@ -202,7 +203,7 @@ to terminate execution:: $io->error('Name must be at least 4 characters long.'); $this->abort(); } - + return static::CODE_SUCCESS; } @@ -215,7 +216,7 @@ You can also use ``abort()`` on the ``$io`` object to emit a message and code:: // Halt execution, output to stderr, and set exit code to 99 $io->abort('Name must be at least 4 characters long.', 99); } - + return static::CODE_SUCCESS; } @@ -384,7 +385,7 @@ conventions. Let's continue by adding more logic to our command:: 'modified' => new FrozenTime() ]) ->execute(); - + return static::CODE_SUCCESS; } } @@ -486,7 +487,7 @@ Update the command class to the following:: 'modified' => new FrozenTime() ]) ->execute(); - + return static::CODE_SUCCESS; } } diff --git a/en/console-commands/shells.rst b/en/console-commands/shells.rst index e38f0b5a33..fe607da775 100644 --- a/en/console-commands/shells.rst +++ b/en/console-commands/shells.rst @@ -146,12 +146,14 @@ Also, the task name must be added as a sub-command to the Shell's OptionParser:: public function getOptionParser() { $parser = parent::getOptionParser(); + $parser->addSubcommand('sound', [ // Provide help text for the command list 'help' => 'Execute The Sound Task.', // Link the option parsers together. 'parser' => $this->Sound->getOptionParser(), ]); + return $parser; } diff --git a/en/controllers/components.rst b/en/controllers/components.rst index aa4df27d18..dd6ffc4dc6 100644 --- a/en/controllers/components.rst +++ b/en/controllers/components.rst @@ -142,6 +142,7 @@ in your controller, you could access it like so:: { if ($this->Post->delete($this->request->getData('Post.id')) { $this->Flash->success('Post deleted.'); + return $this->redirect(['action' => 'index']); } } @@ -317,6 +318,7 @@ To redirect from within a component callback method you can use the following:: public function beforeFilter(EventInterface $event) { $event->stopPropagation(); + return $this->getController()->redirect('/'); } diff --git a/en/controllers/components/authentication.rst b/en/controllers/components/authentication.rst index c4fc22c4c3..b5ea2ef285 100644 --- a/en/controllers/components/authentication.rst +++ b/en/controllers/components/authentication.rst @@ -228,6 +228,7 @@ working with a login form could look like:: $user = $this->Auth->identify(); if ($user) { $this->Auth->setUser($user); + return $this->redirect($this->Auth->redirectUrl()); } else { $this->Flash->error(__('Username or password is incorrect')); @@ -444,6 +445,7 @@ from the normal password hash:: $entity->plain_password, env('SERVER_NAME') ); + return true; } } @@ -721,6 +723,7 @@ calling ``$this->Auth->setUser()`` with the user data you want to 'login':: $user = $this->Users->newEntity($this->request->getData()); if ($this->Users->save($user)) { $this->Auth->setUser($user->toArray()); + return $this->redirect([ 'controller' => 'Users', 'action' => 'home' diff --git a/en/core-libraries/events.rst b/en/core-libraries/events.rst index 7bdc697352..4d840388c5 100644 --- a/en/core-libraries/events.rst +++ b/en/core-libraries/events.rst @@ -61,10 +61,12 @@ has been created. To keep your Orders model clean you could use events:: { if ($this->save($order)) { $this->Cart->remove($order); + $event = new Event('Order.afterPlace', $this, [ 'order' => $order ]); $this->getEventManager()->dispatch($event); + return true; } return false; @@ -456,6 +458,7 @@ directly or returning the value in the callback itself:: { // ... $alteredData = $event->getData('order') + $moreData; + return $alteredData; } diff --git a/en/core-libraries/hash.rst b/en/core-libraries/hash.rst index bab09fdde3..cc93c378fc 100644 --- a/en/core-libraries/hash.rst +++ b/en/core-libraries/hash.rst @@ -633,6 +633,7 @@ Attribute Matching Types public function noop(array $array) { // Do stuff to array and return the result + return $array; } diff --git a/en/core-libraries/logging.rst b/en/core-libraries/logging.rst index 4111274ebf..c895ced115 100644 --- a/en/core-libraries/logging.rst +++ b/en/core-libraries/logging.rst @@ -471,6 +471,7 @@ After installing Monolog using composer, configure the logger using the Log::setConfig('default', function () { $log = new Logger('app'); $log->pushHandler(new StreamHandler('path/to/your/combined.log')); + return $log; }); @@ -488,6 +489,7 @@ Use similar methods if you want to configure a different logger for your console Log::setConfig('default', function () { $log = new Logger('cli'); $log->pushHandler(new StreamHandler('path/to/your/combined-cli.log')); + return $log; }); diff --git a/en/development/sessions.rst b/en/development/sessions.rst index 55bafcbdf3..9fd2045161 100644 --- a/en/development/sessions.rst +++ b/en/development/sessions.rst @@ -303,6 +303,7 @@ something like:: public function write($id, $data): bool { Cache::write($id, $data, $this->cacheKey); + return parent::write($id, $data); } @@ -310,6 +311,7 @@ something like:: public function destroy($id): bool { Cache::delete($id, $this->cacheKey); + return parent::destroy($id); } diff --git a/en/development/testing.rst b/en/development/testing.rst index af530916e4..c9b7358c30 100644 --- a/en/development/testing.rst +++ b/en/development/testing.rst @@ -147,6 +147,7 @@ Our helper looks like:: public function bar($value) { $width = round($value / 100, 2) * 100; + return sprintf( '
@@ -867,6 +868,7 @@ Let's say we already have our Articles Table class defined in $query->where([ $this->getAlias() . '.published' => 1 ]); + return $query; } } @@ -1337,7 +1339,7 @@ and make sure our web service is returning the proper response:: class MarkersControllerTest extends IntegrationTestCase { use IntegrationTestTrait; - + public function testGet(): void { $this->configRequest([ @@ -1921,6 +1923,7 @@ Expanding on the Orders example, say we have the following tables:: 'order' => $order ]); $this->getEventManager()->dispatch($event); + return true; } return false; diff --git a/en/installation.rst b/en/installation.rst index 135af3ed48..73b7ec3c0b 100644 --- a/en/installation.rst +++ b/en/installation.rst @@ -449,6 +449,7 @@ A sample of the server directive is as follows: listen 80; listen [::]:80; server_name www.example.com; + return 301 http://example.com$request_uri; } diff --git a/en/orm/behaviors.rst b/en/orm/behaviors.rst index bb92422048..35d254aebb 100644 --- a/en/orm/behaviors.rst +++ b/en/orm/behaviors.rst @@ -189,6 +189,7 @@ To prevent the save from continuing, simply stop event propagation in your callb if (...) { $event->stopPropagation(); $event->setResult(false); + return; } $this->slug($entity); diff --git a/en/orm/behaviors/tree.rst b/en/orm/behaviors/tree.rst index 1bf79ae012..34f69c53db 100644 --- a/en/orm/behaviors/tree.rst +++ b/en/orm/behaviors/tree.rst @@ -98,14 +98,14 @@ in a hierarchy, you can stack the 'threaded' finder:: } While, if you’re using custom ``parent_id`` you need to pass it in the -'threaded' finder option (i.e. ``parentField``) . +'threaded' finder option (i.e. ``parentField``) . .. note:: For more information on 'threaded' finder options see :ref:`Finding Threaded Data logic ` Getting formatted tree lists ---------------------------- - + Traversing threaded results usually requires recursive functions in, but if you only require a result set containing a single field from each level so you can display a list, in an HTML select for example, it is better to use the @@ -246,6 +246,7 @@ as the scope:: $this->behaviors()->Tree->setConfig('scope', function ($query) { $country = $this->getConfigureContry(); // A made-up function + return $query->where(['country_name' => $country]); }); @@ -335,7 +336,7 @@ conditional deletes:: } TreeBehavior will reorder the ``lft`` and ``rght`` values of records in the -table when a node is deleted. +table when a node is deleted. In our example above, the ``lft`` and ``rght`` values of the entities inside ``$descendants`` will be inaccurate. You will need to reload existing entity diff --git a/en/orm/query-builder.rst b/en/orm/query-builder.rst index f90c5c436f..5e88b52be4 100644 --- a/en/orm/query-builder.rst +++ b/en/orm/query-builder.rst @@ -169,7 +169,8 @@ implement the collection interface:: ->all() ->map(function ($row) { $row->trimmedTitle = trim($row->title); - return $row; + + return $row; }) ->combine('id', 'trimmedTitle') // combine() is another collection method ->toArray(); // Also a collections library method @@ -699,6 +700,7 @@ of people, you could calculate their age with a result formatter:: $query->formatResults(function (\Cake\Collection\CollectionInterface $results) { return $results->map(function ($row) { $row['age'] = $row['birth_date']->diff(new \DateTime)->y; + return $row; }); }); @@ -720,6 +722,7 @@ expect:: return $q->formatResults(function (\Cake\Collection\CollectionInterface $authors) { return $authors->map(function ($author) { $author['age'] = $author['birth_date']->diff(new \DateTime)->y; + return $author; }); }); @@ -834,6 +837,7 @@ following:: ->where(function (QueryExpression $exp) { $orConditions = $exp->or(['author_id' => 2]) ->eq('author_id', 5); + return $exp ->add($orConditions) ->eq('published', true) @@ -862,6 +866,7 @@ the method chaining:: return $or->eq('author_id', 2) ->eq('author_id', 5); }); + return $exp ->not($orConditions) ->lte('view_count', 10); @@ -873,6 +878,7 @@ You can negate sub-expressions using ``not()``:: ->where(function (QueryExpression $exp) { $orConditions = $exp->or(['author_id' => 2]) ->eq('author_id', 5); + return $exp ->not($orConditions) ->lte('view_count', 10); @@ -896,6 +902,7 @@ It is also possible to build expressions using SQL functions:: $year = $q->func()->year([ 'created' => 'identifier' ]); + return $exp ->gte($year, 2014) ->eq('published', true); @@ -1224,6 +1231,7 @@ And can be used combined with aggregations too:: $query->newExpr(['Stocks.quantity', 'Products.unit_price']) ->setConjunction('*') ); + return [ 'Products.name', 'stock_quantity' => $stockQuantity, diff --git a/en/orm/retrieving-data-and-resultsets.rst b/en/orm/retrieving-data-and-resultsets.rst index 16abab7b70..23a34090b9 100644 --- a/en/orm/retrieving-data-and-resultsets.rst +++ b/en/orm/retrieving-data-and-resultsets.rst @@ -77,7 +77,7 @@ by using the ``finder`` option:: $article = $articles->get($id, [ 'finder' => 'translations', ]); - + The list of options supported by get() are: - ``cache`` cache config. @@ -389,6 +389,7 @@ given user, we would do the following:: public function findOwnedBy(Query $query, array $options) { $user = $options['user']; + return $query->where(['author_id' => $user->id]); } } @@ -1071,8 +1072,8 @@ can load additional associations using ``loadInto()``:: $articles = $this->Articles->find()->all(); $withMore = $this->Articles->loadInto($articles, ['Comments', 'Users']); -It is possible to restrict the data returned by the associations and filter them -by conditions. To specify conditions, pass an anonymous function that receives +It is possible to restrict the data returned by the associations and filter them +by conditions. To specify conditions, pass an anonymous function that receives as the first argument a query object, ``\Cake\ORM\Query``:: $user = $this->Users->get($id); @@ -1288,6 +1289,7 @@ This is particularly useful for building custom finder methods as described in t // Same as in the common words example in the previous section $mapper = ...; $reducer = ...; + return $query->mapReduce($mapper, $reducer); } diff --git a/en/orm/table-objects.rst b/en/orm/table-objects.rst index 00c7d71e62..60da80f7d8 100644 --- a/en/orm/table-objects.rst +++ b/en/orm/table-objects.rst @@ -135,20 +135,20 @@ more detail on how to use the events subsystem:: // In a controller $articles->save($article, ['customVariable1' => 'yourValue1']); - + // In ArticlesTable.php public function afterSave(Event $event, EntityInterface $entity, ArrayObject $options) { $customVariable = $options['customVariable1']; // 'yourValue1' - $options['customVariable2'] = 'yourValue2'; - } - + $options['customVariable2'] = 'yourValue2'; + } + public function afterSaveCommit(Event $event, EntityInterface $entity, ArrayObject $options) { $customVariable = $options['customVariable1']; // 'yourValue1' $customVariable = $options['customVariable2']; // 'yourValue2' } - + Event List ---------- @@ -357,6 +357,7 @@ To prevent the save from continuing, simply stop event propagation in your callb if (...) { $event->stopPropagation(); $event->setResult(false); + return; } ... diff --git a/en/orm/validation.rst b/en/orm/validation.rst index a3693a0e02..23fcbc81cb 100644 --- a/en/orm/validation.rst +++ b/en/orm/validation.rst @@ -112,6 +112,7 @@ used. An example validator for our articles table would be:: $validator ->notEmptyString('title', __('You need to provide a title')) ->notEmptyString('body', __('A body is required')); + return $validator; } } @@ -173,6 +174,7 @@ construction process into multiple reusable steps:: $validator = $this->validationDefault($validator); $validator->add('password', 'length', ['rule' => ['lengthBetween', 8, 100]]); + return $validator; } @@ -207,6 +209,7 @@ a validation rule:: 'message' => __('You need to provide a valid role'), 'provider' => 'table', ]); + return $validator; } @@ -548,6 +551,7 @@ You may want to re-use custom domain rules. You can do so by creating your own i 'errorField' => 'name', 'message' => 'Name must be unique per parent.' ]); + return $rules; } @@ -571,6 +575,7 @@ those rules into re-usable classes:: public function __invoke(EntityInterface $entity, array $options) { // Do work + return false; } } diff --git a/en/security/csrf.rst b/en/security/csrf.rst index 02d9fcae21..fe707035ee 100644 --- a/en/security/csrf.rst +++ b/en/security/csrf.rst @@ -48,6 +48,7 @@ stack you protect all the actions in application:: $csrf = new SessionCsrfProtectionMiddleware($options); $middlewareQueue->add($csrf); + return $middlewareQueue; } @@ -83,8 +84,8 @@ The available configuration options are: will fail. Defaults to ``false``. - ``httponly`` Whether or not the cookie will be set with the HttpOnly flag. Defaults to ``false``. Prior to 4.1.0 use the ``httpOnly`` option. -- ``samesite`` Allows you to declare if your cookie should be restricted to a - first-party or same-site context. Possible values are ``Lax``, ``Strict`` and +- ``samesite`` Allows you to declare if your cookie should be restricted to a + first-party or same-site context. Possible values are ``Lax``, ``Strict`` and ``None``. Defaults to ``null``. - ``field`` The form field to check. Defaults to ``_csrfToken``. Changing this will also require configuring FormHelper. diff --git a/en/tutorials-and-examples/blog-auth-example/auth.rst b/en/tutorials-and-examples/blog-auth-example/auth.rst index ae76498dea..c0335cf033 100644 --- a/en/tutorials-and-examples/blog-auth-example/auth.rst +++ b/en/tutorials-and-examples/blog-auth-example/auth.rst @@ -95,6 +95,7 @@ utilities bundled with CakePHP:: $user = $this->Users->patchEntity($user, $this->request->getData()); if ($this->Users->save($user)) { $this->Flash->success(__('The user has been saved.')); + return $this->redirect(['action' => 'add']); } $this->Flash->error(__('Unable to add the user.')); @@ -359,6 +360,7 @@ Add the logout action to the ``UsersController`` class:: // regardless of POST or GET, redirect if user is logged in if ($result->isValid()) { $this->Authentication->logout(); + return $this->redirect(['controller' => 'Users', 'action' => 'login']); } } diff --git a/en/tutorials-and-examples/blog/part-three.rst b/en/tutorials-and-examples/blog/part-three.rst index b40a02c8ad..35ed4fb85e 100644 --- a/en/tutorials-and-examples/blog/part-three.rst +++ b/en/tutorials-and-examples/blog/part-three.rst @@ -351,6 +351,7 @@ it:: $article = $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been saved.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to add your article.')); diff --git a/en/tutorials-and-examples/blog/part-two.rst b/en/tutorials-and-examples/blog/part-two.rst index 150846a883..d7c39ac6c3 100644 --- a/en/tutorials-and-examples/blog/part-two.rst +++ b/en/tutorials-and-examples/blog/part-two.rst @@ -296,6 +296,7 @@ First, start by creating an ``add()`` action in the $article = $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been saved.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to add your article.')); @@ -459,6 +460,7 @@ like:: $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been updated.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to update your article.')); @@ -549,6 +551,7 @@ Next, let's make a way for users to delete articles. Start with a $article = $this->Articles->get($id); if ($this->Articles->delete($article)) { $this->Flash->success(__('The article with id: {0} has been deleted.', h($id))); + return $this->redirect(['action' => 'index']); } } diff --git a/en/tutorials-and-examples/bookmarks/intro.rst b/en/tutorials-and-examples/bookmarks/intro.rst index 080071d5a1..707be8fdff 100644 --- a/en/tutorials-and-examples/bookmarks/intro.rst +++ b/en/tutorials-and-examples/bookmarks/intro.rst @@ -289,6 +289,7 @@ add the following:: protected function _setPassword($value) { $hasher = new DefaultPasswordHasher(); + return $hasher->hash($value); } } diff --git a/en/tutorials-and-examples/bookmarks/part-two.rst b/en/tutorials-and-examples/bookmarks/part-two.rst index f2927f12e7..c66f6f77a3 100644 --- a/en/tutorials-and-examples/bookmarks/part-two.rst +++ b/en/tutorials-and-examples/bookmarks/part-two.rst @@ -63,6 +63,7 @@ not written that code yet. So let's create the login action:: $user = $this->Auth->identify(); if ($user) { $this->Auth->setUser($user); + return $this->redirect($this->Auth->redirectUrl()); } $this->Flash->error('Your username or password is incorrect.'); @@ -102,6 +103,7 @@ well. Again, in the ``UsersController``, add the following code:: public function logout() { $this->Flash->success('You are now logged out.'); + return $this->redirect($this->Auth->logout()); } @@ -234,6 +236,7 @@ like:: $bookmark->user_id = $this->Auth->user('id'); if ($this->Bookmarks->save($bookmark)) { $this->Flash->success('The bookmark has been saved.'); + return $this->redirect(['action' => 'index']); } $this->Flash->error('The bookmark could not be saved. Please, try again.'); @@ -258,6 +261,7 @@ edit form and action. Your ``edit()`` action from $bookmark->user_id = $this->Auth->user('id'); if ($this->Bookmarks->save($bookmark)) { $this->Flash->success('The bookmark has been saved.'); + return $this->redirect(['action' => 'index']); } $this->Flash->error('The bookmark could not be saved. Please, try again.'); @@ -317,6 +321,7 @@ can add a virtual/computed field to the entity. In $str = $tags->reduce(function ($string, $tag) { return $string . $tag->title . ', '; }, ''); + return trim($str, ', '); } diff --git a/en/tutorials-and-examples/cms/articles-controller.rst b/en/tutorials-and-examples/cms/articles-controller.rst index 8e7a9f012e..696df0f90c 100644 --- a/en/tutorials-and-examples/cms/articles-controller.rst +++ b/en/tutorials-and-examples/cms/articles-controller.rst @@ -212,6 +212,7 @@ to be created. Start by creating an ``add()`` action in the if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been saved.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to add your article.')); @@ -356,6 +357,7 @@ now. Add the following action to your ``ArticlesController``:: $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been updated.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to update your article.')); @@ -488,6 +490,7 @@ Next, let's make a way for users to delete articles. Start with a $article = $this->Articles->findBySlug($slug)->firstOrFail(); if ($this->Articles->delete($article)) { $this->Flash->success(__('The {0} article has been deleted.', $article->title)); + return $this->redirect(['action' => 'index']); } } diff --git a/en/tutorials-and-examples/cms/authentication.rst b/en/tutorials-and-examples/cms/authentication.rst index 6df7acb93b..ef67f67811 100644 --- a/en/tutorials-and-examples/cms/authentication.rst +++ b/en/tutorials-and-examples/cms/authentication.rst @@ -195,7 +195,7 @@ If you visit your site, you'll get an "infinite redirect loop" so let's fix that If your application serves from both SSL and non-SSL protocols, then you might have problems with sessions being lost, in case your application is on non-SSL protocol. You need to enable - access by setting session.cookie_secure to false in your config config/app.php or config/app_local.php. + access by setting session.cookie_secure to false in your config config/app.php or config/app_local.php. (See :doc:`CakePHP’s defaults on session.cookie_secure `) In your ``UsersController``, add the following code:: @@ -289,6 +289,7 @@ Add the logout action to the ``UsersController`` class:: // regardless of POST or GET, redirect if user is logged in if ($result && $result->isValid()) { $this->Authentication->logout(); + return $this->redirect(['controller' => 'Users', 'action' => 'login']); } } diff --git a/en/tutorials-and-examples/cms/authorization.rst b/en/tutorials-and-examples/cms/authorization.rst index 4e97fa729e..5e24fc2283 100644 --- a/en/tutorials-and-examples/cms/authorization.rst +++ b/en/tutorials-and-examples/cms/authorization.rst @@ -201,6 +201,7 @@ logged in user. Replace your add action with the following:: if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been saved.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to add your article.')); @@ -228,6 +229,7 @@ Next we'll update the ``edit`` action. Replace the edit method with the followin ]); if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been updated.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to update your article.')); diff --git a/en/tutorials-and-examples/cms/tags-and-users.rst b/en/tutorials-and-examples/cms/tags-and-users.rst index d64ff548a0..c32bae7067 100644 --- a/en/tutorials-and-examples/cms/tags-and-users.rst +++ b/en/tutorials-and-examples/cms/tags-and-users.rst @@ -85,6 +85,7 @@ articles. First, update the ``add`` action to look like:: if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been saved.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to add your article.')); @@ -125,6 +126,7 @@ edit method should now look like:: $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been updated.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to update your article.')); @@ -355,6 +357,7 @@ can add a virtual/computed field to the entity. In $str = $tags->reduce(function ($string, $tag) { return $string . $tag->title . ', '; }, ''); + return trim($str, ', '); } diff --git a/en/views/helpers/breadcrumbs.rst b/en/views/helpers/breadcrumbs.rst index 00643491b8..8708209c8a 100644 --- a/en/views/helpers/breadcrumbs.rst +++ b/en/views/helpers/breadcrumbs.rst @@ -186,6 +186,7 @@ when you want to transform the crumbs and overwrite the list:: $crumbs = $this->Breadcrumbs->getCrumbs(); $crumbs = collection($crumbs)->map(function ($crumb) { $crumb['options']['class'] = 'breadcrumb-item'; + return $crumb; })->toArray(); diff --git a/en/views/helpers/form.rst b/en/views/helpers/form.rst index 4e9078bf9b..a26114127b 100644 --- a/en/views/helpers/form.rst +++ b/en/views/helpers/form.rst @@ -661,10 +661,10 @@ as well as HTML attributes. This subsection will cover the options specific to As seen above you can set the error message for each validation rule you have in your models. In addition you can provide i18n messages for your forms. - + To disable the HTML entity encoding for error messages only, the ``'escape'`` sub key can be used:: - + $this->Form->control('name', [ 'error' => ['escape' => false], ]); @@ -2507,6 +2507,7 @@ could do the following:: $data += [ 'name' => '', ]; + return $this->_templates->format('autocomplete', [ 'name' => $data['name'], 'attrs' => $this->_templates->formatAttributes($data, ['name']) diff --git a/es/controllers/components.rst b/es/controllers/components.rst index 6f3a53ada1..1e7ad992f3 100644 --- a/es/controllers/components.rst +++ b/es/controllers/components.rst @@ -2,14 +2,14 @@ Componentes ########### Los componentes son paquetes de lógica que se comparten entre los controladores. -CakePHP viene un con fantástico conjunto de componentes básicos que puedes usar +CakePHP viene un con fantástico conjunto de componentes básicos que puedes usar para ayudar en varias tareas comunes. También puedes crear tus propios componentes. Si te encuentras queriendo copiar y pegar cosas entre componentes, deberías considerar crear tu propio componente que contenga la funcionalidad. Crear componentes mantiene el código del controlador limpio y te permite rehusar código entre los diferentes controladores. -Para más información sobre componentes incluidos en CakePHP, consulte el capítulo +Para más información sobre componentes incluidos en CakePHP, consulte el capítulo de cada componente: .. toctree:: @@ -28,9 +28,9 @@ de cada componente: Configurando componentes ======================== -Muchos de los componentes principales requieren configuración. Algunos ejemplos +Muchos de los componentes principales requieren configuración. Algunos ejemplos de componentes que requieren configuración son :doc:`/controllers/components/security` -y :doc:`/controllers/components/form-protection`. La configuración para estos +y :doc:`/controllers/components/form-protection`. La configuración para estos componentes, y para los componentes en general, es usualmente hecho a través ``loadComponent()`` en el método ``initialize()`` del controlador o a través del array ``$components``:: @@ -105,7 +105,7 @@ Carga de componentes sobre la marcha ------------------------------------ Es posible que no necesites todos tus componentes disponibles en cada acción del -controlador. En situaciones como estas, puedes cargar un componente en tiempo de +controlador. En situaciones como estas, puedes cargar un componente en tiempo de ejecución usando el método ``loadComponent()`` en tu controlador:: // En una acción del controlador @@ -115,7 +115,7 @@ ejecución usando el método ``loadComponent()`` en tu controlador:: .. note:: Ten en cuenta que los componentes cargados sobre la marcha no perderán devoluciones - de llamadas. Si te basas en que las devoluciones de llamada ``beforeFilter`` o + de llamadas. Si te basas en que las devoluciones de llamada ``beforeFilter`` o ``startup`` serán llamadas, necesitarás llamarlas manualmente dependiendo de cuándo cargas tu componente. @@ -123,7 +123,7 @@ Uso de componentes ================== Una vez que hayas incluido algunos componentes a tu controlador, usarlos es bastante -simple. Cada componente que uses se exponen como una propiedad en tu controlador. +simple. Cada componente que uses se exponen como una propiedad en tu controlador. Si cargaste el :php:class:`Cake\\Controller\\Component\\FlashComponent` en tu controlador, puedes acceder a él de esta forma:: @@ -139,6 +139,7 @@ puedes acceder a él de esta forma:: { if ($this->Post->delete($this->request->getData('Post.id')) { $this->Flash->success('Post deleted.'); + return $this->redirect(['action' => 'index']); } } @@ -159,7 +160,7 @@ Supongamos que nuestra aplicación necesita realizar una operación matemática en muchas partes diferentes de la aplicación. Podríamos crear un componente para albergar esta lógica compartida para su uso en muchos controladores diferentes. -El primer paso es crear un nuevo archivo de componente y clase. Crea el archivo en +El primer paso es crear un nuevo archivo de componente y clase. Crea el archivo en **src/Controller/Component/MathComponent.php**. La estructura básica para el componente debería verse algo como esto:: @@ -184,8 +185,8 @@ Incluyendo tu componente en tus controladores --------------------------------------------- Una vez que nuestro componente está terminado, podemos usarlo en los controladores -de la aplicación cargándolo durante el método ``initialize()`` del controlador. -Una vez cargado, el controlador recibirá un nuevo atributo con el nombre del +de la aplicación cargándolo durante el método ``initialize()`` del controlador. +Una vez cargado, el controlador recibirá un nuevo atributo con el nombre del componente, a través del cual podemos acceder a una instancia del mismo:: // En un controlador @@ -198,7 +199,7 @@ componente, a través del cual podemos acceder a una instancia del mismo:: $this->loadComponent('Csrf'); } -Al incluir componentes en un controlador, también puedes declarar un conjunto de +Al incluir componentes en un controlador, también puedes declarar un conjunto de parámetros que se pasarán al constructor del componente. Estos parámetros pueden ser manejados por el componente:: @@ -213,7 +214,7 @@ ser manejados por el componente:: $this->loadComponent('Csrf'); } -Lo anterior pasaría el array que contiene precision y randomGenerator a ``MathComponent::initialize()`` +Lo anterior pasaría el array que contiene precision y randomGenerator a ``MathComponent::initialize()`` en el parámetro ``$config``. Usando otros componentes en tu componente @@ -259,13 +260,13 @@ componentes agregándolos a la propiedad `$components`:: .. note:: - A diferencia de un componente incluido en un controlador, no se activarán + A diferencia de un componente incluido en un controlador, no se activarán devoluciones de llamada en el componente de un componente. Accediendo al controlador de un componente ------------------------------------------ -Desde dentro de un componente, puedes acceder al controlador actual a través del +Desde dentro de un componente, puedes acceder al controlador actual a través del registro:: $controller = $this->getController(); @@ -288,7 +289,7 @@ de las solicitudes que les permiten aumentar el ciclo de solicitud. .. php:method:: beforeRender(EventInterface $event) - Es llamado después de que el controlador ejecute la lógica de la acción + Es llamado después de que el controlador ejecute la lógica de la acción solicitada, pero antes de que el controlador renderize las vistas y el diseño. .. php:method:: shutdown(EventInterface $event) @@ -313,6 +314,7 @@ puedes usar lo siguiente:: public function beforeFilter(EventInterface $event) { $event->stopPropagation(); + return $this->getController()->redirect('/'); } diff --git a/es/orm/behaviors/tree.rst b/es/orm/behaviors/tree.rst index 37f97c62cb..45352a1ff0 100644 --- a/es/orm/behaviors/tree.rst +++ b/es/orm/behaviors/tree.rst @@ -172,6 +172,7 @@ Opcionalmente, puede ejercer un control más riguroso pasando una clausura como $this->behaviors()->Tree->config('scope', function ($query) { $country = $this->getConfigureContry(); // A made-up function + return $query->where(['country_name' => $country]); }); diff --git a/es/tutorials-and-examples/blog-auth-example/auth.rst b/es/tutorials-and-examples/blog-auth-example/auth.rst index 36f13b78da..162b99617e 100644 --- a/es/tutorials-and-examples/blog-auth-example/auth.rst +++ b/es/tutorials-and-examples/blog-auth-example/auth.rst @@ -87,6 +87,7 @@ También vamos a crear UsersController; el siguiente contenido fue generado usan $user = $this->Users->patchEntity($user, $this->request->getData()); if ($this->Users->save($user)) { $this->Flash->success(__('The user has been saved.')); + return $this->redirect(['action' => 'add']); } $this->Flash->error(__('Unable to add the user.')); @@ -181,6 +182,7 @@ Ahora necesitamos poder registrar nuevos usuarios, guardar el nombre de usuario $user = $this->Auth->identify(); if ($user) { $this->Auth->setUser($user); + return $this->redirect($this->Auth->redirectUrl()); } $this->Flash->error(__('Invalid email or password, try again')); @@ -270,6 +272,7 @@ También, un pequeño cambio en ArticlesController es necesario para guardar el //$article = $this->Articles->patchEntity($article, $newData); if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been saved.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to add your article.')); diff --git a/es/tutorials-and-examples/blog/part-three.rst b/es/tutorials-and-examples/blog/part-three.rst index efa66b9c09..bfd543021f 100644 --- a/es/tutorials-and-examples/blog/part-three.rst +++ b/es/tutorials-and-examples/blog/part-three.rst @@ -246,6 +246,7 @@ Esto nos permitirá elegir una categoría para un Article al momento de crearlo $article = $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been saved.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to add your article.')); diff --git a/es/tutorials-and-examples/blog/part-two.rst b/es/tutorials-and-examples/blog/part-two.rst index e96344b767..d627bde3d0 100644 --- a/es/tutorials-and-examples/blog/part-two.rst +++ b/es/tutorials-and-examples/blog/part-two.rst @@ -269,6 +269,7 @@ ArticlesController:: $article = $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been saved.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to add your article.')); @@ -424,6 +425,7 @@ ser la acción ``edit()`` del controlador ``ArticlesController``:: $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Tu artículo ha sido actualizado.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Tu artículo no se ha podido actualizar.')); @@ -512,6 +514,7 @@ Vamos a permitir a los usuarios que borren artículos. Empieza con una acción $article = $this->Articles->get($id); if ($this->Articles->delete($article)) { $this->Flash->success(__('El artículo con id: {0} ha sido eliminado.', h($id))); + return $this->redirect(['action' => 'index']); } } diff --git a/es/tutorials-and-examples/bookmarks/intro.rst b/es/tutorials-and-examples/bookmarks/intro.rst index 12c308a159..df0f9c4cc2 100644 --- a/es/tutorials-and-examples/bookmarks/intro.rst +++ b/es/tutorials-and-examples/bookmarks/intro.rst @@ -222,6 +222,7 @@ Añadamos un setter para la contraseña añadiendo el siguiente código en **src protected function _setPassword($value) { $hasher = new DefaultPasswordHasher(); + return $hasher->hash($value); } } diff --git a/es/tutorials-and-examples/bookmarks/part-two.rst b/es/tutorials-and-examples/bookmarks/part-two.rst index dad36a097d..39ea6aa1b2 100644 --- a/es/tutorials-and-examples/bookmarks/part-two.rst +++ b/es/tutorials-and-examples/bookmarks/part-two.rst @@ -71,6 +71,7 @@ así que hagámoslo ahora:: $user = $this->Auth->identify(); if ($user) { $this->Auth->setUser($user); + return $this->redirect($this->Auth->redirectUrl()); } $this->Flash->error('Tu usuario o contraseña es incorrecta.'); @@ -115,6 +116,7 @@ Otra vez en ``UsersController``, añade el siguiente código:: public function logout() { $this->Flash->success('Ahora estás deslogueado.'); + return $this->redirect($this->Auth->logout()); } @@ -261,6 +263,7 @@ Con esa parte eliminada actualizaremos la acción ``add()`` de $bookmark->user_id = $this->Auth->user('id'); if ($this->Bookmarks->save($bookmark)) { $this->Flash->success('El favorito se ha guardado.'); + return $this->redirect(['action' => 'index']); } $this->Flash->error('El favorito podría no haberse guardado. Por favor, inténtalo de nuevo.'); @@ -287,6 +290,7 @@ así:: $bookmark->user_id = $this->Auth->user('id'); if ($this->Bookmarks->save($bookmark)) { $this->Flash->success('El favorito se ha guardado.'); + return $this->redirect(['action' => 'index']); } $this->Flash->error('El favorito podría no haberse guardado. Por favor, inténtalo de nuevo.'); @@ -350,6 +354,7 @@ En **src/Model/Entity/Bookmark.php** añade lo siguiente:: $str = $tags->reduce(function ($string, $tag) { return $string . $tag->title . ', '; }, ''); + return trim($str, ', '); } diff --git a/fr/console-commands/commands.rst b/fr/console-commands/commands.rst index 6a4f6bf5e4..8aabe80962 100644 --- a/fr/console-commands/commands.rst +++ b/fr/console-commands/commands.rst @@ -27,7 +27,7 @@ Hello world toute simple. Dans le répertoire **src/Command** de votre applicati public function execute(Arguments $args, ConsoleIo $io): int { $io->out('Hello world.'); - + return static::CODE_SUCCESS; } } @@ -61,6 +61,7 @@ Notre méthode ``execute()`` n'est pas très intéressente, ajoutons des entrée $parser->addArgument('name', [ 'help' => 'Quel est votre nom' ]); + return $parser; } @@ -68,7 +69,7 @@ Notre méthode ``execute()`` n'est pas très intéressente, ajoutons des entrée { $name = $args->getArgument('name'); $io->out("Hello {$name}."); - + return static::CODE_SUCCESS; } } @@ -82,7 +83,7 @@ Après avoir sauvegardé ce fichier, vous devriez pouvoir exécuter la commande # Affiche Hello jillian - + Changer le Nom Par Défaut de la Commande ======================================== @@ -127,7 +128,7 @@ pour définir des arguments. Nous pouvons aussi définir des options. Par exempl $name = mb_strtoupper($name); } $io->out("Hello {$name}."); - + return static::CODE_SUCCESS; } @@ -216,7 +217,7 @@ message et un code:: // Arrête l'exécution, affiche vers stderr, et définit le code de sortie à 99 $io->abort('Le nom doit avoir au moins 4 caractères.', 99); } - + return static::CODE_SUCCESS; } @@ -337,7 +338,7 @@ moment, mais testons simplement si la description de notre shell description s'a use Cake\TestSuite\ConsoleIntegrationTestTrait; use Cake\TestSuite\TestCase; - + class UpdateTableCommandTest extends TestCase { user ConsoleIntegrationTestTrait; diff --git a/fr/console-commands/shells.rst b/fr/console-commands/shells.rst index 377fcb9b8a..0a674b3b00 100644 --- a/fr/console-commands/shells.rst +++ b/fr/console-commands/shells.rst @@ -146,12 +146,14 @@ Also, the task name must be added as a sub-command to the Shell's OptionParser:: public function getOptionParser() { $parser = parent::getOptionParser(); + $parser->addSubcommand('sound', [ // Provide help text for the command list 'help' => 'Execute The Sound Task.', // Link the option parsers together. 'parser' => $this->Sound->getOptionParser(), ]); + return $parser; } diff --git a/fr/controllers/components.rst b/fr/controllers/components.rst index edc9ac99a6..9019773047 100644 --- a/fr/controllers/components.rst +++ b/fr/controllers/components.rst @@ -144,6 +144,7 @@ vous pouvez y accéder comme ceci:: { if ($this->Post->delete($this->request->getData('Post.id')) { $this->Flash->success('Publication effacée.'); + return $this->redirect(['action' => 'index']); } } @@ -324,6 +325,7 @@ Pour rediriger à partir d'une méthode de rappel de composant, vous pouvez util public function beforeFilter(EventInterface $event) { $event->stopPropagation(); + return $this->getController()->redirect('/'); } diff --git a/fr/controllers/components/authentication.rst b/fr/controllers/components/authentication.rst index bdb1669608..2e06f0d3fb 100644 --- a/fr/controllers/components/authentication.rst +++ b/fr/controllers/components/authentication.rst @@ -247,6 +247,7 @@ connexion pourrait ressembler à cela:: $user = $this->Auth->identify(); if ($user) { $this->Auth->setUser($user); + return $this->redirect($this->Auth->redirectUrl()); } else { $this->Flash->error(__("Nom d'utilisateur ou mot de passe incorrect")); @@ -476,6 +477,7 @@ colonne séparée du mot de passe standard hashé:: $entity->plain_password, env('SERVER_NAME') ); + return true; } } @@ -773,6 +775,7 @@ utilisateur que vous voulez pour la 'connexion':: $user = $this->Users->newEntity($this->request->getData()); if ($this->Users->save($user)) { $this->Auth->setUser($user->toArray()); + return $this->redirect([ 'controller' => 'Users', 'action' => 'home' diff --git a/fr/controllers/middleware.rst b/fr/controllers/middleware.rst index 2379eab71b..9934105355 100644 --- a/fr/controllers/middleware.rst +++ b/fr/controllers/middleware.rst @@ -88,6 +88,7 @@ pour en attacher :: { // Attache le gestionnaire d'erreur dans la file du middleware $middlewareQueue->add(new ErrorHandlerMiddleware()); + return $middlewareQueue; } } @@ -140,7 +141,7 @@ appliquer un de leurs middlewares dans la file de middlewares de l'application:: use Cake\Http\MiddlewareQueue; use ContactManager\Middleware\ContactManagerContextMiddleware; - + class Plugin extends BasePlugin { public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue diff --git a/fr/controllers/request-response.rst b/fr/controllers/request-response.rst index 57c605f269..44d3f6279c 100644 --- a/fr/controllers/request-response.rst +++ b/fr/controllers/request-response.rst @@ -712,6 +712,7 @@ Vous pouvez accomplir cela en utilisant :php:meth:`Cake\\Http\\Response::withFil { $file = $this->Attachments->getFile($id); $response = $this->response->withFile($file['path']); + // Renvoie la réponse pour empêcher le contrôleur d'essayer // de rendre une vue return $response; diff --git a/fr/core-libraries/caching.rst b/fr/core-libraries/caching.rst index 0600e705ce..297450ad5e 100644 --- a/fr/core-libraries/caching.rst +++ b/fr/core-libraries/caching.rst @@ -289,6 +289,7 @@ Par exemple:: // Stocke les données en cache Cache::write('cloud', $cloud); + return $cloud; Lire Plusieurs Clés d'un Coup diff --git a/fr/core-libraries/events.rst b/fr/core-libraries/events.rst index f132767986..d37f9b9e39 100644 --- a/fr/core-libraries/events.rst +++ b/fr/core-libraries/events.rst @@ -76,6 +76,7 @@ garder votre model Orders propre, vous pouvez utiliser les événements:: 'order' => $order ]); $this->getEventManager()->dispatch($event); + return true; } return false; @@ -493,6 +494,7 @@ callback elle-même:: { // ... $alteredData = $event->getData('order') + $moreData; + return $alteredData; } diff --git a/fr/core-libraries/hash.rst b/fr/core-libraries/hash.rst index 7f65d732b9..0c01b1cf31 100644 --- a/fr/core-libraries/hash.rst +++ b/fr/core-libraries/hash.rst @@ -641,6 +641,7 @@ Les Types d'Attribut Correspondants public function noop(array $array) { // Fait des choses au tableau et retourne les résultats + return $array; } diff --git a/fr/core-libraries/logging.rst b/fr/core-libraries/logging.rst index 924d6f748b..3a7197c0b0 100755 --- a/fr/core-libraries/logging.rst +++ b/fr/core-libraries/logging.rst @@ -499,6 +499,7 @@ utilisant la méthode ``Log::setConfig()``:: Log::setConfig('default', function () { $log = new Logger('app'); $log->pushHandler(new StreamHandler('path/to/your/combined.log')); + return $log; }); @@ -516,6 +517,7 @@ Utilisez des méthodes similaires pour configurer un logger différent pour la c Log::setConfig('default', function () { $log = new Logger('cli'); $log->pushHandler(new StreamHandler('path/to/your/combined-cli.log')); + return $log; }); diff --git a/fr/development/sessions.rst b/fr/development/sessions.rst index 2d64801872..a4e80e930f 100644 --- a/fr/development/sessions.rst +++ b/fr/development/sessions.rst @@ -287,6 +287,7 @@ devrait ressembler à:: public function write($id, $data) { Cache::write($id, $data, $this->cacheKey); + return parent::write($id, $data); } @@ -294,6 +295,7 @@ devrait ressembler à:: public function destroy($id) { Cache::delete($id, $this->cacheKey); + return parent::destroy($id); } diff --git a/fr/development/testing.rst b/fr/development/testing.rst index 3b90417638..ead8e15dda 100755 --- a/fr/development/testing.rst +++ b/fr/development/testing.rst @@ -155,6 +155,7 @@ barre de progression HTML. Notre helper ressemblera à cela:: public function bar($value) { $width = round($value / 100, 2) * 100; + return sprintf( '
@@ -864,6 +865,7 @@ Supposons que nous avons déjà notre table Articles définie dans $query->where([ $this->alias() . '.published' => 1 ]); + return $query; } } @@ -1326,7 +1328,7 @@ service web. Commençons avec un exemple simple de controller qui renvoie du JSON:: use Cake\View\JsonView; - + class MarkersController extends AppController { public function viewClasses(): array @@ -1607,7 +1609,7 @@ d'assertions afin de tester les réponses plus simplement. Quelques exemples:: $this->assertResponseEmpty(); // Vérifie le contenu de la réponse - $this->assertResponseEquals('Ouais !'); + $this->assertResponseEquals('Ouais !'); // Vérifie que le contenu de la réponse n'est pas égal à... $this->assertResponseNotEquals('Non !'); @@ -1721,7 +1723,7 @@ Mocker les Injections de Dépendances Voir :ref:`mocking-services-in-tests` pour savoir comment remplacer des services injectés avec le conteneur d'injection de dépendances dans vos tests d'intégration. - + Mocker les Réponses du Client HTTP ================================== @@ -1940,6 +1942,7 @@ suivantes:: 'order' => $order ]); $this->getEventManager()->dispatch($event); + return true; } return false; @@ -2015,7 +2018,7 @@ globaux:: Testing Email ============= - + Consultez :ref:`email-testing` pour savoir comment tester les emails. Créer des Suites de Test (Test Suites) diff --git a/fr/installation.rst b/fr/installation.rst index dba735f7ce..b57487b8c3 100644 --- a/fr/installation.rst +++ b/fr/installation.rst @@ -477,6 +477,7 @@ Un exemple de la directive server est le suivant: listen 80; listen [::]:80; server_name www.example.com; + return 301 http://example.com$request_uri; } diff --git a/fr/orm/behaviors.rst b/fr/orm/behaviors.rst index d720a1dd4f..075c68db18 100644 --- a/fr/orm/behaviors.rst +++ b/fr/orm/behaviors.rst @@ -195,6 +195,7 @@ de l'évènement dans votre callback:: { if (...) { $event->stopPropagation(); + return; } $this->slug($entity); diff --git a/fr/orm/behaviors/tree.rst b/fr/orm/behaviors/tree.rst index 4dcdc514ea..413012cc63 100644 --- a/fr/orm/behaviors/tree.rst +++ b/fr/orm/behaviors/tree.rst @@ -243,6 +243,7 @@ closure au scope:: $this->behaviors()->Tree->config('scope', function ($query) { $country = $this->getConfigureContry(); // A made-up function + return $query->where(['country_name' => $country]); }); diff --git a/fr/orm/query-builder.rst b/fr/orm/query-builder.rst index 4e44be3748..266e10abce 100644 --- a/fr/orm/query-builder.rst +++ b/fr/orm/query-builder.rst @@ -176,6 +176,7 @@ pouvez aussi le faire avec un objet Query:: ->order(['title' => 'DESC']) ->map(function ($row) { // map() est une méthode de collection, elle exécute la requête $row->trimmedTitle = trim($row->title); + return $row; }) ->combine('id', 'trimmedTitle') // combine() est une autre méthode de collection @@ -215,7 +216,7 @@ activer les :ref:`logs de requête `. Récupérer vos Données ===================== -CakePHP permet de construire simplement des requêtes ``SELECT``. La +CakePHP permet de construire simplement des requêtes ``SELECT``. La méthode ``select()`` vous permet de ne récupérer que les champs qui vous sont nécessaires:: @@ -730,6 +731,7 @@ formatter*):: $query->formatResults(function (\Cake\Collection\CollectionInterface $results) { return $results->map(function ($row) { $row['age'] = $row['date_de_naissance']->diff(new \DateTime)->y; + return $row; }); }); @@ -752,6 +754,7 @@ comme vous pouvez vous y attendre:: return $q->formatResults(function (\Cake\Collection\CollectionInterface $auteurs) { return $auteurs->map(function ($auteur) { $auteur['age'] = $auteur['date_de_naissance']->diff(new \DateTime)->y; + return $auteur; }); }); @@ -870,6 +873,7 @@ nous pouvons faire ceci:: ->where(function (QueryExpression $exp) { $orConditions = $exp->or(['auteur_id' => 2]) ->eq('auteur_id', 5); + return $exp ->add($orConditions) ->eq('published', true) @@ -898,6 +902,7 @@ chaînage des méthodes:: return $or->eq('auteur_id', 2) ->eq('auteur_id', 5); }); + return $exp ->not($orConditions) ->lte('nombre_de_vues', 10); @@ -909,6 +914,7 @@ Vous pouvez faire une négation des sous-expressions en utilisant ``not()``:: ->where(function (QueryExpression $exp) { $orConditions = $exp->or(['author_id' => 2]) ->eq('author_id', 5); + return $exp ->not($orConditions) ->lte('view_count', 10); @@ -933,6 +939,7 @@ SQL:: $year = $q->func()->year([ 'created' => 'identifier' ]); + return $exp ->gte($year, 2014) ->eq('published', true); diff --git a/fr/orm/retrieving-data-and-resultsets.rst b/fr/orm/retrieving-data-and-resultsets.rst index 5458c77395..4544dd9ff8 100644 --- a/fr/orm/retrieving-data-and-resultsets.rst +++ b/fr/orm/retrieving-data-and-resultsets.rst @@ -400,6 +400,7 @@ les articles d'un certain auteur, nous ferions ceci:: public function findEcritPar(Query $query, array $options) { $user = $options['user']; + return $query->where(['author_id' => $user->id]); } @@ -582,7 +583,7 @@ définir le second argument à ``true``:: $query = $articles->find(); $query->contain(['Authors', 'Comments'], true); - + .. note:: Les noms d'association dans les appels à ``contain()`` doivent respecter la @@ -801,7 +802,7 @@ l'association et charger d'autres champs de cette même association, vous pouvez parfaitement combiner ``innerJoinWith()`` et ``contain()``. L'exemple ci-dessous filtre les Articles qui ont des Tags spécifiques et charge ces Tags:: - + $filter = ['Tags.name' => 'CakePHP']; $query = $articles->find() ->distinct($articles->getPrimaryKey()) @@ -820,9 +821,9 @@ ces Tags:: $query ->select(['country_name' => 'Countries.name']) ->innerJoinWith('Countries'); - + Sinon, vous verrez les données dans ``_matchingData``, comme cela a été - décrit ci-dessous à propos de ``matching()``. C'est un angle mort de + décrit ci-dessous à propos de ``matching()``. C'est un angle mort de ``matching()``, qui ne sait pas que vous avez sélectionné des champs. .. warning:: @@ -949,7 +950,7 @@ exemple des tables se trouvant dans deux bases de données différentes. Habituellement, vous définisser la stratégie d'une association quand vous la définissez, dans la méthode ``Table::initialize()``, mais vous pouvez changer manuellement la stratégie de façon permanente:: - + $articles->Comments->setStrategy('select'); Récupération Avec la Stratégie de Sous-Requête @@ -1340,6 +1341,7 @@ comme décrit dans la section :ref:`custom-find-methods`:: // Comme dans l'exemple précédent sur la fréquence des mots $mapper = ...; $reducer = ...; + return $query->mapReduce($mapper, $reducer); } diff --git a/fr/orm/table-objects.rst b/fr/orm/table-objects.rst index 0600b5d7ab..b9933b109e 100644 --- a/fr/orm/table-objects.rst +++ b/fr/orm/table-objects.rst @@ -146,14 +146,14 @@ façon d'utiliser le sous-système d'events:: // Dans un controller $articles->save($article, ['variablePerso1' => 'votreValeur1']); - + // Dans ArticlesTable.php public function afterSave(Event $event, EntityInterface $entity, ArrayObject $options) { $variablePerso = $options['variablePerso1']; // 'votreValeur1' - $options['variablePerso2'] = 'votreValeur2'; - } - + $options['variablePerso2'] = 'votreValeur2'; + } + public function afterSaveCommit(Event $event, EntityInterface $entity, ArrayObject $options) { $variablePerso = $options['variablePerso1']; // 'votreValeur1' @@ -375,6 +375,7 @@ de l'event dans votre callback:: if (...) { $event->stopPropagation(); $event->setResult(false); + return; } ... diff --git a/fr/orm/validation.rst b/fr/orm/validation.rst index bff226fbdf..5db597f0e0 100644 --- a/fr/orm/validation.rst +++ b/fr/orm/validation.rst @@ -123,6 +123,7 @@ notre table ``articles``:: $validator ->notEmptyString('title', __('Vous devez indiquer un titre')) ->notEmptyString('body', __('Un contenu est nécessaire')); + return $validator; } } @@ -186,6 +187,7 @@ diviser leur process de construction en petites étapes réutilisables:: $validator = $this->validationDefault($validator); $validator->add('password', 'length', ['rule' => ['lengthBetween', 8, 100]]); + return $validator; } @@ -220,6 +222,7 @@ l'utiliser comme une règle de validation:: 'message' => __('Vous devez fournir un rôle valide'), 'provider' => 'table', ]); + return $validator; } @@ -583,6 +586,7 @@ le faire en créant votre propre règle invokable:: 'errorField' => 'name', 'message' => 'Doit être unique pour chaque parent.' ]); + return $rules; } @@ -607,6 +611,7 @@ utile de packager ces règles dans des classes réutilisables:: public function __invoke(EntityInterface $entity, array $options) { // Faire le boulot ici + return false; } } @@ -727,6 +732,7 @@ pour les transitions de données générées à l'intérieur de l'application:: 'errorField' => 'livraison', 'message' => 'Pas de frais de port gratuits pour une commande de moins de 100!' ]); + return $rules; } diff --git a/fr/security/csrf.rst b/fr/security/csrf.rst index c9110a502b..200b916db6 100644 --- a/fr/security/csrf.rst +++ b/fr/security/csrf.rst @@ -50,6 +50,7 @@ de votre Application, vous protégez toutes les actions de l'application:: $csrf = new SessionCsrfProtectionMiddleware($options); $middlewareQueue->add($csrf); + return $middlewareQueue; } diff --git a/fr/tutorials-and-examples/blog-auth-example/auth.rst b/fr/tutorials-and-examples/blog-auth-example/auth.rst index c866295469..c2aa207e4e 100755 --- a/fr/tutorials-and-examples/blog-auth-example/auth.rst +++ b/fr/tutorials-and-examples/blog-auth-example/auth.rst @@ -100,6 +100,7 @@ classe obtenue grâce à l'utilitaire de génération de code fourni par CakePHP $user = $this->Users->patchEntity($user, $this->request->getData()); if ($this->Users->save($user)) { $this->Flash->success(__("L'utilisateur a été sauvegardé.")); + return $this->redirect(['action' => 'add']); } $this->Flash->error(__("Impossible d'ajouter l\'utilisateur.")); @@ -378,6 +379,7 @@ Ajoutez l'action logout à votre classe ``UsersController``:: // Qu'on soit en POST ou en GET, rediriger l'utilisateur s'il est déjà connecté if ($result->isValid()) { $this->Authentication->logout(); + return $this->redirect(['controller' => 'Users', 'action' => 'login']); } } diff --git a/fr/tutorials-and-examples/blog/part-three.rst b/fr/tutorials-and-examples/blog/part-three.rst index 32bcf8e51f..4339fbee7a 100644 --- a/fr/tutorials-and-examples/blog/part-three.rst +++ b/fr/tutorials-and-examples/blog/part-three.rst @@ -364,6 +364,7 @@ lorsqu'on va le créer ou le modifier:: $article = $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Votre article a été enregistré.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__("Impossible d\'ajouter votre article.")); diff --git a/fr/tutorials-and-examples/blog/part-two.rst b/fr/tutorials-and-examples/blog/part-two.rst index 532bab5cc5..e0ce294da7 100755 --- a/fr/tutorials-and-examples/blog/part-two.rst +++ b/fr/tutorials-and-examples/blog/part-two.rst @@ -314,6 +314,7 @@ Premièrement, commençons par créer une action ``add()`` dans le $article = $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Votre article a été sauvegardé.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Impossible d\'ajouter votre article.')); @@ -487,6 +488,7 @@ devrait ressembler:: $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Votre article a été mis à jour.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Impossible de mettre à jour votre article.')); @@ -580,6 +582,7 @@ Articles (``ArticlesController``):: $article = $this->Articles->get($id); if ($this->Articles->delete($article)) { $this->Flash->success(__("L'article avec l'id: {0} a été supprimé.", h($id))); + return $this->redirect(['action' => 'index']); } } diff --git a/fr/tutorials-and-examples/bookmarks/intro.rst b/fr/tutorials-and-examples/bookmarks/intro.rst index 4684b86cfa..d9d2506690 100644 --- a/fr/tutorials-and-examples/bookmarks/intro.rst +++ b/fr/tutorials-and-examples/bookmarks/intro.rst @@ -272,6 +272,7 @@ dans une de vos entities. Ajoutons un setter pour le mot de passe. Dans protected function _setPassword($value) { $hasher = new DefaultPasswordHasher(); + return $hasher->hash($value); } } diff --git a/fr/tutorials-and-examples/bookmarks/part-two.rst b/fr/tutorials-and-examples/bookmarks/part-two.rst index 9a6fc1144a..2df600334c 100644 --- a/fr/tutorials-and-examples/bookmarks/part-two.rst +++ b/fr/tutorials-and-examples/bookmarks/part-two.rst @@ -69,6 +69,7 @@ nous n'avons pas encore écrit ce code. Créons donc l'action login:: $user = $this->Auth->identify(); if ($user) { $this->Auth->setUser($user); + return $this->redirect($this->Auth->redirectUrl()); } $this->Flash->error('Votre username ou mot de passe est incorrect.'); @@ -110,6 +111,7 @@ probablement fournir un moyen de se déconnecter. Encore une fois, dans public function logout() { $this->Flash->success('Vous êtes maintenant déconnecté.'); + return $this->redirect($this->Auth->logout()); } @@ -247,6 +249,7 @@ ressembler à ceci:: $bookmark->user_id = $this->Auth->user('id'); if ($this->Bookmarks->save($bookmark)) { $this->Flash->success('Le bookmark a été sauvegardé.'); + return $this->redirect(['action' => 'index']); } $this->Flash->error('Le bookmark ne peut être sauvegardé. Merci de réessayer.'); @@ -272,6 +275,7 @@ ceci:: $bookmark->user_id = $this->Auth->user('id'); if ($this->Bookmarks->save($bookmark)) { $this->Flash->success('Le bookmark a été sauvegardé.'); + return $this->redirect(['action' => 'index']); } else { $this->Flash->error('Le bookmark ne peut être sauvegardé. Merci de réessayer.'); @@ -335,6 +339,7 @@ pouvons ajouter un champ virtuel/calculé à l'entity. Dans $str = $tags->reduce(function ($string, $tag) { return $string . $tag->title . ', '; }, ''); + return trim($str, ', '); } diff --git a/fr/tutorials-and-examples/cms/articles-controller.rst b/fr/tutorials-and-examples/cms/articles-controller.rst index bddb19b1c2..f0ba714d51 100644 --- a/fr/tutorials-and-examples/cms/articles-controller.rst +++ b/fr/tutorials-and-examples/cms/articles-controller.rst @@ -217,6 +217,7 @@ la création d'articles. Commencez par créer une action ``add()`` dans le if ($this->Articles->save($article)) { $this->Flash->success(__('Votre article a été sauvegardé.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Impossible d\'ajouter votre article.')); @@ -367,6 +368,7 @@ dans votre ``ArticlesController``:: $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Votre article a été mis à jour.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Impossible de mettre à jour l\'article.')); @@ -501,6 +503,7 @@ Commencez par créer une action ``delete()`` dans ``ArticlesController``:: $article = $this->Articles->findBySlug($slug)->firstOrFail(); if ($this->Articles->delete($article)) { $this->Flash->success(__('L\'article {0} a été supprimé.', $article->title)); + return $this->redirect(['action' => 'index']); } } diff --git a/fr/tutorials-and-examples/cms/authentication.rst b/fr/tutorials-and-examples/cms/authentication.rst index 718120adda..0dcc55471c 100644 --- a/fr/tutorials-and-examples/cms/authentication.rst +++ b/fr/tutorials-and-examples/cms/authentication.rst @@ -288,6 +288,7 @@ Ajoutez l'action de logout à la classe ``UsersController``:: // indépendamment de POST ou GET, rediriger si l'utilisateur est connecté if ($result && $result->isValid()) { $this->Authentication->logout(); + return $this->redirect(['controller' => 'Users', 'action' => 'login']); } } diff --git a/fr/tutorials-and-examples/cms/authorization.rst b/fr/tutorials-and-examples/cms/authorization.rst index 9590f9b67e..7d2f0456ab 100644 --- a/fr/tutorials-and-examples/cms/authorization.rst +++ b/fr/tutorials-and-examples/cms/authorization.rst @@ -198,6 +198,7 @@ l'utilisateur actuellement authentifié. Remplacez l'action ``add`` par le code if ($this->Articles->save($article)) { $this->Flash->success(__('Votre article a été enregistré avec succès.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Impossible d\'ajouter votre article.')); @@ -225,6 +226,7 @@ Ensuite nous allons modifier l'action ``edit``. Remplacez la méthode d'édition ]); if ($this->Articles->save($article)) { $this->Flash->success(__('Votre article a été sauvegardé.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Impossible de mettre à jour votre article.')); diff --git a/fr/tutorials-and-examples/cms/tags-and-users.rst b/fr/tutorials-and-examples/cms/tags-and-users.rst index a4ad5c35f3..7eee133a5f 100644 --- a/fr/tutorials-and-examples/cms/tags-and-users.rst +++ b/fr/tutorials-and-examples/cms/tags-and-users.rst @@ -85,6 +85,7 @@ l'action ``add`` pour qu'elle ressemble à ceci:: if ($this->Articles->save($article)) { $this->Flash->success(__('Votre article a été sauvegardé.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Impossible de sauvegarder l\'article.')); @@ -127,6 +128,7 @@ maintenant ressembler à ceci:: $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Votre article a été modifié.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Impossible de mettre à jour votre article.')); @@ -360,6 +362,7 @@ entity, nous ajoutons un champ virtuel/pré-calculé pour l'entity. Dans $str = $tags->reduce(function ($string, $tag) { return $string . $tag->title . ', '; }, ''); + return trim($str, ', '); } diff --git a/fr/views/helpers/breadcrumbs.rst b/fr/views/helpers/breadcrumbs.rst index 8b719a89be..417d889164 100644 --- a/fr/views/helpers/breadcrumbs.rst +++ b/fr/views/helpers/breadcrumbs.rst @@ -194,6 +194,7 @@ complètement réinitialiser la liste:: $crumbs = $this->Breadcrumbs->getCrumbs(); $crumbs = collection($crumbs)->map(function ($crumb) { $crumb['options']['class'] = 'breadcrumb-item'; + return $crumb; })->toArray(); diff --git a/fr/views/helpers/form.rst b/fr/views/helpers/form.rst index 8a146aa7f9..39b00ec8b1 100644 --- a/fr/views/helpers/form.rst +++ b/fr/views/helpers/form.rst @@ -2543,6 +2543,7 @@ vouliez construire un widget Autocomplete, vous pourriez le faire comme ceci:: $data += [ 'name' => '', ]; + return $this->_templates->format('autocomplete', [ 'name' => $data['name'], 'attrs' => $this->_templates->formatAttributes($data, ['name']) diff --git a/ja/console-commands/commands.rst b/ja/console-commands/commands.rst index adc0b8ae38..a4b2783a72 100644 --- a/ja/console-commands/commands.rst +++ b/ja/console-commands/commands.rst @@ -62,6 +62,7 @@ CakePHP には、開発のスピードアップと日常的なタスクの自動 $parser->addArgument('name', [ 'help' => 'What is your name' ]); + return $parser; } diff --git a/ja/console-commands/shells.rst b/ja/console-commands/shells.rst index c965361f52..7fc5e5a9a2 100644 --- a/ja/console-commands/shells.rst +++ b/ja/console-commands/shells.rst @@ -140,12 +140,14 @@ public メソッドのうち頭に _ が付かないものは、コマンドラ public function getOptionParser() { $parser = parent::getOptionParser(); + $parser->addSubcommand('sound', [ // コマンド一覧のヘルプテキストを提供 'help' => 'Execute The Sound Task.', // オプションパーサーを互いにリンク 'parser' => $this->Sound->getOptionParser(), ]); + return $parser; } diff --git a/ja/controllers/components.rst b/ja/controllers/components.rst index 0a122cb943..557c0efeeb 100644 --- a/ja/controllers/components.rst +++ b/ja/controllers/components.rst @@ -140,6 +140,7 @@ CakePHP の中に含まれるコンポーネントの詳細については、各 { if ($this->Post->delete($this->request->getData('Post.id')) { $this->Flash->success('Post deleted.'); + return $this->redirect(['action' => 'index']); } } @@ -313,6 +314,7 @@ CakePHP の中に含まれるコンポーネントの詳細については、各 public function beforeFilter(EventInterface $event) { $event->stopPropagation(); + return $this->getController()->redirect('/'); } diff --git a/ja/controllers/components/authentication.rst b/ja/controllers/components/authentication.rst index 74ec8983f4..a9c4572c7d 100644 --- a/ja/controllers/components/authentication.rst +++ b/ja/controllers/components/authentication.rst @@ -221,6 +221,7 @@ SSL 暗号化しないアプリケーションにもふさわしいものです $user = $this->Auth->identify(); if ($user) { $this->Auth->setUser($user); + return $this->redirect($this->Auth->redirectUrl()); } else { $this->Flash->error(__('Username or password is incorrect')); @@ -427,6 +428,7 @@ CakePHP のライブラリーを使用してランダムにこれらの API ト $entity->plain_password, env('SERVER_NAME') ); + return true; } } @@ -697,6 +699,7 @@ CakePHP は、1つのアルゴリズムから別のユーザーのパスワー $user = $this->Users->newEntity($this->request->getData()); if ($this->Users->save($user)) { $this->Auth->setUser($user->toArray()); + return $this->redirect([ 'controller' => 'Users', 'action' => 'home' diff --git a/ja/controllers/middleware.rst b/ja/controllers/middleware.rst index 8900fe3e09..876416a425 100644 --- a/ja/controllers/middleware.rst +++ b/ja/controllers/middleware.rst @@ -74,6 +74,7 @@ CakePHP はウェブアプリケーションの一般的なタスクを処理す { // ミドルウェアのキューにエラーハンドラーを結びつけます。 $middlewareQueue->add(new ErrorHandlerMiddleware()); + return $middlewareQueue; } } @@ -110,7 +111,7 @@ CakePHP はウェブアプリケーションの一般的なタスクを処理す If your middleware is only applicable to a subset of routes or individual -controllers you can use :ref:`Route scoped middleware `, +controllers you can use :ref:`Route scoped middleware `, or :ref:`Controller middleware `. プラグインからのミドルウェア追加 diff --git a/ja/core-libraries/events.rst b/ja/core-libraries/events.rst index 288b5a104b..00fbeb47a0 100644 --- a/ja/core-libraries/events.rst +++ b/ja/core-libraries/events.rst @@ -437,6 +437,7 @@ DOM イベントのように、追加のリスナーへ通知されることを { // ... $alteredData = $event->getData('order') + $moreData; + return $alteredData; } diff --git a/ja/core-libraries/logging.rst b/ja/core-libraries/logging.rst index b2b4e57361..7fd01ddb6e 100644 --- a/ja/core-libraries/logging.rst +++ b/ja/core-libraries/logging.rst @@ -431,6 +431,7 @@ Composer を使って Monolog をインストールしたら、 Log::setConfig('default', function () { $log = new Logger('app'); $log->pushHandler(new StreamHandler('path/to/your/combined.log')); + return $log; }); @@ -448,6 +449,7 @@ Composer を使って Monolog をインストールしたら、 Log::setConfig('default', function () { $log = new Logger('cli'); $log->pushHandler(new StreamHandler('path/to/your/combined-cli.log')); + return $log; }); diff --git a/ja/development/errors.rst b/ja/development/errors.rst index ac14f82942..fb85ac56fb 100644 --- a/ja/development/errors.rst +++ b/ja/development/errors.rst @@ -199,6 +199,7 @@ ExceptionRenderer の変更 public function missingWidget($error) { $response = $this->controller->response; + return $response->withStringBody('おっとウィジェットが見つからない!'); } } diff --git a/ja/development/sessions.rst b/ja/development/sessions.rst index a3709e1152..65cd9289f0 100644 --- a/ja/development/sessions.rst +++ b/ja/development/sessions.rst @@ -265,6 +265,7 @@ IO をもたらします。 public function write($id, $data): bool { Cache::write($id, $data, $this->cacheKey); + return parent::write($id, $data); } @@ -272,6 +273,7 @@ IO をもたらします。 public function destroy($id): bool { Cache::delete($id, $this->cacheKey); + return parent::destroy($id); } diff --git a/ja/development/testing.rst b/ja/development/testing.rst index 2c4fc45a2d..75dd1a68a9 100644 --- a/ja/development/testing.rst +++ b/ja/development/testing.rst @@ -131,6 +131,7 @@ CakePHP が全般的にそうであるように、テストケースにもいく public function bar($value) { $width = round($value / 100, 2) * 100; + return sprintf( '
@@ -743,6 +744,7 @@ CakePHPコアまたはプラグインからフィクスチャをロードする $query->where([ $this->alias() . '.published' => 1 ]); + return $query; } } diff --git a/ja/orm/behaviors.rst b/ja/orm/behaviors.rst index ecb211204d..857a1fcd65 100644 --- a/ja/orm/behaviors.rst +++ b/ja/orm/behaviors.rst @@ -175,6 +175,7 @@ sluggable behavior を作成してみます。 if (...) { $event->stopPropagation(); $event->setResult(false); + return; } $this->slug($entity); diff --git a/ja/orm/query-builder.rst b/ja/orm/query-builder.rst index b71fc0b703..d8a4db13ab 100644 --- a/ja/orm/query-builder.rst +++ b/ja/orm/query-builder.rst @@ -168,6 +168,7 @@ Query オブジェクトのメソッドに慣れたら、 :doc:`Collection map(function ($row) { // map() は Collection のメソッドで、クエリーを実行します $row->trimmedTitle = trim($row->title); + return $row; }) ->combine('id', 'trimmedTitle') // combine() も Collection のメソッドです @@ -550,6 +551,7 @@ ORM とオブジェクトの結果セットは強力である一方で、エン $query->formatResults(function (\Cake\Collection\CollectionInterface $results) { return $results->map(function ($row) { $row['age'] = $row['birth_date']->diff(new \DateTime)->y; + return $row; }); }); @@ -679,6 +681,7 @@ Conditions ->where(function (QueryExpression $exp) { $orConditions = $exp->or(['author_id' => 2]) ->eq('author_id', 5); + return $exp ->add($orConditions) ->eq('published', true) @@ -706,6 +709,7 @@ Conditions return $or->eq('author_id', 2) ->eq('author_id', 5); }); + return $exp ->not($orConditions) ->lte('view_count', 10); @@ -717,6 +721,7 @@ Conditions ->where(function (QueryExpression $exp) { $orConditions = $exp->or(['author_id' => 2]) ->eq('author_id', 5); + return $exp ->not($orConditions) ->lte('view_count', 10); @@ -740,6 +745,7 @@ SQL 関数を使った式を構築することも可能です。 :: $year = $q->func()->year([ 'created' => 'identifier' ]); + return $exp ->gte($year, 2014) ->eq('published', true); diff --git a/ja/orm/retrieving-data-and-resultsets.rst b/ja/orm/retrieving-data-and-resultsets.rst index e793cdc806..9045935a48 100644 --- a/ja/orm/retrieving-data-and-resultsets.rst +++ b/ja/orm/retrieving-data-and-resultsets.rst @@ -357,6 +357,7 @@ fineder メソッドは、あなたが作成したい finder の名前が ``Foo` public function findOwnedBy(Query $query, array $options) { $user = $options['user']; + return $query->where(['author_id' => $user->id]); } } @@ -1190,6 +1191,7 @@ reducer が呼ばれるごとに、reducer はユーザーごとのフォロワ // 前のセクションで説明した共通の単語の件と同じもの $mapper = ...; $reducer = ...; + return $query->mapReduce($mapper, $reducer); } diff --git a/ja/orm/validation.rst b/ja/orm/validation.rst index 21615783d9..a418c88941 100644 --- a/ja/orm/validation.rst +++ b/ja/orm/validation.rst @@ -113,6 +113,7 @@ CakePHP ではデータの検証には二つの段階があります: $validator ->notEmptyString('title', __('タイトルを設定してください')) ->notEmptyString('body', __('本文は必須です')); + return $validator; } } @@ -207,6 +208,7 @@ CakePHP ではデータの検証には二つの段階があります: 'message' => __('有効な権限を指定する必要があります'), 'provider' => 'table', ]); + return $validator; } diff --git a/ja/security/csrf.rst b/ja/security/csrf.rst index 85685d9f97..98018be596 100644 --- a/ja/security/csrf.rst +++ b/ja/security/csrf.rst @@ -52,6 +52,7 @@ CSRFプロテクションは、アプリケーション全体、または特定 $csrf = new SessionCsrfProtectionMiddleware($options); $middlewareQueue->add($csrf); + return $middlewareQueue; } diff --git a/ja/tutorials-and-examples/blog-auth-example/auth.rst b/ja/tutorials-and-examples/blog-auth-example/auth.rst index 563242b7fd..aacc7cab7f 100644 --- a/ja/tutorials-and-examples/blog-auth-example/auth.rst +++ b/ja/tutorials-and-examples/blog-auth-example/auth.rst @@ -81,6 +81,7 @@ CakePHP にバンドルされているコード生成ユーティリティを利 $user = $this->Users->patchEntity($user, $this->request->getData()); if ($this->Users->save($user)) { $this->Flash->success(__('The user has been saved.')); + return $this->redirect(['action' => 'add']); } $this->Flash->error(__('Unable to add the user.')); @@ -342,6 +343,7 @@ composerを使ってAuthenticationプラグインをインストールします // POSTやGETに関係なく、ユーザーがログインしていればリダイレクトします if ($result->isValid()) { $this->Authentication->logout(); + return $this->redirect(['controller' => 'Users', 'action' => 'login']); } } diff --git a/ja/tutorials-and-examples/blog/part-three.rst b/ja/tutorials-and-examples/blog/part-three.rst index 8635ae8607..f75cfc1f93 100644 --- a/ja/tutorials-and-examples/blog/part-three.rst +++ b/ja/tutorials-and-examples/blog/part-three.rst @@ -347,6 +347,7 @@ Articles コントローラーを編集する $article = $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been saved.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to add your article.')); diff --git a/ja/tutorials-and-examples/blog/part-two.rst b/ja/tutorials-and-examples/blog/part-two.rst index 52f1aee036..c885c4f258 100644 --- a/ja/tutorials-and-examples/blog/part-two.rst +++ b/ja/tutorials-and-examples/blog/part-two.rst @@ -280,6 +280,7 @@ Articles テーブルに対して ``get()`` を用いるとき、存在するレ $article = $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('記事が保存されました。')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('記事の保存が出来ませんでした。')); @@ -436,6 +437,7 @@ CakePHP のバリデーションエンジンは強力で、 $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('記事が更新されました。')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('記事の更新が出来ませんでした。')); @@ -523,6 +525,7 @@ CakePHP は挿入あるいは更新のどちらを生成するかを決定しま $article = $this->Articles->get($id); if ($this->Articles->delete($article)) { $this->Flash->success(__('ID:{0}の記事が削除されました。', h($id))); + return $this->redirect(['action' => 'index']); } } diff --git a/ja/tutorials-and-examples/bookmarks/intro.rst b/ja/tutorials-and-examples/bookmarks/intro.rst index dd1955d54e..45611fd2d8 100644 --- a/ja/tutorials-and-examples/bookmarks/intro.rst +++ b/ja/tutorials-and-examples/bookmarks/intro.rst @@ -237,6 +237,7 @@ Scaffold コードの生成 protected function _setPassword($value) { $hasher = new DefaultPasswordHasher(); + return $hasher->hash($value); } } diff --git a/ja/tutorials-and-examples/bookmarks/part-two.rst b/ja/tutorials-and-examples/bookmarks/part-two.rst index d453108dcb..5ec2e9c74f 100644 --- a/ja/tutorials-and-examples/bookmarks/part-two.rst +++ b/ja/tutorials-and-examples/bookmarks/part-two.rst @@ -61,6 +61,7 @@ AppController に追加しましょう。 :: $user = $this->Auth->identify(); if ($user) { $this->Auth->setUser($user); + return $this->redirect($this->Auth->redirectUrl()); } $this->Flash->error('あなたのユーザー名またはパスワードが不正です。'); @@ -104,6 +105,7 @@ AppController に追加しましょう。 :: public function logout() { $this->Flash->success('ログアウトしました。'); + return $this->redirect($this->Auth->logout()); } @@ -231,6 +233,7 @@ AppController に追加しましょう。 :: $bookmark->user_id = $this->Auth->user('id'); if ($this->Bookmarks->save($bookmark)) { $this->Flash->success('ブックマークを保存しました。'); + return $this->redirect(['action' => 'index']); } $this->Flash->error('ブックマークは保存できませんでした。もう一度お試しください。'); @@ -254,6 +257,7 @@ AppController に追加しましょう。 :: $bookmark->user_id = $this->Auth->user('id'); if ($this->Bookmarks->save($bookmark)) { $this->Flash->success('ブックマークを保存しました。'); + return $this->redirect(['action' => 'index']); } $this->Flash->error('ブックマークは保存できませんでした。もう一度お試しください。'); @@ -312,6 +316,7 @@ AppController に追加しましょう。 :: $str = $tags->reduce(function ($string, $tag) { return $string . $tag->title . ', '; }, ''); + return trim($str, ', '); } diff --git a/ja/tutorials-and-examples/cms/articles-controller.rst b/ja/tutorials-and-examples/cms/articles-controller.rst index 0b5dbd3555..5aa8f1ce50 100644 --- a/ja/tutorials-and-examples/cms/articles-controller.rst +++ b/ja/tutorials-and-examples/cms/articles-controller.rst @@ -210,6 +210,7 @@ view テンプレートの作成 if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been saved.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to add your article.')); @@ -342,6 +343,7 @@ edit アクションの追加 $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been updated.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to update your article.')); @@ -471,6 +473,7 @@ delete アクションの追加 $article = $this->Articles->findBySlug($slug)->firstOrFail(); if ($this->Articles->delete($article)) { $this->Flash->success(__('The {0} article has been deleted.', $article->title)); + return $this->redirect(['action' => 'index']); } } diff --git a/ja/tutorials-and-examples/cms/authentication.rst b/ja/tutorials-and-examples/cms/authentication.rst index 234525c636..f26e193f04 100644 --- a/ja/tutorials-and-examples/cms/authentication.rst +++ b/ja/tutorials-and-examples/cms/authentication.rst @@ -266,6 +266,7 @@ logout アクションを ``UsersController`` に追加します。:: // POST, GET を問わず、ユーザーがログインしている場合はリダイレクトします if ($result && $result->isValid()) { $this->Authentication->logout(); + return $this->redirect(['controller' => 'Users', 'action' => 'login']); } } diff --git a/ja/tutorials-and-examples/cms/tags-and-users.rst b/ja/tutorials-and-examples/cms/tags-and-users.rst index ad11a0b03e..77a237070c 100644 --- a/ja/tutorials-and-examples/cms/tags-and-users.rst +++ b/ja/tutorials-and-examples/cms/tags-and-users.rst @@ -79,6 +79,7 @@ ArticlesTable の ``initialize`` メソッドに以下を追加することで if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been saved.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to add your article.')); diff --git a/ja/views/helpers/breadcrumbs.rst b/ja/views/helpers/breadcrumbs.rst index b8648d5ac4..8b6dd20e6b 100644 --- a/ja/views/helpers/breadcrumbs.rst +++ b/ja/views/helpers/breadcrumbs.rst @@ -176,6 +176,7 @@ BreadcrumbsHelper は内部で ``StringTemplateTrait`` を使用しています $crumbs = $this->Breadcrumbs->getCrumbs(); $crumbs = collection($crumbs)->map(function ($crumb) { $crumb['options']['class'] = 'breadcrumb-item'; + return $crumb; })->toArray(); diff --git a/ja/views/helpers/form.rst b/ja/views/helpers/form.rst index 12093fa09c..644976988f 100644 --- a/ja/views/helpers/form.rst +++ b/ja/views/helpers/form.rst @@ -2544,6 +2544,7 @@ autocomplete ウィジェットを作成したい場合、以下を実行でき $data += [ 'name' => '', ]; + return $this->_templates->format('autocomplete', [ 'name' => $data['name'], 'attrs' => $this->_templates->formatAttributes($data, ['name']) diff --git a/pt/console-and-shells.rst b/pt/console-and-shells.rst index 105f611294..60191bf643 100644 --- a/pt/console-and-shells.rst +++ b/pt/console-and-shells.rst @@ -494,7 +494,9 @@ facilmente definir múltiplas opções/argumentos de uma vez:: public function getOptionParser() { $parser = parent::getOptionParser(); + // Configure parser + return $parser; } @@ -508,6 +510,7 @@ série de chamadas de métodos:: public function getOptionParser() { $parser = parent::getOptionParser(); + $parser->addArgument('type', [ 'help' => 'Either a full path or type of class.' ])->addArgument('className', [ @@ -516,6 +519,7 @@ série de chamadas de métodos:: 'short' => 'm', 'help' => __('The specific method you want help on.') ])->description(__('Lookup doc block comments for classes in CakePHP.')); + return $parser; } diff --git a/pt/controllers/components.rst b/pt/controllers/components.rst index 425dea5277..43609cb2ed 100644 --- a/pt/controllers/components.rst +++ b/pt/controllers/components.rst @@ -1,14 +1,14 @@ Componentes ########### -Componentes são pacotes de lógica compartilhados entre controladores. O CakePHP -vem com um conjunto fantástico de componentes principais que você pode usar para +Componentes são pacotes de lógica compartilhados entre controladores. O CakePHP +vem com um conjunto fantástico de componentes principais que você pode usar para ajudar em várias tarefas comuns. Você também pode criar seus próprios componentes. -Se você deseja copiar e colar coisas entre controladores, considere criar seu próprio -componente para conter a funcionalidade. A criação de componentes mantém o código do +Se você deseja copiar e colar coisas entre controladores, considere criar seu próprio +componente para conter a funcionalidade. A criação de componentes mantém o código do controlador limpo e permite reutilizar o código entre diferentes controladores. -Para mais informações sobre os componentes incluídos no CakePHP, consulte o +Para mais informações sobre os componentes incluídos no CakePHP, consulte o capítulo para cada componente: .. toctree:: @@ -25,9 +25,9 @@ capítulo para cada componente: Configurando Componentes ======================== -Muitos dos componentes principais requerem configuração. Alguns exemplos de componentes -que requerem configuração são :doc:`/controllers/components/security` e -:doc:`/controllers/components/request-handling`. A configuração desses componentes e dos +Muitos dos componentes principais requerem configuração. Alguns exemplos de componentes +que requerem configuração são :doc:`/controllers/components/security` e +:doc:`/controllers/components/request-handling`. A configuração desses componentes e dos componentes em geral é geralmente feita via ``loadComponent()`` no método ``initialize()`` do seu Controlador ou através do array ``$components``:: @@ -45,7 +45,7 @@ do seu Controlador ou através do array ``$components``:: } Você pode configurar componentes em tempo de execução usando o método ``setConfig()``. -Muitas vezes, isso é feito no método ``beforeFilter()`` do seu controlador. O exemplo acima +Muitas vezes, isso é feito no método ``beforeFilter()`` do seu controlador. O exemplo acima também pode ser expresso como:: public function beforeFilter(EventInterface $event) @@ -53,7 +53,7 @@ também pode ser expresso como:: $this->RequestHandler->setConfig('viewClassMap', ['rss' => 'MyRssView']); } -Como os auxiliares, os componentes implementam os métodos ``getConfig()`` e +Como os auxiliares, os componentes implementam os métodos ``getConfig()`` e ``setConfig()`` para ler e gravar dados de configuração:: // Leia os dados de configuração. @@ -62,14 +62,14 @@ Como os auxiliares, os componentes implementam os métodos ``getConfig()`` e // Definir configuração $this->Csrf->setConfig('cookieName', 'token'); -Assim como os auxiliares, os componentes mesclam automaticamente sua propriedade -``$ _defaultConfig`` com a configuração do construtor para criar a propriedade +Assim como os auxiliares, os componentes mesclam automaticamente sua propriedade +``$ _defaultConfig`` com a configuração do construtor para criar a propriedade ``$_config`` que pode ser acessada com ``getConfig()`` e ``setConfig()``. Alias em Componentes -------------------- -Uma configuração comum a ser usada é a opção ``className``, que permite o alias +Uma configuração comum a ser usada é a opção ``className``, que permite o alias de componentes. Esse recurso é útil quando você deseja substituir ``$this->Auth`` ou outra referência de componente comum por uma implementação personalizada:: @@ -96,14 +96,14 @@ O exemplo acima seria *alias* ``MyAuthComponent`` para ``$this->Auth`` em seus c .. note:: - O alias de um componente substitui essa instância em qualquer lugar em que esse componente + O alias de um componente substitui essa instância em qualquer lugar em que esse componente seja usado, inclusive dentro de outros componentes. Carregando Componentes em Tempo Real ------------------------------------ -Você pode não precisar de todos os seus componentes disponíveis em todas as ações do controlador. -Em situações como essa, você pode carregar um componente em tempo de execução usando o método +Você pode não precisar de todos os seus componentes disponíveis em todas as ações do controlador. +Em situações como essa, você pode carregar um componente em tempo de execução usando o método ``loadComponent()`` no seu controlador:: // Em um método do controlador @@ -112,16 +112,16 @@ Em situações como essa, você pode carregar um componente em tempo de execuç .. note:: - Lembre-se de que os componentes carregados em tempo real não terão retornos de chamada perdidos. - Se você confiar nos retornos de chamada ``beforeFilter`` ou ``startup`` que estão sendo chamados, + Lembre-se de que os componentes carregados em tempo real não terão retornos de chamada perdidos. + Se você confiar nos retornos de chamada ``beforeFilter`` ou ``startup`` que estão sendo chamados, pode ser necessário chamá-los manualmente, dependendo de quando você carregar o componente. Usando Componentes ================== -Depois de incluir alguns componentes no seu controlador, usá-los é bastante simples. -Cada componente usado é exposto como uma propriedade no seu controlador. Se você -carregou a classe :php:class:`Cake\\Controller\\Component\\FlashComponent` no seu +Depois de incluir alguns componentes no seu controlador, usá-los é bastante simples. +Cada componente usado é exposto como uma propriedade no seu controlador. Se você +carregou a classe :php:class:`Cake\\Controller\\Component\\FlashComponent` no seu controlador, é possível acessá-lo da seguinte maneira:: class PostsController extends AppController @@ -136,14 +136,15 @@ controlador, é possível acessá-lo da seguinte maneira:: { if ($this->Post->delete($this->request->getData('Post.id')) { $this->Flash->success('Post deleted.'); + return $this->redirect(['action' => 'index']); } } .. note:: - Como os Modelos e os Componentes são adicionados aos Controladores - como propriedades, eles compartilham o mesmo 'namespace'. Certifique-se + Como os Modelos e os Componentes são adicionados aos Controladores + como propriedades, eles compartilham o mesmo 'namespace'. Certifique-se de não dar o mesmo nome a um componente de um modelo. .. _creating-a-component: @@ -151,12 +152,12 @@ controlador, é possível acessá-lo da seguinte maneira:: Criando um Componente ===================== -Suponha que nosso aplicativo precise executar uma operação matemática complexa -em muitas partes diferentes do aplicativo. Poderíamos criar um componente para +Suponha que nosso aplicativo precise executar uma operação matemática complexa +em muitas partes diferentes do aplicativo. Poderíamos criar um componente para hospedar essa lógica compartilhada para uso em muitos controladores diferentes. -O primeiro passo é criar um novo arquivo e classe de componente. Crie o arquivo em -**src/Controller/Component/MathComponent.php**. A estrutura básica do componente +O primeiro passo é criar um novo arquivo e classe de componente. Crie o arquivo em +**src/Controller/Component/MathComponent.php**. A estrutura básica do componente será semelhante a isso:: namespace App\Controller\Component; @@ -173,19 +174,19 @@ será semelhante a isso:: .. note:: - Todos os componentes devem estender :php:class:`Cake\\Controller\\Component`. + Todos os componentes devem estender :php:class:`Cake\\Controller\\Component`. Não fazer isso acionará uma exceção. Incluindo seu Componente em seus Controladores ---------------------------------------------- -Depois que nosso componente é concluído, podemos usá-lo nos controladores -do aplicativo carregando-o durante o método ``initialize()`` do controlador. -Uma vez carregado, o controlador receberá um novo atributo com o nome do componente, +Depois que nosso componente é concluído, podemos usá-lo nos controladores +do aplicativo carregando-o durante o método ``initialize()`` do controlador. +Uma vez carregado, o controlador receberá um novo atributo com o nome do componente, através do qual podemos acessar uma instância dele:: // Em um controlador - // Disponibilize o novo componente em $this->Math, + // Disponibilize o novo componente em $this->Math, // bem como o padrão $this->Csrf public function initialize(): void { @@ -194,8 +195,8 @@ através do qual podemos acessar uma instância dele:: $this->loadComponent('Csrf'); } -Ao incluir componentes em um controlador, você também pode declarar -um conjunto de parâmetros que serão passados para o construtor do componente. +Ao incluir componentes em um controlador, você também pode declarar +um conjunto de parâmetros que serão passados para o construtor do componente. Esses parâmetros podem ser manipulados pelo componente:: // Em seu controlador @@ -209,14 +210,14 @@ Esses parâmetros podem ser manipulados pelo componente:: $this->loadComponent('Csrf'); } -O exemplo acima passaria um array contendo precision e randomGenerator +O exemplo acima passaria um array contendo precision e randomGenerator para ``MathComponent::initialize()`` no parâmetro ``$config``. Usando Outros Componentes em seu Componente ------------------------------------------- -Às vezes, um de seus componentes pode precisar usar outro componente. -Nesse caso, você pode incluir outros componentes no seu componente +Às vezes, um de seus componentes pode precisar usar outro componente. +Nesse caso, você pode incluir outros componentes no seu componente exatamente da mesma maneira que os inclui nos controladores - usando o atributo ``$components``:: @@ -258,18 +259,18 @@ atributo ``$components``:: .. note:: - Ao contrário de um componente incluído em um controlador, + Ao contrário de um componente incluído em um controlador, nenhum retorno de chamada será acionado no componente de um componente. Acessando o Controlador de um Componente ---------------------------------------- -De dentro de um componente, você pode acessar o controlador atual através do +De dentro de um componente, você pode acessar o controlador atual através do registro:: $controller = $this->_registry->getController(); -Você pode acessar o controlador em qualquer método de retorno de chamada do objeto de +Você pode acessar o controlador em qualquer método de retorno de chamada do objeto de evento:: $controller = $event->getSubject(); @@ -277,22 +278,22 @@ evento:: Callback de Componentes ======================= -Os componentes também oferecem alguns retornos de chamada do ciclo de vida da solicitação que +Os componentes também oferecem alguns retornos de chamada do ciclo de vida da solicitação que permitem aumentar o ciclo da solicitação. .. php:method:: beforeFilter(EventInterface $event) - É chamado antes do método beforeFilter do controlador, + É chamado antes do método beforeFilter do controlador, mas *após* o método initialize() do controlador. .. php:method:: startup(EventInterface $event) - É chamado após o método beforeFilter do controlador, + É chamado após o método beforeFilter do controlador, mas antes que o controlador execute o manipulador de ações atual. .. php:method:: beforeRender(EventInterface $event) - É chamado após o controlador executar a lógica da ação solicitada, + É chamado após o controlador executar a lógica da ação solicitada, mas antes de o controlador renderizar visualizações e layout. .. php:method:: shutdown(EventInterface $event) @@ -301,10 +302,10 @@ permitem aumentar o ciclo da solicitação. .. php:method:: beforeRedirect(EventInterface $event, $url, Response $response) - É chamado quando o método de redirecionamento do controlador é chamado, - mas antes de qualquer ação adicional. Se esse método retornar ``false``, - o controlador não continuará redirecionando a solicitação. Os parâmetros - $url e $response permitem inspecionar e modificar o local ou qualquer outro + É chamado quando o método de redirecionamento do controlador é chamado, + mas antes de qualquer ação adicional. Se esse método retornar ``false``, + o controlador não continuará redirecionando a solicitação. Os parâmetros + $url e $response permitem inspecionar e modificar o local ou qualquer outro cabeçalho na resposta. .. meta:: diff --git a/pt/controllers/components/authentication.rst b/pt/controllers/components/authentication.rst index 6cde10e025..17d399cc24 100644 --- a/pt/controllers/components/authentication.rst +++ b/pt/controllers/components/authentication.rst @@ -216,6 +216,7 @@ trabalhar com um formulário de login pode se parecer com:: $user = $this->Auth->identify(); if ($user) { $this->Auth->setUser($user); + return $this->redirect($this->Auth->redirectUrl()); } else { $this->Flash->error(__('Username or password is incorrect')); @@ -432,6 +433,7 @@ a partir do hash da senha normal:: $entity->plain_password, env('SERVER_NAME') ); + return true; } } @@ -717,6 +719,7 @@ logo após ele se registrar no seu aplicativo. Você pode fazer isso chamando $user = $this->Users->newEntity($this->request->getData()); if ($this->Users->save($user)) { $this->Auth->setUser($user->toArray()); + return $this->redirect([ 'controller' => 'Users', 'action' => 'home' diff --git a/pt/controllers/middleware.rst b/pt/controllers/middleware.rst index 2b772318d6..06d02facf0 100644 --- a/pt/controllers/middleware.rst +++ b/pt/controllers/middleware.rst @@ -1,28 +1,28 @@ Middleware ########## -Os objetos de middleware permitem que você 'embrulhe' seu aplicativo em camadas -reutilizáveis e composíveis de manipulação de solicitações ou lógica de criação -de respostas. Visualmente, seu aplicativo termina no centro e o middleware é envolvido -em volta do aplicativo como uma cebola. Aqui, podemos ver um aplicativo agrupado com os +Os objetos de middleware permitem que você 'embrulhe' seu aplicativo em camadas +reutilizáveis e composíveis de manipulação de solicitações ou lógica de criação +de respostas. Visualmente, seu aplicativo termina no centro e o middleware é envolvido +em volta do aplicativo como uma cebola. Aqui, podemos ver um aplicativo agrupado com os middlewares Routes, Assets, Exception Handling e CORS. .. image:: /_static/img/middleware-setup.png -Quando um pedido é tratado pelo seu aplicativo, ele entra no middleware mais externo. -Cada middleware pode delegar a solicitação/resposta para a próxima camada ou retornar -uma resposta. O retorno de uma resposta impede que as camadas inferiores vejam a solicitação. -Um exemplo disso é o plugin AssetMiddleware manipulando uma solicitação de uma imagem de +Quando um pedido é tratado pelo seu aplicativo, ele entra no middleware mais externo. +Cada middleware pode delegar a solicitação/resposta para a próxima camada ou retornar +uma resposta. O retorno de uma resposta impede que as camadas inferiores vejam a solicitação. +Um exemplo disso é o plugin AssetMiddleware manipulando uma solicitação de uma imagem de durante o desenvolvimento. .. image:: /_static/img/middleware-request.png -Se nenhum middleware executar uma ação para manipular a solicitação, um controlador +Se nenhum middleware executar uma ação para manipular a solicitação, um controlador será localizado e terá sua ação invocada ou uma exceção será gerada gerando uma página de erro. -O middleware faz parte da nova pilha HTTP no CakePHP que aproveita as interfaces de solicitação e -resposta PSR-7. O CakePHP também suporta o padrão PSR-15 para manipuladores de solicitações de -servidor, para que você possa usar qualquer middleware compatível com PSR-15 disponível em +O middleware faz parte da nova pilha HTTP no CakePHP que aproveita as interfaces de solicitação e +resposta PSR-7. O CakePHP também suporta o padrão PSR-15 para manipuladores de solicitações de +servidor, para que você possa usar qualquer middleware compatível com PSR-15 disponível em `The Packagist `_. Middleware em CakePHP @@ -30,24 +30,24 @@ Middleware em CakePHP O CakePHP fornece vários middlewares para lidar com tarefas comuns em aplicativos da web: -* ``Cake\Error\Middleware\ErrorHandlerMiddleware`` intercepta exceções do middleware - empacotado e renderiza uma página de erro usando o manipulador de +* ``Cake\Error\Middleware\ErrorHandlerMiddleware`` intercepta exceções do middleware + empacotado e renderiza uma página de erro usando o manipulador de exceção :doc:`/development/errors`. -* ``Cake\Routing\AssetMiddleware`` verifica se a solicitação está se referindo a um tema ou - arquivo estático do plug-in, como CSS, JavaScript ou arquivo de imagem armazenado na pasta +* ``Cake\Routing\AssetMiddleware`` verifica se a solicitação está se referindo a um tema ou + arquivo estático do plug-in, como CSS, JavaScript ou arquivo de imagem armazenado na pasta raiz da web de um plug-in ou na pasta correspondente a um Tema. -* ``Cake\Routing\Middleware\RoutingMiddleware`` usa o ``Router`` para analisar a URL +* ``Cake\Routing\Middleware\RoutingMiddleware`` usa o ``Router`` para analisar a URL recebida e atribuir parâmetros de roteamento à solicitação. -* ``Cake\I18n\Middleware\LocaleSelectorMiddleware`` habilita a troca automática de idioma no +* ``Cake\I18n\Middleware\LocaleSelectorMiddleware`` habilita a troca automática de idioma no cabeçalho ``Accept-Language`` enviado pelo navegador. -* ``Cake\Http\Middleware\SecurityHeadersMiddleware`` facilita adicionar cabeçalhos relacionados +* ``Cake\Http\Middleware\SecurityHeadersMiddleware`` facilita adicionar cabeçalhos relacionados à segurança como ``X-Frame-Options`` às respostas. -* ``Cake\Http\Middleware\EncryptedCookieMiddleware`` oferece a capacidade de manipular cookies +* ``Cake\Http\Middleware\EncryptedCookieMiddleware`` oferece a capacidade de manipular cookies criptografados, caso você precise manipular cookies com dados ofuscados. * ``Cake\Http\Middleware\CsrfProtectionMiddleware`` adiciona proteção CSRF ao seu aplicativo. -* ``Cake\Http\Middleware\BodyParserMiddleware`` permite decodificar JSON, XML e outros corpos +* ``Cake\Http\Middleware\BodyParserMiddleware`` permite decodificar JSON, XML e outros corpos de solicitação codificados com base no cabeçalho ``Content-Type``. -* ``Cake\Http\Middleware\CspMiddleware`` simplifica a adição de cabeçalhos de política de +* ``Cake\Http\Middleware\CspMiddleware`` simplifica a adição de cabeçalhos de política de segurança de conteúdo ao seu aplicativo. .. _using-middleware: @@ -58,8 +58,8 @@ Usando Middleware O middleware pode ser aplicado ao seu aplicativo globalmente ou individualmente a escopos de roteamento. -Para aplicar o middleware a todas as solicitações, use o método ``middleware`` da sua classe -``App\Application``. O método de gancho ``middleware`` do seu aplicativo será chamado no +Para aplicar o middleware a todas as solicitações, use o método ``middleware`` da sua classe +``App\Application``. O método de gancho ``middleware`` do seu aplicativo será chamado no início do processo de solicitação; você pode usar o objeto ``MiddlewareQueue`` para anexar o middleware:: @@ -75,6 +75,7 @@ middleware:: { // Vincule o manipulador de erros à fila do middleware. $middlwareQueue->add(new ErrorHandlerMiddleware()); + return $middlwareQueue; } } @@ -89,7 +90,7 @@ Além de adicionar ao final do ``MiddlewareQueue``, você pode executar várias // O middleware precedido será o primeiro da fila. $middlwareQueue->prepend($layer); - // Insira em um slot específico. Se o slot estiver + // Insira em um slot específico. Se o slot estiver // fora dos limites, ele será adicionado ao final. $middlwareQueue->insertAt(2, $layer); @@ -109,14 +110,14 @@ Além de adicionar ao final do ``MiddlewareQueue``, você pode executar várias $layer ); -Além de aplicar o middleware a todo o aplicativo, você pode aplicar o -middleware a conjuntos específicos de rotas usando +Além de aplicar o middleware a todo o aplicativo, você pode aplicar o +middleware a conjuntos específicos de rotas usando :ref:`Scope Middleware `. Adicionando Middleware a partir de Plugins ------------------------------------------ -Os plug-ins podem usar seu método de gancho ``middleware`` para aplicar qualquer +Os plug-ins podem usar seu método de gancho ``middleware`` para aplicar qualquer middleware que eles tenham à fila de middleware do aplicativo:: // Em plugins/ContactManager/src/Plugin.php @@ -139,19 +140,19 @@ middleware que eles tenham à fila de middleware do aplicativo:: Criando um Middleware ===================== -O middleware pode ser implementado como funções anônimas (Closures) ou classes que -estendem ``Psr\Http\Server\MiddlewareInterface``. Embora os Closures sejam -adequados para tarefas menores, eles tornam os testes mais difíceis e podem criar -uma classe ``Application`` complicada. As classes de middleware no CakePHP têm +O middleware pode ser implementado como funções anônimas (Closures) ou classes que +estendem ``Psr\Http\Server\MiddlewareInterface``. Embora os Closures sejam +adequados para tarefas menores, eles tornam os testes mais difíceis e podem criar +uma classe ``Application`` complicada. As classes de middleware no CakePHP têm algumas convenções: -* Os arquivos de classe Middleware devem ser colocados em ** src/Middleware**. Por exemplo: +* Os arquivos de classe Middleware devem ser colocados em ** src/Middleware**. Por exemplo: **src/Middleware/CorsMiddleware.php** -* As classes de middleware devem ter o sufixo ``Middleware``. Por exemplo: +* As classes de middleware devem ter o sufixo ``Middleware``. Por exemplo: ``LinkMiddleware``. * O Middleware deve implementar ``Psr\Http\Server\MiddlewareInterface``. -O middleware pode retornar uma resposta chamando ``$handler->handle()`` +O middleware pode retornar uma resposta chamando ``$handler->handle()`` ou criando sua própria resposta. Podemos ver as duas opções em nosso middleware simples:: // Em src/Middleware/TrackingCookieMiddleware.php @@ -169,9 +170,9 @@ ou criando sua própria resposta. Podemos ver as duas opções em nosso middlewa public function process( ServerRequestInterface $request, RequestHandlerInterface $handler - ): ResponseInterface + ): ResponseInterface { - // Chamar $handler->handle() delega o controle para + // Chamar $handler->handle() delega o controle para // o *próximo* middleware na fila do seu aplicativo. $response = $handler->handle($request); @@ -188,7 +189,7 @@ ou criando sua própria resposta. Podemos ver as duas opções em nosso middlewa } } -Agora que criamos um middleware muito simples, vamos anexá-lo ao nosso +Agora que criamos um middleware muito simples, vamos anexá-lo ao nosso aplicativo:: // Em src/Application.php @@ -216,10 +217,10 @@ aplicativo:: Roteamento de Middleware ======================== -O middleware de roteamento é responsável por aplicar as rotas no seu aplicativo e -resolver o: plug-in, o controlador e a ação que uma solicitação está pedindo. -Ele pode armazenar em cache a coleção de rotas usada no seu aplicativo para aumentar o -tempo de inicialização. Para habilitar o cache de rotas em, forneça o +O middleware de roteamento é responsável por aplicar as rotas no seu aplicativo e +resolver o: plug-in, o controlador e a ação que uma solicitação está pedindo. +Ele pode armazenar em cache a coleção de rotas usada no seu aplicativo para aumentar o +tempo de inicialização. Para habilitar o cache de rotas em, forneça o :ref:`cache configuration ` desejado como um parâmetro:: // Em Application.php @@ -229,7 +230,7 @@ tempo de inicialização. Para habilitar o cache de rotas em, forneça o $middlwareQueue->add(new RoutingMiddleware($this, 'routing')); } -O exemplo acima usaria o mecanismo de cache ``routing`` para armazenar a coleção +O exemplo acima usaria o mecanismo de cache ``routing`` para armazenar a coleção de rotas gerada. .. _security-header-middleware: @@ -237,8 +238,8 @@ de rotas gerada. Middleware de Cabeçalho de Segurança ==================================== -A camada ``Security Headers Middleware`` facilita a aplicação de cabeçalhos -relacionados à segurança em seu aplicativo. Depois de configurado, o middleware +A camada ``Security Headers Middleware`` facilita a aplicação de cabeçalhos +relacionados à segurança em seu aplicativo. Depois de configurado, o middleware pode aplicar os seguintes cabeçalhos às respostas: * ``X-Content-Type-Options`` @@ -247,7 +248,7 @@ pode aplicar os seguintes cabeçalhos às respostas: * ``X-Permitted-Cross-Domain-Policies`` * ``Referrer-Policy`` -Esse middleware é configurado usando uma interface simples antes de ser aplicado à +Esse middleware é configurado usando uma interface simples antes de ser aplicado à pilha de middleware do seu aplicativo:: use Cake\Http\Middleware\SecurityHeadersMiddleware; @@ -266,14 +267,14 @@ pilha de middleware do seu aplicativo:: Middleware do Cabeçalho da Política de Segurança de Conteúdo ============================================================ -O ``CspMiddleware`` facilita a adição de cabeçalhos referente a política de segurança de +O ``CspMiddleware`` facilita a adição de cabeçalhos referente a política de segurança de conteúdo em seu aplicativo. Antes de usá-lo, você deve instalar o ``paragonie/csp-builder``: .. code-block::bash composer require paragonie/csp-builder -Você pode configurar o middleware usando uma matriz ou passando um +Você pode configurar o middleware usando uma matriz ou passando um objeto ``CSPBuilder`` integrado:: use Cake\Http\Middleware\CspMiddleware; @@ -296,10 +297,10 @@ objeto ``CSPBuilder`` integrado:: Middleware de Cookie Criptografado ================================== -Se o seu aplicativo possui cookies que contêm dados que você deseja ofuscar e -proteger contra adulterações do usuário, você pode usar o middleware de cookies -criptografado do CakePHP para criptografar e descriptografar de forma transparente -os dados de cookies via middleware. Os dados dos cookies são criptografados via +Se o seu aplicativo possui cookies que contêm dados que você deseja ofuscar e +proteger contra adulterações do usuário, você pode usar o middleware de cookies +criptografado do CakePHP para criptografar e descriptografar de forma transparente +os dados de cookies via middleware. Os dados dos cookies são criptografados via OpenSSL usando AES:: use Cake\Http\Middleware\EncryptedCookieMiddleware; @@ -313,10 +314,10 @@ OpenSSL usando AES:: $middlwareQueue->add($cookies); .. note:: - É recomendável que a chave de criptografia usada para os dados do + É recomendável que a chave de criptografia usada para os dados do cookie seja usada *exclusivamente* para os dados do cookie. -Os algoritmos de criptografia e o estilo de preenchimento usados pelo middleware +Os algoritmos de criptografia e o estilo de preenchimento usados pelo middleware do cookie são compatíveis com o ``CookieComponent`` de versões anteriores do CakePHP. .. _csrf-middleware: @@ -328,11 +329,11 @@ A proteção CSRF pode ser aplicada a todo o aplicativo ou a escopos de roteamen .. note:: - Você não pode usar as duas abordagens a seguir juntas; deve escolher apenas uma. - Se você usar as duas abordagens juntas, ocorrerá um erro de incompatibilidade de + Você não pode usar as duas abordagens a seguir juntas; deve escolher apenas uma. + Se você usar as duas abordagens juntas, ocorrerá um erro de incompatibilidade de token CSRF em cada solicitação `PUT` e` POST` -Ao aplicar o ``CsrfProtectionMiddleware`` à pilha de middleware do Aplicativo, +Ao aplicar o ``CsrfProtectionMiddleware`` à pilha de middleware do Aplicativo, você protege todas as ações no aplicativo:: // Em src/Application.php @@ -345,10 +346,11 @@ você protege todas as ações no aplicativo:: $csrf = new CsrfProtectionMiddleware($options); $middlwareQueue->add($csrf); + return $middlwareQueue; } -Ao aplicar o ``CsrfProtectionMiddleware`` aos escopos de roteamento, você pode +Ao aplicar o ``CsrfProtectionMiddleware`` aos escopos de roteamento, você pode incluir ou excluir grupos de rotas específicos:: // Em src/Application.php @@ -386,27 +388,27 @@ Quando ativado, você pode acessar o token CSRF atual no objeto de solicitação .. note:: - Você deve aplicar o middleware de proteção CSRF apenas para URLs que manipulam solicitações - com estado usando cookies/sessão. Solicitações sem estado, por ex. ao desenvolver uma API, + Você deve aplicar o middleware de proteção CSRF apenas para URLs que manipulam solicitações + com estado usando cookies/sessão. Solicitações sem estado, por ex. ao desenvolver uma API, não são afetados pelo CSRF; portanto, o middleware não precisa ser aplicado a essas URLs. Integração com FormHelper ------------------------- -O ``CsrfProtectionMiddleware`` se integra perfeitamente ao ``FormHelper``. Cada vez +O ``CsrfProtectionMiddleware`` se integra perfeitamente ao ``FormHelper``. Cada vez que você cria um formulário com ``FormHelper``, ele insere um campo oculto que contém o token CSRF. .. note:: - Ao usar a proteção CSRF, você sempre deve iniciar seus formulários com o ``FormHelper``. + Ao usar a proteção CSRF, você sempre deve iniciar seus formulários com o ``FormHelper``. Caso contrário, será necessário criar manualmente entradas ocultas em cada um dos seus formulários. Solicitações de Proteção CSRF e AJAX ------------------------------------ -Além de solicitar parâmetros de dados, os tokens CSRF podem ser enviados por meio -de um cabeçalho especial ``X-CSRF-Token``. O uso de um cabeçalho geralmente facilita -a integração de um token CSRF com aplicativos pesados de JavaScript ou endpoints de API +Além de solicitar parâmetros de dados, os tokens CSRF podem ser enviados por meio +de um cabeçalho especial ``X-CSRF-Token``. O uso de um cabeçalho geralmente facilita +a integração de um token CSRF com aplicativos pesados de JavaScript ou endpoints de API baseados em XML/JSON. O token CSRF pode ser obtido através do cookie ``csrfToken``. @@ -417,11 +419,11 @@ O token CSRF pode ser obtido através do cookie ``csrfToken``. Body Parser Middleware ====================== -Se seu aplicativo aceitar JSON, XML ou outros corpos de solicitação codificados, -o ``BodyParserMiddleware`` permitirá que você decodifique essas solicitações em -uma matriz que esteja disponível em ``$request->getParsedData()`` e -``$request->getData()``. Por padrão, apenas os corpos ``json`` serão analisados, -mas a análise XML pode ser ativada com uma opção. Você também pode definir seus +Se seu aplicativo aceitar JSON, XML ou outros corpos de solicitação codificados, +o ``BodyParserMiddleware`` permitirá que você decodifique essas solicitações em +uma matriz que esteja disponível em ``$request->getParsedData()`` e +``$request->getData()``. Por padrão, apenas os corpos ``json`` serão analisados, +mas a análise XML pode ser ativada com uma opção. Você também pode definir seus próprios analisadores:: use Cake\Http\Middleware\BodyParserMiddleware; @@ -435,7 +437,7 @@ próprios analisadores:: // Desativar a análise JSON $bodies = new BodyParserMiddleware(['json' => false]); - // Adicione seu próprio analisador que corresponda aos + // Adicione seu próprio analisador que corresponda aos // valores do cabeçalho do tipo de conteúdo à chamada que pode analisá-los. $bodies = new BodyParserMiddleware(); $bodies->addParser(['text/csv'], function ($body, $request) { diff --git a/pt/core-libraries/events.rst b/pt/core-libraries/events.rst index 1eb6e6901f..11cccd43ad 100644 --- a/pt/core-libraries/events.rst +++ b/pt/core-libraries/events.rst @@ -65,6 +65,7 @@ o Model Orders limpo você poderia usar eventos:: 'order' => $order ]); $this->eventManager()->dispatch($event); + return true; } return false; @@ -453,6 +454,7 @@ diretamente ou retornando o valor no próprio callback:: { // ... $alteredData = $event->getData('order') + $moreData; + return $alteredData; } // Outro callback diff --git a/pt/development/configuration.rst b/pt/development/configuration.rst index 45de3cd029..9f2df9b85b 100644 --- a/pt/development/configuration.rst +++ b/pt/development/configuration.rst @@ -431,6 +431,7 @@ aplicação:: public function read($key) { $xml = Xml::build($this->_path . $key . '.xml'); + return Xml::toArray($xml); } diff --git a/pt/development/sessions.rst b/pt/development/sessions.rst index a37405bfd4..3d82f9bb41 100644 --- a/pt/development/sessions.rst +++ b/pt/development/sessions.rst @@ -258,6 +258,7 @@ A classe deve se parecer com:: public function write($id, $data) { Cache::write($id, $data, $this->cacheKey); + return parent::write($id, $data); } @@ -265,6 +266,7 @@ A classe deve se parecer com:: public function destroy($id) { Cache::delete($id, $this->cacheKey); + return parent::destroy($id); } @@ -409,4 +411,4 @@ e :doc:`/views/helpers/flash`. .. meta:: :title lang=pt: Sessões - :keywords lang=pt: sessões padrão, classes de sessão, recursos utilitários, encerramento de sessão, ids de sessão, persistência de dados, chave de sessão, cookie de sessão, dados de sessão, última sessão, core do banco de dados, nível de segurança, useragent, razões de segurança, id de sessão, attr, countdown, regeneração, sessions, config \ No newline at end of file + :keywords lang=pt: sessões padrão, classes de sessão, recursos utilitários, encerramento de sessão, ids de sessão, persistência de dados, chave de sessão, cookie de sessão, dados de sessão, última sessão, core do banco de dados, nível de segurança, useragent, razões de segurança, id de sessão, attr, countdown, regeneração, sessions, config diff --git a/pt/development/testing.rst b/pt/development/testing.rst index 9804eb9a9d..e110b7460d 100644 --- a/pt/development/testing.rst +++ b/pt/development/testing.rst @@ -137,6 +137,7 @@ que vamos testar estará formatando a barra de progresso HTML. Nosso ajudante se public function bar($value) { $width = round($value / 100, 2) * 100; + return sprintf( '
@@ -684,6 +685,7 @@ Digamos que já temos nossa classe de tabela de artigos definida em $query->where([ $this->alias() . '.published' => 1 ]); + return $query; } } @@ -1707,6 +1709,7 @@ Expandindo no exemplo Orders, digamos que temos as seguintes tabelas:: 'order' => $order ]); $this->eventManager()->dispatch($event); + return true; } return false; diff --git a/pt/orm/behaviors.rst b/pt/orm/behaviors.rst index d88db14b6e..9641237a7e 100644 --- a/pt/orm/behaviors.rst +++ b/pt/orm/behaviors.rst @@ -192,6 +192,7 @@ evento em seu callback:: { if (...) { $event->stopPropagation(); + return; } $this->slug($entity); diff --git a/pt/orm/behaviors/tree.rst b/pt/orm/behaviors/tree.rst index b6c4557de3..69be9f6950 100644 --- a/pt/orm/behaviors/tree.rst +++ b/pt/orm/behaviors/tree.rst @@ -187,6 +187,7 @@ Opcionalmente, você pode ter um controle mais refinado do escopo passando um cl $this->behaviors()->Tree->config('scope', function ($query) { $country = $this->getConfigureContry(); // uma função inventada + return $query->where(['country_name' => $country]); }); diff --git a/pt/orm/query-builder.rst b/pt/orm/query-builder.rst index 96c9002793..5071d026d1 100644 --- a/pt/orm/query-builder.rst +++ b/pt/orm/query-builder.rst @@ -176,6 +176,7 @@ você também pode fazer em um objeto Query:: ->order(['title' => 'DESC']) ->map(function ($row) { // map() é um método de coleção, ele executa a consulta $row->trimmedTitle = trim($row->title); + return $row; }) ->combine('id', 'trimmedTitle') // combine() é outro método de coleção @@ -573,6 +574,7 @@ um formatador de resultados:: $query->formatResults(function (\Cake\Collection\CollectionInterface $results) { return $results->map(function ($row) { $row['age'] = $row['birth_date']->diff(new \DateTime)->y; + return $row; }); }); @@ -594,6 +596,7 @@ funcionaria conforme o esperado:: return $q->formatResults(function (\Cake\Collection\CollectionInterface $authors) { return $authors->map(function ($author) { $author['age'] = $author['birth_date']->diff(new \DateTime)->y; + return $author; }); }); @@ -705,6 +708,7 @@ No entanto, se quisermos usar as condições ``AND`` e ``OR``, poderíamos fazer ->where(function (QueryExpression $exp) { $orConditions = $exp->or_(['author_id' => 2]) ->eq('author_id', 5); + return $exp ->add($orConditions) ->eq('published', true) @@ -731,6 +735,7 @@ Muitas vezes, é mais fácil ler do que encadear métodos:: return $or->eq('author_id', 2) ->eq('author_id', 5); }); + return $exp ->not($orConditions) ->lte('view_count', 10); @@ -742,6 +747,7 @@ Você pode negar sub-expressões usando ``not()``:: ->where(function (QueryExpression $exp) { $orConditions = $exp->or_(['author_id' => 2]) ->eq('author_id', 5); + return $exp ->not($orConditions) ->lte('view_count', 10); @@ -764,6 +770,7 @@ Também é possível construir expressões usando as funções SQL:: $year = $q->func()->year([ 'created' => 'identifier' ]); + return $exp ->gte($year, 2014) ->eq('published', true); diff --git a/pt/orm/retrieving-data-and-resultsets.rst b/pt/orm/retrieving-data-and-resultsets.rst index da92145a55..ecb68b4508 100644 --- a/pt/orm/retrieving-data-and-resultsets.rst +++ b/pt/orm/retrieving-data-and-resultsets.rst @@ -347,6 +347,7 @@ Neste exemplo mostramos como encontrarmos um artigo quando este estiver publicad public function findOwnedBy(Query $query, array $options) { $user = $options['user']; + return $query->where(['author_id' => $user->id]); } @@ -1188,6 +1189,7 @@ This is particularly useful for building custom finder methods as described in t // Same as in the common words example in the previous section $mapper = ...; $reducer = ...; + return $query->mapReduce($mapper, $reducer); } diff --git a/pt/tutorials-and-examples/blog-auth-example/auth.rst b/pt/tutorials-and-examples/blog-auth-example/auth.rst index 43dfd633f8..2ba17fdfdc 100644 --- a/pt/tutorials-and-examples/blog-auth-example/auth.rst +++ b/pt/tutorials-and-examples/blog-auth-example/auth.rst @@ -92,6 +92,7 @@ geração de código ``bake`` fornecido com CakePHP:: $user = $this->Users->patchEntity($user, $this->request->getData()); if ($this->Users->save($user)) { $this->Flash->success(__('O usuário foi salvo.')); + return $this->redirect(['action' => 'add']); } $this->Flash->error(__('Não é possível adicionar o usuário.')); @@ -202,6 +203,7 @@ execute as ações de ``login`` e ``logout``:: $user = $this->Auth->identify(); if ($user) { $this->Auth->setUser($user); + return $this->redirect($this->Auth->redirectUrl()); } $this->Flash->error(__('Usuário ou senha ínvalido, tente novamente')); @@ -315,6 +317,7 @@ criado:: //$article = $this->Articles->patchEntity($article, $newData); if ($this->Articles->save($article)) { $this->Flash->success(__('Seu artigo foi salvo.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Não foi possível adicionar seu artigo.')); diff --git a/pt/tutorials-and-examples/blog/part-three.rst b/pt/tutorials-and-examples/blog/part-three.rst index c81b1e7b56..f7361622f9 100644 --- a/pt/tutorials-and-examples/blog/part-three.rst +++ b/pt/tutorials-and-examples/blog/part-three.rst @@ -356,6 +356,7 @@ ele: $article = $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been saved.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to add your article.')); diff --git a/pt/tutorials-and-examples/blog/part-two.rst b/pt/tutorials-and-examples/blog/part-two.rst index e9b69007c8..5f30bc5d4a 100644 --- a/pt/tutorials-and-examples/blog/part-two.rst +++ b/pt/tutorials-and-examples/blog/part-two.rst @@ -280,6 +280,7 @@ Primeiro, comece criando a action ``add()`` no ``ArticlesController``:: $article = $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Seu artigo foi salvo.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Não é possível adicionar o seu artigo.')); @@ -439,6 +440,7 @@ a action ``edit()`` que deverá ser inserida no ``ArticlesController``:: $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Seu artigo foi atualizado.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Seu artigo não pôde ser atualizado.')); @@ -527,6 +529,7 @@ A seguir, vamos criar uma forma de deletar artigos. Comece com uma action $article = $this->Articles->get($id); if ($this->Articles->delete($article)) { $this->Flash->success(__('O artigo com id: {0} foi deletado.', h($id))); + return $this->redirect(['action' => 'index']); } } diff --git a/pt/tutorials-and-examples/bookmarks/intro.rst b/pt/tutorials-and-examples/bookmarks/intro.rst index 3955fa3070..86fa41d627 100644 --- a/pt/tutorials-and-examples/bookmarks/intro.rst +++ b/pt/tutorials-and-examples/bookmarks/intro.rst @@ -233,6 +233,7 @@ para a senha. Em **src/Model/Entity/User.php** adicione o seguinte:: protected function _setPassword($value) { $hasher = new DefaultPasswordHasher(); + return $hasher->hash($value); } } diff --git a/pt/tutorials-and-examples/bookmarks/part-two.rst b/pt/tutorials-and-examples/bookmarks/part-two.rst index 896fa6f8f0..972ea99c0f 100644 --- a/pt/tutorials-and-examples/bookmarks/part-two.rst +++ b/pt/tutorials-and-examples/bookmarks/part-two.rst @@ -66,6 +66,7 @@ Então, vamos criar a ação de login:: $user = $this->Auth->identify(); if ($user) { $this->Auth->setUser($user); + return $this->redirect($this->Auth->redirectUrl()); } $this->Flash->error('Your username or password is incorrect.'); @@ -103,6 +104,7 @@ fornecer uma maneira de encerrar a sessão também. Mais uma vez, no public function logout() { $this->Flash->success('You are now logged out.'); + return $this->redirect($this->Auth->logout()); } @@ -236,6 +238,7 @@ Com isso removido, nós também vamos atualizar o método add:: $bookmark->user_id = $this->Auth->user('id'); if ($this->Bookmarks->save($bookmark)) { $this->Flash->success('The bookmark has been saved.'); + return $this->redirect(['action' => 'index']); } $this->Flash->error('The bookmark could not be saved. Please, try again.'); @@ -245,7 +248,7 @@ Com isso removido, nós também vamos atualizar o método add:: } Ao definir a propriedade da entidade com os dados da sessão, nós removemos -qualquer possibilidade do user modificar algo que não pertenca a ele. +qualquer possibilidade do user modificar algo que não pertenca a ele. Nós vamos fazer o mesmo para o formulário edit e action edit. Sua ação edit deve ficar assim:: @@ -259,6 +262,7 @@ ação edit deve ficar assim:: $bookmark->user_id = $this->Auth->user('id'); if ($this->Bookmarks->save($bookmark)) { $this->Flash->success('The bookmark has been saved.'); + return $this->redirect(['action' => 'index']); } $this->Flash->error('The bookmark could not be saved. Please, try again.'); @@ -317,6 +321,7 @@ entidade. Em **src/Model/Entity/Bookmark.php** adicione o seguinte:: $str = $tags->reduce(function ($string, $tag) { return $string . $tag->title . ', '; }, ''); + return trim($str, ', '); } From 2827cbfe0b725b2e5acc1f09c3122a4f8c0fa3ce Mon Sep 17 00:00:00 2001 From: "marc.wuerth" Date: Thu, 2 May 2024 17:21:36 +0200 Subject: [PATCH 44/68] Comment out ellipsis for better copy-paste-ability --- en/contributing/cakephp-coding-conventions.rst | 2 +- en/core-libraries/httpclient.rst | 16 ++++++++-------- en/orm/query-builder.rst | 2 +- en/orm/retrieving-data-and-resultsets.rst | 2 +- en/orm/validation.rst | 2 +- fr/core-libraries/httpclient.rst | 16 ++++++++-------- fr/orm/query-builder.rst | 2 +- fr/orm/retrieving-data-and-resultsets.rst | 2 +- fr/orm/validation.rst | 2 +- ja/contributing/cakephp-coding-conventions.rst | 2 +- ja/core-libraries/httpclient.rst | 16 ++++++++-------- ja/orm/retrieving-data-and-resultsets.rst | 2 +- ja/orm/validation.rst | 4 ++-- pt/core-libraries/httpclient.rst | 6 +++--- pt/orm/query-builder.rst | 2 +- pt/orm/retrieving-data-and-resultsets.rst | 2 +- 16 files changed, 40 insertions(+), 40 deletions(-) diff --git a/en/contributing/cakephp-coding-conventions.rst b/en/contributing/cakephp-coding-conventions.rst index 4b764eff17..a1d3d07f71 100644 --- a/en/contributing/cakephp-coding-conventions.rst +++ b/en/contributing/cakephp-coding-conventions.rst @@ -265,7 +265,7 @@ Try to avoid unnecessary nesting by bailing early:: { ... if (!$success) { - throw new RuntimeException(...); + throw new RuntimeException(/* ... */); } ... diff --git a/en/core-libraries/httpclient.rst b/en/core-libraries/httpclient.rst index 018331e858..a7ff1a60cb 100644 --- a/en/core-libraries/httpclient.rst +++ b/en/core-libraries/httpclient.rst @@ -45,9 +45,9 @@ Doing POST and PUT requests is equally simple:: ]); // Other methods as well. - $http->delete(...); - $http->head(...); - $http->patch(...); + $http->delete(/* ... */); + $http->head(/* ... */); + $http->patch(/* ... */); If you have created a PSR-7 request object you can send it using ``sendRequest()``:: @@ -508,11 +508,11 @@ is making:: There are methods to mock the most commonly used HTTP methods:: - $this->mockClientGet(...); - $this->mockClientPatch(...); - $this->mockClientPost(...); - $this->mockClientPut(...); - $this->mockClientDelete(...); + $this->mockClientGet(/* ... */); + $this->mockClientPatch(/* ... */); + $this->mockClientPost(/* ... */); + $this->mockClientPut(/* ... */); + $this->mockClientDelete(/* ... */); .. php:method:: newClientResponse(int $code = 200, array $headers = [], string $body = '') diff --git a/en/orm/query-builder.rst b/en/orm/query-builder.rst index f90c5c436f..d3e480fbf9 100644 --- a/en/orm/query-builder.rst +++ b/en/orm/query-builder.rst @@ -464,7 +464,7 @@ complex expressions:: To build complex order clauses, use a Closure to build order expressions:: $query->orderAsc(function (QueryExpression $exp, Query $query) { - return $exp->addCase(...); + return $exp->addCase(/* ... */); }); diff --git a/en/orm/retrieving-data-and-resultsets.rst b/en/orm/retrieving-data-and-resultsets.rst index 16abab7b70..0788595e6e 100644 --- a/en/orm/retrieving-data-and-resultsets.rst +++ b/en/orm/retrieving-data-and-resultsets.rst @@ -648,7 +648,7 @@ Use the ``queryBuilder`` option to customize the query when using an array:: 'Authors' => [ 'foreignKey' => false, 'queryBuilder' => function (Query $q) { - return $q->where(...); // Full conditions for filtering + return $q->where(/* ... */); // Full conditions for filtering } ] ]); diff --git a/en/orm/validation.rst b/en/orm/validation.rst index a3693a0e02..e0b3aed99c 100644 --- a/en/orm/validation.rst +++ b/en/orm/validation.rst @@ -578,7 +578,7 @@ those rules into re-usable classes:: // Add the custom rule use App\Model\Rule\CustomRule; - $rules->add(new CustomRule(...), 'ruleName'); + $rules->add(new CustomRule(/* ... */), 'ruleName'); By creating custom rule classes you can keep your code DRY and tests your domain rules in isolation. diff --git a/fr/core-libraries/httpclient.rst b/fr/core-libraries/httpclient.rst index c59419841e..ccd6f59fdb 100644 --- a/fr/core-libraries/httpclient.rst +++ b/fr/core-libraries/httpclient.rst @@ -46,9 +46,9 @@ Faire des requêtes POST et PUT est tout aussi simple:: ]); // Autres méthodes. - $http->delete(...); - $http->head(...); - $http->patch(...); + $http->delete(/* ... */); + $http->head(/* ... */); + $http->patch(/* ... */); Si vous avez créé un objet de requêtes PSR-7, vous pouvez l'envoyer avec ``sendRequest()``:: @@ -521,11 +521,11 @@ requêtes faites par votre application:: Il existe des méthodes pour mocker les méthodes HTTP les plus courantes:: - $this->mockClientGet(...); - $this->mockClientPatch(...); - $this->mockClientPost(...); - $this->mockClientPut(...); - $this->mockClientDelete(...); + $this->mockClientGet(/* ... */); + $this->mockClientPatch(/* ... */); + $this->mockClientPost(/* ... */); + $this->mockClientPut(/* ... */); + $this->mockClientDelete(/* ... */); .. php:method:: newClientResponse(int $code = 200, array $headers = [], string $body = '') diff --git a/fr/orm/query-builder.rst b/fr/orm/query-builder.rst index 4e44be3748..287435d421 100644 --- a/fr/orm/query-builder.rst +++ b/fr/orm/query-builder.rst @@ -481,7 +481,7 @@ des expressions complexes:: Pour construire des clauses de tri complexes, utilisez une Closure:: $query->orderAsc(function (QueryExpression $exp, Query $query) { - return $exp->addCase(...); + return $exp->addCase(/* ... */); }); Limiter les Résultats diff --git a/fr/orm/retrieving-data-and-resultsets.rst b/fr/orm/retrieving-data-and-resultsets.rst index 5458c77395..b7fb7978e9 100644 --- a/fr/orm/retrieving-data-and-resultsets.rst +++ b/fr/orm/retrieving-data-and-resultsets.rst @@ -667,7 +667,7 @@ passez un tableau:: 'Authors' => [ 'foreignKey' => false, 'queryBuilder' => function (Query $q) { - return $q->where(...); // Conditions complètes pour le filtrage + return $q->where(/* ... */); // Conditions complètes pour le filtrage } ] ]); diff --git a/fr/orm/validation.rst b/fr/orm/validation.rst index bff226fbdf..7e9ee43c8b 100644 --- a/fr/orm/validation.rst +++ b/fr/orm/validation.rst @@ -614,7 +614,7 @@ utile de packager ces règles dans des classes réutilisables:: // Ajouter la règle personnalisée use App\Model\Rule\CustomRule; - $rules->add(new CustomRule(...), 'ruleName'); + $rules->add(new CustomRule(/* ... */), 'ruleName'); En ajoutant des classes de règles personnalisées, vous pouvez garder votre code DRY et tester vos règles de domaine isolément. diff --git a/ja/contributing/cakephp-coding-conventions.rst b/ja/contributing/cakephp-coding-conventions.rst index 4710962427..3fb88e7023 100644 --- a/ja/contributing/cakephp-coding-conventions.rst +++ b/ja/contributing/cakephp-coding-conventions.rst @@ -254,7 +254,7 @@ false を、関数呼び出しが成功したかどうかを判定できるよ { ... if (!$success) { - throw new RuntimeException(...); + throw new RuntimeException(/* ... */); } ... diff --git a/ja/core-libraries/httpclient.rst b/ja/core-libraries/httpclient.rst index ec1e68190f..6a54a9c076 100644 --- a/ja/core-libraries/httpclient.rst +++ b/ja/core-libraries/httpclient.rst @@ -52,9 +52,9 @@ POST や PUT のリクエストを実行することは、同様に簡単です ]); // 他のメソッドも同様に、 - $http->delete(...); - $http->head(...); - $http->patch(...); + $http->delete(/* ... */); + $http->head(/* ... */); + $http->patch(/* ... */); If you have created a PSR-7 request object you can send it using ``sendRequest()``:: @@ -515,11 +515,11 @@ is making:: There are methods to mock the most commonly used HTTP methods:: - $this->mockClientGet(...); - $this->mockClientPatch(...); - $this->mockClientPost(...); - $this->mockClientPut(...); - $this->mockClientDelete(...); + $this->mockClientGet(/* ... */); + $this->mockClientPatch(/* ... */); + $this->mockClientPost(/* ... */); + $this->mockClientPut(/* ... */); + $this->mockClientDelete(/* ... */); .. php:method:: newClientResponse(int $code = 200, array $headers = [], string $body = '') diff --git a/ja/orm/retrieving-data-and-resultsets.rst b/ja/orm/retrieving-data-and-resultsets.rst index e793cdc806..f47afa4ef4 100644 --- a/ja/orm/retrieving-data-and-resultsets.rst +++ b/ja/orm/retrieving-data-and-resultsets.rst @@ -596,7 +596,7 @@ contain に条件を渡す 'Authors' => [ 'foreignKey' => false, 'queryBuilder' => function (Query $q) { - return $q->where(...); // フィルターのための完全な条件 + return $q->where(/* ... */); // フィルターのための完全な条件 } ] ]); diff --git a/ja/orm/validation.rst b/ja/orm/validation.rst index 21615783d9..0ca5e985aa 100644 --- a/ja/orm/validation.rst +++ b/ja/orm/validation.rst @@ -566,7 +566,7 @@ CakePHP は、エンティティーが保存される前に適用される「ル // カスタムルールの追加 use App\Model\Rule\CustomRule; - $rules->add(new CustomRule(...), 'ruleName'); + $rules->add(new CustomRule(/* ... */), 'ruleName'); カスタムルールクラスを作ることでコードを *重複がない状態* (訳注:DRY = Don't Repeat Yourself の訳) @@ -610,7 +610,7 @@ CakePHP の ORM は検証に二層のアプローチを使う点がユニーク public function validationCustomName($validator) { - $validator->add(...); + $validator->add(/* ... */); return $validator; } diff --git a/pt/core-libraries/httpclient.rst b/pt/core-libraries/httpclient.rst index fbe7cd3855..3b7bc2c66a 100644 --- a/pt/core-libraries/httpclient.rst +++ b/pt/core-libraries/httpclient.rst @@ -45,9 +45,9 @@ Fazer solicitações POST e PUT é igualmente simples:: ]); // Outros métodos também. - $http->delete(...); - $http->head(...); - $http->patch(...); + $http->delete(/* ... */); + $http->head(/* ... */); + $http->patch(/* ... */); Se você criou um objeto de solicitação PSR-7, pode enviá-lo usando ``sendRequest()``:: diff --git a/pt/orm/query-builder.rst b/pt/orm/query-builder.rst index 96c9002793..136532b765 100644 --- a/pt/orm/query-builder.rst +++ b/pt/orm/query-builder.rst @@ -666,7 +666,7 @@ criam novos objetos de expressão que mudam **como** as condições são combina segundo tipo de métodos são **condições**. As condições são adicionadas a uma expressão em que são alinhadas com o combinador atual. -Por exemplo, chamar ``$exp->and_(...)`` criará um novo objeto ``Expression`` que +Por exemplo, chamar ``$exp->and_(/* ... */)`` criará um novo objeto ``Expression`` que combina todas as condições que ele contém com ``AND``. Enquanto ``$exp->or_()`` criará um novo objeto ``Expression`` que combina todas as condições adicionadas a ele com ``OR``. Um exemplo de adição de condições com um objeto ``Expression`` seria:: diff --git a/pt/orm/retrieving-data-and-resultsets.rst b/pt/orm/retrieving-data-and-resultsets.rst index da92145a55..1170b8dc26 100644 --- a/pt/orm/retrieving-data-and-resultsets.rst +++ b/pt/orm/retrieving-data-and-resultsets.rst @@ -568,7 +568,7 @@ case you should use an array passing ``foreignKey`` and ``queryBuilder``:: 'Authors' => [ 'foreignKey' => false, 'queryBuilder' => function ($q) { - return $q->where(...); // Full conditions for filtering + return $q->where(/* ... */); // Full conditions for filtering } ] ]); From a80c0313a91ad7a89eadd4c9d645cfac81a34566 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Fri, 3 May 2024 13:52:20 -0400 Subject: [PATCH 45/68] Fix build --- en/appendices/migration-guides.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/en/appendices/migration-guides.rst b/en/appendices/migration-guides.rst index 3c10b43490..a3413c6341 100644 --- a/en/appendices/migration-guides.rst +++ b/en/appendices/migration-guides.rst @@ -14,3 +14,4 @@ each version and the migration path between 3.x and 4.x. ./4-3-migration-guide ./4-4-migration-guide ./4-5-migration-guide + ./4-6-migration-guide From 355cdc309c3b5ca35d139df160cae30aa3d503c0 Mon Sep 17 00:00:00 2001 From: Arhell Date: Wed, 8 May 2024 00:32:05 +0300 Subject: [PATCH 46/68] Update form.rst (fr, ja sync) --- fr/views/helpers/form.rst | 4 ++-- ja/views/helpers/form.rst | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/fr/views/helpers/form.rst b/fr/views/helpers/form.rst index 8a146aa7f9..954eecbc63 100644 --- a/fr/views/helpers/form.rst +++ b/fr/views/helpers/form.rst @@ -1847,12 +1847,12 @@ plusieurs messages d'erreur pour un seul champ. Exemple:: - // Si vous avez une règle de validation 'notEmpty' dans TicketsTable: + // Si vous avez une règle de validation 'notEmptyString' dans TicketsTable: public function validationDefault(Validator $validator): Validator { $validator ->requirePresence('ticket', 'create') - ->notEmpty('ticket'); + ->notEmptyString('ticket'); } // Et dans templates/Tickets/add.php vous avez: diff --git a/ja/views/helpers/form.rst b/ja/views/helpers/form.rst index 12093fa09c..27f5184379 100644 --- a/ja/views/helpers/form.rst +++ b/ja/views/helpers/form.rst @@ -1877,12 +1877,12 @@ FormHelper は、フィールドエラーを簡単にチェックしたり、必 例:: - // TicketsTable に 'notEmpty' 検証ルールがある場合: + // TicketsTable に 'notEmptyString' 検証ルールがある場合: public function validationDefault(Validator $validator) { $validator ->requirePresence('ticket', 'create') - ->notEmpty('ticket'); + ->notEmptyString('ticket'); } // そして、 templates/Tickets/add.php の中が次のような場合: From 6c20b2b8d1788e39e9f7a304dafd57d03093cc66 Mon Sep 17 00:00:00 2001 From: Arhell Date: Thu, 9 May 2024 17:53:38 +0300 Subject: [PATCH 47/68] Fix docs about plugin class name (fr, ja sync) --- fr/plugins.rst | 4 ++-- ja/plugins.rst | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/fr/plugins.rst b/fr/plugins.rst index 47463e9e1e..f6e5b9c528 100644 --- a/fr/plugins.rst +++ b/fr/plugins.rst @@ -142,7 +142,7 @@ Configuration du Plugin Les plugins proposent plusieurs *hooks* permettant à un plugin de s'injecter lui-même aux endroits appropriés de votre application. Les *hooks* sont: - + * ``bootstrap`` Utilisé pour charger les fichiers de configuration par défaut d'un plugin, définir des constantes et d'autres fonctions globales. * ``routes`` Utilisé pour charger les routes pour un plugin. Il est déclenché @@ -299,7 +299,7 @@ Plugin Objects Les Objets Plugin permettent à un auteur de plugin de spécifier une logique de démarrage, de définire des *hooks* par défaut, de charger des routes, un middleware ou des commandes de console. Les objets Plugin se trouvent dans -**src/Plugin.php**. Pour notre plugin ContactManager, notre classe de plugin +**src/{PluginName}Plugin.php**. Pour notre plugin ContactManager, notre classe de plugin pourrait ressembler à:: namespace ContactManager; diff --git a/ja/plugins.rst b/ja/plugins.rst index baf88ea003..d0885e7e63 100644 --- a/ja/plugins.rst +++ b/ja/plugins.rst @@ -284,7 +284,7 @@ Plugin オブジェクト Plugin オブジェクトを使用すると、プラグイン作成者は設定ロジックを定義し、 デフォルトのフックを定義し、ルート、ミドルウェア、およびコンソールコマンドをロードできます。 -Plugin オブジェクトは、 **src/Plugin.php** にあります。 +Plugin オブジェクトは、 **src/{PluginName}Plugin.php** にあります。 ContactManager プラグイン の場合、 plugin クラスは、次のようになります。 :: namespace ContactManager; From cecfa2a20ac7705875376dba880969c16bd994e2 Mon Sep 17 00:00:00 2001 From: Arhell Date: Sat, 11 May 2024 11:30:13 +0300 Subject: [PATCH 48/68] Fix syntax error in code sample (fr) --- fr/orm/database-basics.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr/orm/database-basics.rst b/fr/orm/database-basics.rst index 93d6721a92..1a19caf8db 100644 --- a/fr/orm/database-basics.rst +++ b/fr/orm/database-basics.rst @@ -606,7 +606,7 @@ spécifique:: $data = $schema->getColumn($column); $sql = $driver->quoteIdentifier($column); $sql .= ' JSON'; - if (isset($data['null') && $data['null'] === false) { + if (isset($data['null']) && $data['null'] === false) { $sql .= ' NOT NULL'; } return $sql; From 96b23542c65aa3ffdc1e639cdb8b6228878021e8 Mon Sep 17 00:00:00 2001 From: "marc.wuerth" Date: Mon, 13 May 2024 10:21:28 +0200 Subject: [PATCH 49/68] Add blank line before return statements in examples --- en/controllers.rst | 1 + en/controllers/components/authentication.rst | 3 + en/core-libraries/events.rst | 1 + en/core-libraries/validation.rst | 11 ++- en/development/routing.rst | 14 +-- en/development/sessions.rst | 1 + en/development/testing.rst | 1 + en/orm/database-basics.rst | 5 + en/orm/retrieving-data-and-resultsets.rst | 1 + en/orm/validation.rst | 1 + en/tutorials-and-examples/blog/part-three.rst | 2 + en/tutorials-and-examples/bookmarks/intro.rst | 1 + .../bookmarks/part-two.rst | 2 + .../cms/tags-and-users.rst | 1 + es/controllers.rst | 95 ++++++++++--------- es/tutorials-and-examples/blog/part-three.rst | 2 + .../bookmarks/part-two.rst | 2 + fr/controllers.rst | 1 + fr/controllers/components/authentication.rst | 3 + .../components/request-handling.rst | 1 + fr/core-libraries/events.rst | 1 + fr/core-libraries/validation.rst | 1 + fr/development/routing.rst | 2 + fr/development/sessions.rst | 1 + fr/development/testing.rst | 1 + fr/orm/database-basics.rst | 5 + fr/orm/retrieving-data-and-resultsets.rst | 1 + fr/orm/validation.rst | 1 + fr/tutorials-and-examples/blog/part-three.rst | 2 + .../bookmarks/part-two.rst | 2 + .../cms/tags-and-users.rst | 1 + ja/controllers.rst | 2 + ja/controllers/components/authentication.rst | 3 + ja/core-libraries/events.rst | 2 + ja/core-libraries/validation.rst | 1 + ja/development/routing.rst | 2 + ja/development/sessions.rst | 1 + ja/development/testing.rst | 2 + ja/orm/database-basics.rst | 4 + ja/orm/query-builder.rst | 1 + ja/orm/retrieving-data-and-resultsets.rst | 1 + ja/orm/table-objects.rst | 1 + ja/orm/validation.rst | 4 + ja/tutorials-and-examples/blog/part-three.rst | 2 + .../bookmarks/part-two.rst | 2 + .../cms/tags-and-users.rst | 3 + .../cakephp-coding-conventions.rst | 2 + pt/controllers.rst | 2 + pt/controllers/components/authentication.rst | 3 + .../components/request-handling.rst | 1 + pt/core-libraries/events.rst | 1 + pt/development/routing.rst | 2 + pt/development/sessions.rst | 1 + pt/development/testing.rst | 1 + pt/orm/database-basics.rst | 4 + pt/orm/retrieving-data-and-resultsets.rst | 1 + pt/tutorials-and-examples/blog/part-three.rst | 2 + .../bookmarks/part-two.rst | 2 + 58 files changed, 162 insertions(+), 58 deletions(-) diff --git a/en/controllers.rst b/en/controllers.rst index ee4d43a158..293a346024 100644 --- a/en/controllers.rst +++ b/en/controllers.rst @@ -385,6 +385,7 @@ You can redirect using :term:`routing array` values:: Or using a relative or absolute URL:: return $this->redirect('/orders/confirm'); + return $this->redirect('http://www.example.com'); Or to the referer page:: diff --git a/en/controllers/components/authentication.rst b/en/controllers/components/authentication.rst index b5ea2ef285..23d7089b42 100644 --- a/en/controllers/components/authentication.rst +++ b/en/controllers/components/authentication.rst @@ -316,6 +316,7 @@ an array of user information on the success or ``false`` on failure. :: if (empty($username) || empty($pass)) { return false; } + return $this->_findUser($username, $pass); } @@ -382,6 +383,7 @@ generate these API tokens randomly using libraries from CakePHP:: // it during login. $entity->api_key = $hasher->hash($entity->api_key_plain); } + return true; } } @@ -699,6 +701,7 @@ function accordingly:: $user->password = $this->request->getData('password'); $this->Users->save($user); } + return $this->redirect($this->Auth->redirectUrl()); } ... diff --git a/en/core-libraries/events.rst b/en/core-libraries/events.rst index 4d840388c5..64c39201d4 100644 --- a/en/core-libraries/events.rst +++ b/en/core-libraries/events.rst @@ -69,6 +69,7 @@ has been created. To keep your Orders model clean you could use events:: return true; } + return false; } } diff --git a/en/core-libraries/validation.rst b/en/core-libraries/validation.rst index cc9f35f0f8..94f0e2b5a1 100644 --- a/en/core-libraries/validation.rst +++ b/en/core-libraries/validation.rst @@ -289,6 +289,7 @@ conditions only:: if (isset($context['data']['action'])) { return $context['data']['action'] === 'subscribe'; } + return false; }); $validator->requirePresence('email'); @@ -565,10 +566,10 @@ following:: Validating Entity Data ====================== -Validation is meant for checking request data coming from forms or other user +Validation is meant for checking request data coming from forms or other user interfaces used to populate the entities. -The request data is validated automatically when using the ``newEntity()``, +The request data is validated automatically when using the ``newEntity()``, ``newEntities()``, ``patchEntity()`` or ``patchEntities()`` methods of ``Table`` class:: // In the ArticlesController class @@ -601,9 +602,9 @@ validation sets to apply using the ``options`` parameter:: ] ]); -Apart from validating user provided data maintaining integrity of data regardless -where it came from is important. To solve this problem CakePHP offers a second -level of validation which is called "application rules". You can read more about +Apart from validating user provided data maintaining integrity of data regardless +where it came from is important. To solve this problem CakePHP offers a second +level of validation which is called "application rules". You can read more about them in the :ref:`Applying Application Rules ` section. Core Validation Rules diff --git a/en/development/routing.rst b/en/development/routing.rst index 8284f23351..74489f74cf 100644 --- a/en/development/routing.rst +++ b/en/development/routing.rst @@ -1102,17 +1102,17 @@ Would create read only resource routes. The route names are ``create``, The default **route name and controller action used** are as follows: =========== ======================= -Route name Controller action used +Route name Controller action used =========== ======================= -create add +create add ----------- ----------------------- -update edit +update edit ----------- ----------------------- -view view +view view ----------- ----------------------- -index index +index index ----------- ----------------------- -delete delete +delete delete =========== ======================= @@ -1679,6 +1679,7 @@ URL filters allow you to implement features like persistent parameters:: if ($request->getParam('lang') && !isset($params['lang'])) { $params['lang'] = $request->getParam('lang'); } + return $params; }); @@ -1697,6 +1698,7 @@ example):: $params['language'] = $params[0]; unset($params[0]); } + return $params; }); diff --git a/en/development/sessions.rst b/en/development/sessions.rst index 9fd2045161..062c1dacb2 100644 --- a/en/development/sessions.rst +++ b/en/development/sessions.rst @@ -296,6 +296,7 @@ something like:: if ($result) { return $result; } + return parent::read($id); } diff --git a/en/development/testing.rst b/en/development/testing.rst index c9b7358c30..d06663c6fb 100644 --- a/en/development/testing.rst +++ b/en/development/testing.rst @@ -1926,6 +1926,7 @@ Expanding on the Orders example, say we have the following tables:: return true; } + return false; } } diff --git a/en/orm/database-basics.rst b/en/orm/database-basics.rst index 3481982a77..0729efca0f 100644 --- a/en/orm/database-basics.rst +++ b/en/orm/database-basics.rst @@ -491,6 +491,7 @@ class:: if ($value === null) { return null; } + return json_decode($value, true); } @@ -499,6 +500,7 @@ class:: if (is_array($value) || $value === null) { return $value; } + return json_decode($value, true); } @@ -512,6 +514,7 @@ class:: if ($value === null) { return PDO::PARAM_NULL; } + return PDO::PARAM_STR; } } @@ -586,6 +589,7 @@ used:: if (isset($data['null') && $data['null'] === false) { $sql .= ' NOT NULL'; } + return $sql; } @@ -693,6 +697,7 @@ value object and into SQL expressions:: if (is_array($value)) { return new Point($value[0], $value[1]); } + return null; } diff --git a/en/orm/retrieving-data-and-resultsets.rst b/en/orm/retrieving-data-and-resultsets.rst index 3a98a8190e..334db67526 100644 --- a/en/orm/retrieving-data-and-resultsets.rst +++ b/en/orm/retrieving-data-and-resultsets.rst @@ -1000,6 +1000,7 @@ extract a list of unique tags on a collection of articles by running:: if (!in_array($value, $output)) { $output[] = $value; } + return $output; }; diff --git a/en/orm/validation.rst b/en/orm/validation.rst index 6151380217..b198bc6d00 100644 --- a/en/orm/validation.rst +++ b/en/orm/validation.rst @@ -227,6 +227,7 @@ You can also use closures for validation rules:: if ($value > 1) { return true; } + return 'Not a good value.'; } ]); diff --git a/en/tutorials-and-examples/blog/part-three.rst b/en/tutorials-and-examples/blog/part-three.rst index 35ed4fb85e..268a5cc9a6 100644 --- a/en/tutorials-and-examples/blog/part-three.rst +++ b/en/tutorials-and-examples/blog/part-three.rst @@ -266,6 +266,7 @@ the tree:: } else { $this->Flash->error('The category could not be moved up. Please, try again.'); } + return $this->redirect($this->referer(['action' => 'index'])); } @@ -278,6 +279,7 @@ the tree:: } else { $this->Flash->error('The category could not be moved down. Please, try again.'); } + return $this->redirect($this->referer(['action' => 'index'])); } } diff --git a/en/tutorials-and-examples/bookmarks/intro.rst b/en/tutorials-and-examples/bookmarks/intro.rst index 707be8fdff..409ac79ef7 100644 --- a/en/tutorials-and-examples/bookmarks/intro.rst +++ b/en/tutorials-and-examples/bookmarks/intro.rst @@ -414,6 +414,7 @@ method has not been implemented yet, so let's do that. In ->where(['Tags.title IN ' => $options['tags']]) ->group(['Bookmarks.id']); } + return $query; } diff --git a/en/tutorials-and-examples/bookmarks/part-two.rst b/en/tutorials-and-examples/bookmarks/part-two.rst index c66f6f77a3..1f06c73bc0 100644 --- a/en/tutorials-and-examples/bookmarks/part-two.rst +++ b/en/tutorials-and-examples/bookmarks/part-two.rst @@ -202,6 +202,7 @@ sense. First, we'll add the authorization logic for bookmarks. In your if ($bookmark->user_id == $user['id']) { return true; } + return parent::isAuthorized($user); } @@ -396,6 +397,7 @@ to **src/Model/Table/BookmarksTable.php**:: foreach ($newTags as $tag) { $out[] = $this->Tags->newEntity(['title' => $tag]); } + return $out; } diff --git a/en/tutorials-and-examples/cms/tags-and-users.rst b/en/tutorials-and-examples/cms/tags-and-users.rst index c32bae7067..71457a1a9a 100644 --- a/en/tutorials-and-examples/cms/tags-and-users.rst +++ b/en/tutorials-and-examples/cms/tags-and-users.rst @@ -444,6 +444,7 @@ to **src/Model/Table/ArticlesTable.php**:: foreach ($newTags as $tag) { $out[] = $this->Tags->newEntity(['title' => $tag]); } + return $out; } diff --git a/es/controllers.rst b/es/controllers.rst index 0e993037f2..34b8fb1eda 100644 --- a/es/controllers.rst +++ b/es/controllers.rst @@ -5,38 +5,38 @@ Controladores .. php:class:: Controller -Los controladores son la 'C' en MVC. Después de aplicar el enrutamiento y +Los controladores son la 'C' en MVC. Después de aplicar el enrutamiento y que el controlador ha sido encontrado, la acción de tu controlador es llamado. Tu controlador -debe manejar la interpretación de los datos de la solicitud, +debe manejar la interpretación de los datos de la solicitud, asegurándose de que se llamen -a los modelos correctos y se muestre la respuesta o vista correcta. +a los modelos correctos y se muestre la respuesta o vista correcta. Los controladores se pueden considerar como una capa intermedia entre el Modelo y la Vista. Quieres mantener -tus controladores delgados, y tus modelos gruesos. +tus controladores delgados, y tus modelos gruesos. Esto te ayudará a reutilizar tu código y lo hará mas fácil de probar. -Comúnmente, un controlador se usa para administrar la lógica en torno +Comúnmente, un controlador se usa para administrar la lógica en torno a un solo modelo. Por -ejemplo, si estuvieras construyendo un sitio online para una panadería, +ejemplo, si estuvieras construyendo un sitio online para una panadería, podrías tener un -RecipesController que gestiona tus recetas y un IngredientsController +RecipesController que gestiona tus recetas y un IngredientsController que gestiona tus -ingredientes. Sin embargo, es posible hacer que los controladores trabajen -con más de +ingredientes. Sin embargo, es posible hacer que los controladores trabajen +con más de un modelo. En CakePHP, un controlador es nombrado a raíz del modelo que maneja. Los controladores de tu aplicación extienden de la clase ``AppController``, que a su vez extiende de la clase principal :php:class:`Controller`. La clase ``AppController`` puede ser definida en **src/Controller/AppController.php** -y debería contener los métodos que se comparten entre todos los controladores +y debería contener los métodos que se comparten entre todos los controladores de tu aplicación. Los controladores proveen una serie de métodos que manejan las peticiones. Estos son llamadas *acciones*. Por defecto, cada método público en un controlador es -una acción, y es accesible mediante una URL. Una acción es responsable de +una acción, y es accesible mediante una URL. Una acción es responsable de interpretar la petición y crear la respuesta. Por lo general, las respuestas -son de la forma de una vista renderizada, pero también, hay otras maneras de crear +son de la forma de una vista renderizada, pero también, hay otras maneras de crear respuestas. .. _app-controller: @@ -44,10 +44,10 @@ respuestas. El App Controller ================== -Como se indicó en la introducción, la clase ``AppController`` es clase padre de +Como se indicó en la introducción, la clase ``AppController`` es clase padre de todos los controladores de tu aplicación. ``AppController`` extiende de la clase :php:class:`Cake\\Controller\\Controller` que está incluida en CakePHP. -``AppController`` se define en **src/Controller/AppController.php** como se +``AppController`` se define en **src/Controller/AppController.php** como se muestra a continuación:: namespace App\Controller; @@ -58,7 +58,7 @@ muestra a continuación:: { } -Los atributos y métodos del controlador creados en tu ``AppController`` van a +Los atributos y métodos del controlador creados en tu ``AppController`` van a estar disponibles en todos los controladores que extiendan de este. Los componentes (que aprenderás más adelante) son mejor usados para código que se encuentra en muchos (pero no necesariamente en todos) los componentes. @@ -66,7 +66,7 @@ encuentra en muchos (pero no necesariamente en todos) los componentes. Puedes usar tu ``AppController`` para cargar componentes que van a ser utilizados en cada controlador de tu aplicación. CakePHP proporciona un método ``initialize()`` que es llamado al final del constructor de un controlador para este tipo de uso:: - + namespace App\Controller; use Cake\Controller\Controller; @@ -83,11 +83,11 @@ que es llamado al final del constructor de un controlador para este tipo de uso: Flujo de solicitud ================== -Cuando se realiza una solicitud a una aplicación CakePHP, las clases CakePHP +Cuando se realiza una solicitud a una aplicación CakePHP, las clases CakePHP :php:class:`Cake\\Routing\\Router` y :php:class:`Cake\\Routing\\Dispatcher` -usan :ref:`routes-configuration` para encontrar y crear la instancia correcta -del controlador. Los datos de la solicitud son encapsulados en un objeto de -solicitud. CakePHP pone toda la información importante de la solicitud en la +usan :ref:`routes-configuration` para encontrar y crear la instancia correcta +del controlador. Los datos de la solicitud son encapsulados en un objeto de +solicitud. CakePHP pone toda la información importante de la solicitud en la propiedad ``$this->request``. Consulta la sección sobre :ref:`cake-request` para obtener más información sobre el objeto de solicitud de CakePHP. @@ -95,14 +95,14 @@ Acciones del controlador ======================== Las acciones del controlador son las responsables de convertir los parámetros -de la solicitud en una respuesta para el navegador/usuario que realiza la +de la solicitud en una respuesta para el navegador/usuario que realiza la petición. CakePHP usa convenciones para automatizar este proceso y eliminar algunos códigos repetitivos que de otro modo se necesitaría escribir. -Por convención, CakePHP renderiza una vista con una versión en infinitivo del nombre -de la acción. Volviendo a nuestro ejemplo de la panadería online, nuestro -RecipesController podría contener las acciones ``view()``, ``share()``, y -``search()``. El controlador sería encontrado en +Por convención, CakePHP renderiza una vista con una versión en infinitivo del nombre +de la acción. Volviendo a nuestro ejemplo de la panadería online, nuestro +RecipesController podría contener las acciones ``view()``, ``share()``, y +``search()``. El controlador sería encontrado en **src/Controller/RecipesController.php** y contiene:: // src/Controller/RecipesController.php @@ -139,7 +139,7 @@ CakePHP se encargará de renderizar y entregar la vista. Si por algún motivo deseas omitir el comportamiento predeterminado, puedes retornar un objeto :php:class:`Cake\\Http\\Response` de la acción con la respuesta creada. -Para que puedas usar un controlador de manera efectiva en tu aplicación, +Para que puedas usar un controlador de manera efectiva en tu aplicación, cubriremos algunos de los atributos y métodos principales proporcionados por los controladores de CakePHP. @@ -148,7 +148,7 @@ Interactuando con vistas Los controladores interactúan con las vistas de muchas maneras. Primero, los controladores son capaces de pasar información a las vistas, usando ``Controller::set()``. -También puedes decidir qué clase de vista usar, y qué archivo de vista debería +También puedes decidir qué clase de vista usar, y qué archivo de vista debería ser renderizado desde el controlador. .. _setting-view_variables: @@ -158,7 +158,7 @@ Configuración de variables de vista .. php:method:: set(string $var, mixed $value) -El método ``Controller::set()`` es la manera principal de mandar información +El método ``Controller::set()`` es la manera principal de mandar información desde el controlador a la vista. Una vez que hayas utilizado ``Controller::set()``, la variable puede ser accedida en tu vista:: @@ -172,7 +172,7 @@ la variable puede ser accedida en tu vista:: Has seleccionado cubierta para la tarta. El método ``Controller::set()`` también toma un array asociativo como su primer -parámetro. A menudo, esto puede ser una forma rápida de asignar un conjunto de +parámetro. A menudo, esto puede ser una forma rápida de asignar un conjunto de información a la vista:: $data = [ @@ -218,7 +218,7 @@ coloca la vista dentro de su ``View::$layout``, y lo devuelve al usuario final. El archivo de vista por defecto utilizado para el renderizado es definido por convención. -Si la acción ``search()`` de RecipesController es solicitada, el archivo vista en +Si la acción ``search()`` de RecipesController es solicitada, el archivo vista en **templates/Recipes/search.php** será renderizado:: namespace App\Controller; @@ -234,8 +234,8 @@ Si la acción ``search()`` de RecipesController es solicitada, el archivo vista // ... } -Aunque CakePHP va a llamarlo automáticamente después de cada acción de lógica -(a menos que llames a ``$this->disableAutoRender()``), puedes usarlo para +Aunque CakePHP va a llamarlo automáticamente después de cada acción de lógica +(a menos que llames a ``$this->disableAutoRender()``), puedes usarlo para especificar un archivo de vista alternativo especificando el nombre de este como primer argumento del método ``Controller::render()``. @@ -254,7 +254,7 @@ Renderizando una plantilla específica En tu controlador, puede que quieras renderizar una vista diferente a la que es convencional. Puedes hacer esto llamando a ``Controller::render()`` directamente. -Una vez que hayas llamado a ``Controller::render()``, CakePHP no tratará de +Una vez que hayas llamado a ``Controller::render()``, CakePHP no tratará de re-renderizar la vista:: namespace App\Controller; @@ -267,7 +267,7 @@ re-renderizar la vista:: } } -Esto renderizará **templates/Posts/custom_file.php** en vez de +Esto renderizará **templates/Posts/custom_file.php** en vez de **templates/Posts/my_action.php**. También puedes renderizar vistas dentro de plugins usando la siguiente sintaxis: @@ -292,10 +292,10 @@ Negociación del tipo de contenido .. php:method:: viewClasses() -Los controladores pueden definir una lista de clases de vistas que soportan. -Después de que la acción del controlador este completa, CakePHP usará la lista de +Los controladores pueden definir una lista de clases de vistas que soportan. +Después de que la acción del controlador este completa, CakePHP usará la lista de vista para realizar negociación del tipo de contenido. Esto permite a tu aplicación -rehusar la misma acción del controlador para renderizar una vista HTML o +rehusar la misma acción del controlador para renderizar una vista HTML o renderizar una respuesta JSON o XML. Para definir la lista de clases de vista que soporta un controlador se utiliza el método ``viewClasses()``:: @@ -352,7 +352,7 @@ de vista alternativa:: } -Es importante recordar que las vistas coincidentes se aplican sólo *después* de +Es importante recordar que las vistas coincidentes se aplican sólo *después* de intentar la negociación del tipo de contenido. .. versionadded:: 4.4.0 @@ -385,6 +385,7 @@ Puedes redigir usando los valores de un array ordenado:: O usando una URL relativa o absoluta:: return $this->redirect('/orders/confirm'); + return $this->redirect('http://www.example.com'); O la referencia de la página:: @@ -418,7 +419,7 @@ Cargando modelos adicionales .. php:method:: fetchTable(string $alias, array $config = []) -La función ``fetchTable()`` es útil cuando se necesita usar una tabla que no es +La función ``fetchTable()`` es útil cuando se necesita usar una tabla que no es la predeterminada por el controlador:: // En un método del controlador. @@ -439,7 +440,7 @@ Paginación de un modelo Este método se utiliza para paginar los resultados obtenidos por tus modelos. Puedes especificar tamaño de páginas, condiciones de búsqueda del modelo y más. -El atributo ``$paginate`` te da una manera de personalizar cómo ``paginate()`` +El atributo ``$paginate`` te da una manera de personalizar cómo ``paginate()`` se comporta:: class ArticlesController extends AppController @@ -486,24 +487,24 @@ Lista de eventos Métodos de callback del controlador ================================================ -Por defecto, los siguientes métodos de callback están conectados a +Por defecto, los siguientes métodos de callback están conectados a eventos relacionados si los métodos son implementados por tus controladores. .. php:method:: beforeFilter(EventInterface $event) Llamado durante el evento ``Controller.initialize`` que ocurre antes de cada - acción en el controlador. Es un lugar útil para comprobar si hay una sesión + acción en el controlador. Es un lugar útil para comprobar si hay una sesión activa o inspeccionar los permisos del usuario. .. note:: El método beforeFilter() será llamado por acciones faltantes. - + Devolver una respuesta del método ``beforeFilter`` no evitará que otros oyentes del mismo evento sean llamados. Debes explícitamente parar el evento. .. php:method:: beforeRender(EventInterface $event) - Llamado durante el evento ``Controller.beforeRender`` que ocurre después + Llamado durante el evento ``Controller.beforeRender`` que ocurre después de la lógica de acción del controlador, pero antes de que la vista sea renderizada. Este callback no se usa con frecuencia, pero puede ser necesaria si estas llamando :php:meth:`~Cake\\Controller\\Controller::render()` de forma @@ -515,7 +516,7 @@ eventos relacionados si los métodos son implementados por tus controladores. de cada acción del controlador, y después de que se complete el renderizado. Este es el último método del controlador para ejecutar. -Además de las devoluciones de llamada del ciclo de vida del controlador, +Además de las devoluciones de llamada del ciclo de vida del controlador, :doc:`/controllers/components` también proporciona un conjunto similar de devoluciones de llamada. @@ -535,9 +536,9 @@ Middleware del controlador .. php:method:: middleware($middleware, array $options = []) -:doc:`Middleware ` puede ser definido globalmente, en +:doc:`Middleware ` puede ser definido globalmente, en un ámbito de enrutamiento o dentro de un controlador. Para definir el middleware -para un controlador en específico usa el método ``middleware()`` de tu método +para un controlador en específico usa el método ``middleware()`` de tu método ``initialize()`` del controlador:: public function initialize(): void diff --git a/es/tutorials-and-examples/blog/part-three.rst b/es/tutorials-and-examples/blog/part-three.rst index bfd543021f..7ec38038c6 100644 --- a/es/tutorials-and-examples/blog/part-three.rst +++ b/es/tutorials-and-examples/blog/part-three.rst @@ -159,6 +159,7 @@ para poder reordenar las categorías en ese árbol:: } else { $this->Flash->error('The category could not be moved up. Please, try again.'); } + return $this->redirect($this->referer(['action' => 'index'])); } @@ -171,6 +172,7 @@ para poder reordenar las categorías en ese árbol:: } else { $this->Flash->error('The category could not be moved down. Please, try again.'); } + return $this->redirect($this->referer(['action' => 'index'])); } } diff --git a/es/tutorials-and-examples/bookmarks/part-two.rst b/es/tutorials-and-examples/bookmarks/part-two.rst index 39ea6aa1b2..9e815ab793 100644 --- a/es/tutorials-and-examples/bookmarks/part-two.rst +++ b/es/tutorials-and-examples/bookmarks/part-two.rst @@ -225,6 +225,7 @@ En tu ``BookmarksController`` añade lo siguiente:: if ($bookmark->user_id == $user['id']) { return true; } + return parent::isAuthorized($user); } @@ -433,6 +434,7 @@ Añade el siguiente código a **src/Model/Table/BookmarksTable.php**:: foreach ($newTags as $tag) { $out[] = $this->Tags->newEntity(['title' => $tag]); } + return $out; } diff --git a/fr/controllers.rst b/fr/controllers.rst index 2d5e4eae00..7e90e2ac9b 100644 --- a/fr/controllers.rst +++ b/fr/controllers.rst @@ -368,6 +368,7 @@ vous pouvez rediriger en utilisant les valeurs du :term:`tableau de routing`:: Ou utiliser une URL relative ou absolue:: return $this->redirect('/orders/confirm'); + return $this->redirect('http://www.example.com'); Ou rediriger vers l'URL appelante (referer):: diff --git a/fr/controllers/components/authentication.rst b/fr/controllers/components/authentication.rst index 2e06f0d3fb..15bd92add6 100644 --- a/fr/controllers/components/authentication.rst +++ b/fr/controllers/components/authentication.rst @@ -341,6 +341,7 @@ en cas d'échec:: if (empty($username) || empty($pass)) { return false; } + return $this->_findUser($username, $pass); } @@ -411,6 +412,7 @@ de façon aléatoire ces tokens d'API en utilisant les libraries de CakePHP:: // it during login. $entity->api_key = $hasher->hash($entity->api_key_plain); } + return true; } } @@ -750,6 +752,7 @@ pouvez changer la fonction login selon:: $user->password = $this->request->getData('password'); $this->Users->save($user); } + return $this->redirect($this->Auth->redirectUrl()); } ... diff --git a/fr/controllers/components/request-handling.rst b/fr/controllers/components/request-handling.rst index 2268164c48..19900b372c 100644 --- a/fr/controllers/components/request-handling.rst +++ b/fr/controllers/components/request-handling.rst @@ -156,6 +156,7 @@ ajouter un gestionnaire de CSV pourrait ressembler à ceci:: foreach ($rows as &$row) { $row = str_getcsv($row, ','); } + return $rows; }; $this->loadComponent('RequestHandler', [ diff --git a/fr/core-libraries/events.rst b/fr/core-libraries/events.rst index d37f9b9e39..098b4039dd 100644 --- a/fr/core-libraries/events.rst +++ b/fr/core-libraries/events.rst @@ -79,6 +79,7 @@ garder votre model Orders propre, vous pouvez utiliser les événements:: return true; } + return false; } } diff --git a/fr/core-libraries/validation.rst b/fr/core-libraries/validation.rst index 06cde26584..0c13a8eadd 100644 --- a/fr/core-libraries/validation.rst +++ b/fr/core-libraries/validation.rst @@ -371,6 +371,7 @@ certaines conditions seulement:: if (isset($context['data']['action'])) { return $context['data']['action'] === 'subscribe'; } + return false; }); $validator->requirePresence('email'); diff --git a/fr/development/routing.rst b/fr/development/routing.rst index 90c52cb82d..a6da47dcfe 100644 --- a/fr/development/routing.rst +++ b/fr/development/routing.rst @@ -1756,6 +1756,7 @@ l'utilisation de paramètres d'URL persistants:: if ($request->getParam('lang') && !isset($params['lang'])) { $params['lang'] = $request->getParam('lang'); } + return $params; }); @@ -1775,6 +1776,7 @@ Un autre cas lorsque l'on souhaite changer une route en particulier à la volée $params['language'] = $params[0]; unset($params[0]); } + return $params; }); diff --git a/fr/development/sessions.rst b/fr/development/sessions.rst index a4e80e930f..9dd64a941c 100644 --- a/fr/development/sessions.rst +++ b/fr/development/sessions.rst @@ -280,6 +280,7 @@ devrait ressembler à:: if ($result) { return $result; } + return parent::read($id); } diff --git a/fr/development/testing.rst b/fr/development/testing.rst index ead8e15dda..0f75f03c86 100755 --- a/fr/development/testing.rst +++ b/fr/development/testing.rst @@ -1945,6 +1945,7 @@ suivantes:: return true; } + return false; } } diff --git a/fr/orm/database-basics.rst b/fr/orm/database-basics.rst index 93d6721a92..64e168ef2f 100644 --- a/fr/orm/database-basics.rst +++ b/fr/orm/database-basics.rst @@ -503,6 +503,7 @@ type JSON, nous pourrions créer la classe de type suivante:: if ($value === null) { return null; } + return json_decode($value, true); } @@ -511,6 +512,7 @@ type JSON, nous pourrions créer la classe de type suivante:: if (is_array($value) || $value === null) { return $value; } + return json_decode($value, true); } @@ -524,6 +526,7 @@ type JSON, nous pourrions créer la classe de type suivante:: if ($value === null) { return PDO::PARAM_NULL; } + return PDO::PARAM_STR; } @@ -609,6 +612,7 @@ spécifique:: if (isset($data['null') && $data['null'] === false) { $sql .= ' NOT NULL'; } + return $sql; } @@ -717,6 +721,7 @@ faire correspondre les données dans cet objet et les expressions SQL:: if (is_array($value)) { return new Point($value[0], $value[1]); } + return null; } diff --git a/fr/orm/retrieving-data-and-resultsets.rst b/fr/orm/retrieving-data-and-resultsets.rst index 1eec08024a..823908acc5 100644 --- a/fr/orm/retrieving-data-and-resultsets.rst +++ b/fr/orm/retrieving-data-and-resultsets.rst @@ -1051,6 +1051,7 @@ exécutant:: if (!in_array($value, $output)) { $output[] = $value; } + return $output; }; diff --git a/fr/orm/validation.rst b/fr/orm/validation.rst index fd06814f83..afe78570ea 100644 --- a/fr/orm/validation.rst +++ b/fr/orm/validation.rst @@ -240,6 +240,7 @@ Vous pouvez également utiliser des closures en tant que règles de validation:: if ($value > 1) { return true; } + return 'Valeur incorrecte.'; } ]); diff --git a/fr/tutorials-and-examples/blog/part-three.rst b/fr/tutorials-and-examples/blog/part-three.rst index 4339fbee7a..8bde440b32 100644 --- a/fr/tutorials-and-examples/blog/part-three.rst +++ b/fr/tutorials-and-examples/blog/part-three.rst @@ -277,6 +277,7 @@ catégories dans l'arbre:: } else { $this->Flash->error("La catégorie n'a pas pu être remontée. Veuillez réessayer."); } + return $this->redirect($this->referer(['action' => 'index'])); } @@ -289,6 +290,7 @@ catégories dans l'arbre:: } else { $this->Flash->error("La catégorie n'a pas pu être descendue. Veuillez réessayer."); } + return $this->redirect($this->referer(['action' => 'index'])); } } diff --git a/fr/tutorials-and-examples/bookmarks/part-two.rst b/fr/tutorials-and-examples/bookmarks/part-two.rst index 2df600334c..1f02d237f7 100644 --- a/fr/tutorials-and-examples/bookmarks/part-two.rst +++ b/fr/tutorials-and-examples/bookmarks/part-two.rst @@ -214,6 +214,7 @@ les bookmarks. Dans notre ``BookmarksController``, ajoutez ce qui suit:: if ($bookmark->user_id == $user['id']) { return true; } + return parent::isAuthorized($user); } @@ -415,6 +416,7 @@ chaîne de tag et trouver/construire les entities liées. Ajoutez ce qui suit da foreach ($newTags as $tag) { $out[] = $this->Tags->newEntity(['title' => $tag]); } + return $out; } diff --git a/fr/tutorials-and-examples/cms/tags-and-users.rst b/fr/tutorials-and-examples/cms/tags-and-users.rst index 7eee133a5f..a3fef29f87 100644 --- a/fr/tutorials-and-examples/cms/tags-and-users.rst +++ b/fr/tutorials-and-examples/cms/tags-and-users.rst @@ -454,6 +454,7 @@ trouver/construire les entities correspondantes. Ajoutez le code suivant à foreach ($newTags as $tag) { $out[] = $this->Tags->newEntity(['title' => $tag]); } + return $out; } diff --git a/ja/controllers.rst b/ja/controllers.rst index 9dfa32d7b0..1429805f9c 100644 --- a/ja/controllers.rst +++ b/ja/controllers.rst @@ -347,6 +347,7 @@ match-allビューは、content-typeのネゴシエーションが試みられ ['controller' => 'Orders', 'action' => 'thanks'] ); } + return $this->redirect( ['controller' => 'Orders', 'action' => 'confirm'] ); @@ -359,6 +360,7 @@ match-allビューは、content-typeのネゴシエーションが試みられ $url 引数に相対 URL または絶対 URL を指定することもできます。 :: return $this->redirect('/orders/thanks'); + return $this->redirect('http://www.example.com'); アクションにデータを渡すこともできます。 :: diff --git a/ja/controllers/components/authentication.rst b/ja/controllers/components/authentication.rst index a9c4572c7d..e50e2422f7 100644 --- a/ja/controllers/components/authentication.rst +++ b/ja/controllers/components/authentication.rst @@ -304,6 +304,7 @@ AuthComponent がユーザーレコードの格納にセッションを使用し if (empty($username) || empty($pass)) { return false; } + return $this->_findUser($username, $pass); } @@ -369,6 +370,7 @@ CakePHP のライブラリーを使用してランダムにこれらの API ト // トークンを Bcrypt で暗号化 $entity->api_key = $hasher->hash($entity->api_key_plain); } + return true; } } @@ -676,6 +678,7 @@ CakePHP は、1つのアルゴリズムから別のユーザーのパスワー $user->password = $this->request->getData('password'); $this->Users->save($user); } + return $this->redirect($this->Auth->redirectUrl()); } ... diff --git a/ja/core-libraries/events.rst b/ja/core-libraries/events.rst index 00fbeb47a0..baafd52c40 100644 --- a/ja/core-libraries/events.rst +++ b/ja/core-libraries/events.rst @@ -63,8 +63,10 @@ CakePHP は、jQuery などの一般的な JavaScript フレームワークに 'order' => $order ]); $this->getEventManager()->dispatch($event); + return true; } + return false; } } diff --git a/ja/core-libraries/validation.rst b/ja/core-libraries/validation.rst index 170729f76a..de9d3a1115 100644 --- a/ja/core-libraries/validation.rst +++ b/ja/core-libraries/validation.rst @@ -287,6 +287,7 @@ CakePHPは6つの異なる形状のデータに対して空の値のサポート if (isset($context['data']['action'])) { return $context['data']['action'] === 'subscribe'; } + return false; }); $validator->requirePresence('email'); diff --git a/ja/development/routing.rst b/ja/development/routing.rst index 717769aa20..5782751f7e 100644 --- a/ja/development/routing.rst +++ b/ja/development/routing.rst @@ -1437,6 +1437,7 @@ URL フィルターは永続的なパラメーターなどを簡単に扱う機 if ($request->getParam('lang') && !isset($params['lang'])) { $params['lang'] = $request->getParam('lang'); } + return $params; }); @@ -1454,6 +1455,7 @@ URL フィルターは永続的なパラメーターなどを簡単に扱う機 $params['language'] = $params[0]; unset($params[0]); } + return $params; }); diff --git a/ja/development/sessions.rst b/ja/development/sessions.rst index 65cd9289f0..2e02500c8c 100644 --- a/ja/development/sessions.rst +++ b/ja/development/sessions.rst @@ -258,6 +258,7 @@ IO をもたらします。 if ($result) { return $result; } + return parent::read($id); } diff --git a/ja/development/testing.rst b/ja/development/testing.rst index 75dd1a68a9..a8e9c9faaf 100644 --- a/ja/development/testing.rst +++ b/ja/development/testing.rst @@ -1769,8 +1769,10 @@ Orders を例に詳しく説明します。以下のテーブルを持ってい 'order' => $order ]); $this->getEventManager()->dispatch($event); + return true; } + return false; } } diff --git a/ja/orm/database-basics.rst b/ja/orm/database-basics.rst index c8072d236e..4e1b604837 100644 --- a/ja/orm/database-basics.rst +++ b/ja/orm/database-basics.rst @@ -443,6 +443,7 @@ Type クラスは次のメソッドを実装することが期待されます。 if ($value === null) { return null; } + return json_decode($value, true); } @@ -451,6 +452,7 @@ Type クラスは次のメソッドを実装することが期待されます。 if (is_array($value) || $value === null) { return $value; } + return json_decode($value, true); } @@ -464,6 +466,7 @@ Type クラスは次のメソッドを実装することが期待されます。 if ($value === null) { return PDO::PARAM_NULL; } + return PDO::PARAM_STR; } @@ -571,6 +574,7 @@ Type クラスが必要になります。 :: if (is_array($value)) { return new Point($value[0], $value[1]); } + return null; } diff --git a/ja/orm/query-builder.rst b/ja/orm/query-builder.rst index d8a4db13ab..d8f5e5aecb 100644 --- a/ja/orm/query-builder.rst +++ b/ja/orm/query-builder.rst @@ -572,6 +572,7 @@ CakePHP はフォーマッタ関数が適切なスコープになるよう保証 return $q->formatResults(function (\Cake\Collection\CollectionInterface $authors) { return $authors->map(function ($author) { $author['age'] = $author['birth_date']->diff(new \DateTime)->y; + return $author; }); }); diff --git a/ja/orm/retrieving-data-and-resultsets.rst b/ja/orm/retrieving-data-and-resultsets.rst index fafa2201f8..354268051b 100644 --- a/ja/orm/retrieving-data-and-resultsets.rst +++ b/ja/orm/retrieving-data-and-resultsets.rst @@ -921,6 +921,7 @@ serialize が簡単にできるだけでなく、結果セットは 'Collection' if (!in_array($value, $output)) { $output[] = $value; } + return $output; }; diff --git a/ja/orm/table-objects.rst b/ja/orm/table-objects.rst index 2250945e51..3541ccaa84 100644 --- a/ja/orm/table-objects.rst +++ b/ja/orm/table-objects.rst @@ -344,6 +344,7 @@ Stopping Table Events if (...) { $event->stopPropagation(); $event->setResult(false); + return; } ... diff --git a/ja/orm/validation.rst b/ja/orm/validation.rst index 410747ef7b..76bcd705a5 100644 --- a/ja/orm/validation.rst +++ b/ja/orm/validation.rst @@ -175,6 +175,7 @@ CakePHP ではデータの検証には二つの段階があります: $validator = $this->validationDefault($validator); $validator->add('password', 'length', ['rule' => ['lengthBetween', 8, 100]]); + return $validator; } @@ -226,6 +227,7 @@ CakePHP ではデータの検証には二つの段階があります: if ($value > 1) { return true; } + return '適切な値ではありません。'; } ]); @@ -538,6 +540,7 @@ CakePHP は、エンティティーが保存される前に適用される「ル 'errorField' => 'name', 'message' => 'Name must be unique per parent.' ]); + return $rules; } @@ -613,6 +616,7 @@ CakePHP の ORM は検証に二層のアプローチを使う点がユニーク public function validationCustomName($validator) { $validator->add(/* ... */); + return $validator; } diff --git a/ja/tutorials-and-examples/blog/part-three.rst b/ja/tutorials-and-examples/blog/part-three.rst index f75cfc1f93..e56ada8bfc 100644 --- a/ja/tutorials-and-examples/blog/part-three.rst +++ b/ja/tutorials-and-examples/blog/part-three.rst @@ -262,6 +262,7 @@ categories の index テンプレートファイルでは、categories を一覧 } else { $this->Flash->error('The category could not be moved up. Please, try again.'); } + return $this->redirect($this->referer(['action' => 'index'])); } @@ -274,6 +275,7 @@ categories の index テンプレートファイルでは、categories を一覧 } else { $this->Flash->error('The category could not be moved down. Please, try again.'); } + return $this->redirect($this->referer(['action' => 'index'])); } } diff --git a/ja/tutorials-and-examples/bookmarks/part-two.rst b/ja/tutorials-and-examples/bookmarks/part-two.rst index 5ec2e9c74f..832445b242 100644 --- a/ja/tutorials-and-examples/bookmarks/part-two.rst +++ b/ja/tutorials-and-examples/bookmarks/part-two.rst @@ -200,6 +200,7 @@ AppController に追加しましょう。 :: if ($bookmark->user_id == $user['id']) { return true; } + return parent::isAuthorized($user); } @@ -389,6 +390,7 @@ AppController に追加しましょう。 :: foreach ($newTags as $tag) { $out[] = $this->Tags->newEntity(['title' => $tag]); } + return $out; } diff --git a/ja/tutorials-and-examples/cms/tags-and-users.rst b/ja/tutorials-and-examples/cms/tags-and-users.rst index 77a237070c..7852f082ba 100644 --- a/ja/tutorials-and-examples/cms/tags-and-users.rst +++ b/ja/tutorials-and-examples/cms/tags-and-users.rst @@ -118,6 +118,7 @@ edit メソッドは次のようになります。 :: $this->Articles->patchEntity($article, $this->request->getData()); if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been updated.')); + return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to update your article.')); @@ -338,6 +339,7 @@ CakePHP では、コントローラーのアクションをスリムに保ち、 $str = $tags->reduce(function ($string, $tag) { return $string . $tag->title . ', '; }, ''); + return trim($str, ', '); } @@ -423,6 +425,7 @@ CakePHP では、コントローラーのアクションをスリムに保ち、 foreach ($newTags as $tag) { $out[] = $this->Tags->newEntity(['title' => $tag]); } + return $out; } diff --git a/pt/contributing/cakephp-coding-conventions.rst b/pt/contributing/cakephp-coding-conventions.rst index 6886e7c0a5..eab94b75c0 100644 --- a/pt/contributing/cakephp-coding-conventions.rst +++ b/pt/contributing/cakephp-coding-conventions.rst @@ -212,6 +212,7 @@ Exemplo de uma definição de método:: if (expr) { declaração; } + return $var; } @@ -230,6 +231,7 @@ de uma função. Tente fazer suas funções retornarem algo, pelo menos ``true`` if (!($dnsInfo) || !($dnsInfo['phpType'])) { return $this->addError(); } + return true; } diff --git a/pt/controllers.rst b/pt/controllers.rst index ad037f1748..d44cd86f29 100644 --- a/pt/controllers.rst +++ b/pt/controllers.rst @@ -294,6 +294,7 @@ você pode querer redirecioná-lo para uma tela de recepção. :: ['controller' => 'Orders', 'action' => 'thanks'] ); } + return $this->redirect( ['controller' => 'Orders', 'action' => 'confirm'] ); @@ -307,6 +308,7 @@ corrente. Você também pode usar uma URL relativa ou absoluta como o parâmetro $url:: return $this->redirect('/orders/thanks'); + return $this->redirect('http://www.example.com'); Você também pode passar dados para a action:: diff --git a/pt/controllers/components/authentication.rst b/pt/controllers/components/authentication.rst index 17d399cc24..2e9eb11b09 100644 --- a/pt/controllers/components/authentication.rst +++ b/pt/controllers/components/authentication.rst @@ -303,6 +303,7 @@ caso de falha. :: if (empty($username) || empty($pass)) { return false; } + return $this->_findUser($username, $pass); } @@ -370,6 +371,7 @@ do CakePHP:: // possa verificá-lo durante o login. $entity->api_key = $hasher->hash($entity->api_key_plain); } + return true; } } @@ -695,6 +697,7 @@ a função de login de acordo:: $user->password = $this->request->getData('password'); $this->Users->save($user); } + return $this->redirect($this->Auth->redirectUrl()); } ... diff --git a/pt/controllers/components/request-handling.rst b/pt/controllers/components/request-handling.rst index 4f19ab90c6..5adebed49b 100644 --- a/pt/controllers/components/request-handling.rst +++ b/pt/controllers/components/request-handling.rst @@ -150,6 +150,7 @@ parecer:: foreach ($rows as &$row) { $row = str_getcsv($row, ','); } + return $rows; }; $this->loadComponent('RequestHandler', [ diff --git a/pt/core-libraries/events.rst b/pt/core-libraries/events.rst index 11cccd43ad..389ce25a61 100644 --- a/pt/core-libraries/events.rst +++ b/pt/core-libraries/events.rst @@ -68,6 +68,7 @@ o Model Orders limpo você poderia usar eventos:: return true; } + return false; } } diff --git a/pt/development/routing.rst b/pt/development/routing.rst index 6cc1751c22..9edfecaa5c 100644 --- a/pt/development/routing.rst +++ b/pt/development/routing.rst @@ -1286,6 +1286,7 @@ Os filtros de URL permitem implementar recursos como parâmetros persistentes:: if ($request->getParam('lang') && !isset($params['lang'])) { $params['lang'] = $request->getParam('lang'); } + return $params; }); @@ -1303,6 +1304,7 @@ Outro caso de uso está mudando uma determinada rota no tempo de execução (rot $params['language'] = $params[0]; unset($params[0]); } + return $params; }); diff --git a/pt/development/sessions.rst b/pt/development/sessions.rst index 3d82f9bb41..9f2c515e71 100644 --- a/pt/development/sessions.rst +++ b/pt/development/sessions.rst @@ -251,6 +251,7 @@ A classe deve se parecer com:: if ($result) { return $result; } + return parent::read($id); } diff --git a/pt/development/testing.rst b/pt/development/testing.rst index e110b7460d..475964031d 100644 --- a/pt/development/testing.rst +++ b/pt/development/testing.rst @@ -1712,6 +1712,7 @@ Expandindo no exemplo Orders, digamos que temos as seguintes tabelas:: return true; } + return false; } } diff --git a/pt/orm/database-basics.rst b/pt/orm/database-basics.rst index 7d5ba2b005..fc338e054b 100644 --- a/pt/orm/database-basics.rst +++ b/pt/orm/database-basics.rst @@ -443,6 +443,7 @@ poderíamos fazer a seguinte classe de tipo:: if ($value === null) { return null; } + return json_decode($value, true); } @@ -451,6 +452,7 @@ poderíamos fazer a seguinte classe de tipo:: if (is_array($value) || $value === null) { return $value; } + return json_decode($value, true); } @@ -464,6 +466,7 @@ poderíamos fazer a seguinte classe de tipo:: if ($value === null) { return PDO::PARAM_NULL; } + return PDO::PARAM_STR; } @@ -575,6 +578,7 @@ mapear dados nesse objeto de valor e em expressões SQL:: if (is_array($value)) { return new Point($value[0], $value[1]); } + return null; } diff --git a/pt/orm/retrieving-data-and-resultsets.rst b/pt/orm/retrieving-data-and-resultsets.rst index c7ea54d534..9c7b5bbe79 100644 --- a/pt/orm/retrieving-data-and-resultsets.rst +++ b/pt/orm/retrieving-data-and-resultsets.rst @@ -925,6 +925,7 @@ articles by running:: if (!in_array($value, $output)) { $output[] = $value; } + return $output; }; diff --git a/pt/tutorials-and-examples/blog/part-three.rst b/pt/tutorials-and-examples/blog/part-three.rst index f7361622f9..f7276e1a5b 100644 --- a/pt/tutorials-and-examples/blog/part-three.rst +++ b/pt/tutorials-and-examples/blog/part-three.rst @@ -267,6 +267,7 @@ moveUp() e moveDown() para ser capaz de reordenar as categorias na árvore: } else { $this->Flash->error('The category could not be moved up. Please, try again.'); } + return $this->redirect($this->referer(['action' => 'index'])); } @@ -279,6 +280,7 @@ moveUp() e moveDown() para ser capaz de reordenar as categorias na árvore: } else { $this->Flash->error('The category could not be moved down. Please, try again.'); } + return $this->redirect($this->referer(['action' => 'index'])); } } diff --git a/pt/tutorials-and-examples/bookmarks/part-two.rst b/pt/tutorials-and-examples/bookmarks/part-two.rst index 972ea99c0f..c51200b91f 100644 --- a/pt/tutorials-and-examples/bookmarks/part-two.rst +++ b/pt/tutorials-and-examples/bookmarks/part-two.rst @@ -202,6 +202,7 @@ para os bookmarks. Em seu ``BookmarksController`` adicione o seguinte:: if ($bookmark->user_id == $user['id']) { return true; } + return parent::isAuthorized($user); } @@ -389,6 +390,7 @@ entidades relacionadas. Adicione o seguinte em foreach ($new as $tag) { $out[] = $this->Tags->newEntity(['title' => $tag]); } + return $out; } From bf88201d7a37bf059d13e6add8f42d2b5f748834 Mon Sep 17 00:00:00 2001 From: "T.Yajima" Date: Fri, 7 Jun 2024 10:22:54 +0900 Subject: [PATCH 50/68] =?UTF-8?q?fix:=20unify=20"=E9=96=A2=E6=95=B0"=20to?= =?UTF-8?q?=20"=E3=83=A1=E3=82=BD=E3=83=83=E3=83=89"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ja/tutorials-and-examples/cms/articles-controller.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ja/tutorials-and-examples/cms/articles-controller.rst b/ja/tutorials-and-examples/cms/articles-controller.rst index 0b5dbd3555..17e9c33640 100644 --- a/ja/tutorials-and-examples/cms/articles-controller.rst +++ b/ja/tutorials-and-examples/cms/articles-controller.rst @@ -38,9 +38,9 @@ CMS チュートリアル - Articles コントローラーの作成 } } -``ArticlesController`` の ``index()`` 関数を定義することで、ユーザーは、 +``ArticlesController`` の ``index()`` メソッドを定義することで、ユーザーは、 **www.example.com/articles/index** をリクエストすることで、そこにあるロジックに -アクセスできるようになります。同様に、 ``foobar()`` という関数を定義した場合、 +アクセスできるようになります。同様に、 ``foobar()`` というメソッドを定義した場合、 ユーザーはそのメソッドに **www.example.com/articles/foobar** で、アクセスできます。 特定の URL を取得できるように、コントローラーとアクションの名前を付けたいという 誘惑に駆られるかもしれません。その誘惑に抗ってください。代わりに、 :doc:`/intro/conventions` From c2899ba2725095226f1d00d544126f2a6b5d93fc Mon Sep 17 00:00:00 2001 From: "T.Yajima" Date: Fri, 7 Jun 2024 10:24:19 +0900 Subject: [PATCH 51/68] fix: corrected to natural Japanese --- ja/tutorials-and-examples/cms/articles-controller.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ja/tutorials-and-examples/cms/articles-controller.rst b/ja/tutorials-and-examples/cms/articles-controller.rst index 17e9c33640..ed57a30aa5 100644 --- a/ja/tutorials-and-examples/cms/articles-controller.rst +++ b/ja/tutorials-and-examples/cms/articles-controller.rst @@ -20,7 +20,7 @@ CMS チュートリアル - Articles コントローラーの作成 コントローラーのメソッドです。例えば、ユーザーが **www.example.com/articles/index** (**www.example.com/articles** と同じ) をリクエストした場合、CakePHP は、 ``ArticlesController`` の ``index`` メソッドを呼びます。このメソッドは、モデル層に問い合わせ、 -ビューでテンプレートを描画してレスポンスの準備する必要があります。そのアクションのコードは、 +ビューでテンプレートを描画してレスポンスを準備する必要があります。そのアクションのコードは、 次のようになります。 :: Date: Fri, 12 Jul 2024 10:17:56 +0900 Subject: [PATCH 52/68] fix: corrected the sentence --- ja/tutorials-and-examples/blog/part-two.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ja/tutorials-and-examples/blog/part-two.rst b/ja/tutorials-and-examples/blog/part-two.rst index 52f1aee036..39f29aefc3 100644 --- a/ja/tutorials-and-examples/blog/part-two.rst +++ b/ja/tutorials-and-examples/blog/part-two.rst @@ -186,7 +186,7 @@ CakePHP のリバースルーティング機能を活用することができま この時点で、ブラウザーから http://www.example.com/articles/index を開いてみてください。 タイトルと投稿内容のテーブル一覧がまとめられているビューが表示されるはずです。 -ビューの中のリンク (投稿記事のタイトルから ``/articles/view/どれかのID番号``いう表示を出します。 +ビューの中のリンク (投稿記事のタイトル) は ``/articles/view/どれかのID番号`` というリンクを表示します。 もしそういう表示が出ない場合には、何かおかしくなってしまったか、もうすでにあなたが その定義作業をしてしまったから(仕事がハヤイ!)か、のどちらかです。 そうでないなら、これから ``ArticlesController`` の中に作ってみましょう。 :: From 88ba5cd4e586dfd00f900d9976fdddca2548e231 Mon Sep 17 00:00:00 2001 From: "T.Yajima" Date: Thu, 25 Jul 2024 10:23:17 +0900 Subject: [PATCH 53/68] fix: corrected one of the notations --- ja/tutorials-and-examples/blog-auth-example/auth.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ja/tutorials-and-examples/blog-auth-example/auth.rst b/ja/tutorials-and-examples/blog-auth-example/auth.rst index 563242b7fd..b07fe9383a 100644 --- a/ja/tutorials-and-examples/blog-auth-example/auth.rst +++ b/ja/tutorials-and-examples/blog-auth-example/auth.rst @@ -255,7 +255,7 @@ composerを使ってAuthenticationプラグインをインストールします デフォルトでは、認証情報はリクエストデータの ``email`` と ``password`` フィールドから 抽出されます。認証結果は ``authentication`` という名前のリクエスト属性に注入されます。 この結果はいつでもコントローラのアクションから -``$this->request->getAttribute('authentication')``を使って調べることができます。 +``$this->request->getAttribute('authentication')`` を使って調べることができます。 すべてのページは ``AuthenticationComponent`` がリクエストごとに結果をチェックしているため、 制限されてしまいます。認証されたユーザを見つけられなかった場合は ユーザーを ``/users/login`` のページにリダイレクトします。 From 47973d0f7d41910112ec396f1004eed376d9ecaf Mon Sep 17 00:00:00 2001 From: Mark Story Date: Fri, 9 Aug 2024 22:58:00 -0400 Subject: [PATCH 54/68] 4.x Rename cookbook to book Simplify documentation naming conventions across the various file formats. --- config/conf.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/config/conf.py b/config/conf.py index 3d6a94b8e6..a3c6424d6c 100644 --- a/config/conf.py +++ b/config/conf.py @@ -64,7 +64,7 @@ # (source start file, target name, title, author, # documentclass [howto/manual]). latex_documents = [ - ('pdf-contents', 'CakePHPCookbook.tex', u'CakePHP Cookbook Documentation', + ('pdf-contents', 'CakePHPBook.tex', u'CakePHP Book', u'Cake Software Foundation', 'manual'), ] @@ -73,7 +73,7 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - ('index', 'cakephpcookbook', u'CakePHP Cookbook Documentation', + ('index', 'cakephpbook', u'CakePHP Book', [u'CakePHP'], 1) ] @@ -81,7 +81,7 @@ # -- Options for Epub output ------------------------------------------------- # Bibliographic Dublin Core info. -epub_title = u'CakePHP Cookbook' +epub_title = u'CakePHP Book' epub_author = u'Cake Software Foundation, Inc.' epub_publisher = u'Cake Software Foundation, Inc.' epub_copyright = u'%d, Cake Software Foundation, Inc.' % datetime.datetime.now().year @@ -99,7 +99,7 @@ epub_identifier = 'https://cakephp.org' # A unique identification for the text. -epub_uid = 'cakephpcookbook1393624653' +epub_uid = 'cakephpbook1393624653' # A list of files that should not be packed into the epub file. epub_exclude_files = [ From e06231208bd61ed419faa1e85a6fca259c442342 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sun, 11 Aug 2024 00:07:46 -0400 Subject: [PATCH 55/68] Bump docs theme --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 5793b68834..f6d654ebf0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ docutils==0.20.1 sphinx==7.0.1 sphinxcontrib-phpdomain==0.11.1 -cakephpsphinx>=0.1.57,<1.0 +cakephpsphinx>=0.1.58,<1.0 From 07983c3aceddc50a9d50f6a49ed9fdff87c1ecd6 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sun, 11 Aug 2024 23:08:07 -0400 Subject: [PATCH 56/68] Update PDF file reference. --- README.md | 2 +- en/index.rst | 2 +- es/index.rst | 2 +- fr/index.rst | 2 +- ja/index.rst | 2 +- pt/index.rst | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index f536f8f251..5b8597f766 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,7 @@ Building the PDF is a non-trivial task. 2. Run `make latex-en`. 3. Run `make pdf-en`. -At this point the completed PDF should be in `build/latex/en/CakePHPCookbook.pdf`. +At this point the completed PDF should be in `build/latex/en/CakePHPBook.pdf`. Contributing ------------ diff --git a/en/index.rst b/en/index.rst index 0b5e1830ae..e9088ac3fc 100644 --- a/en/index.rst +++ b/en/index.rst @@ -20,7 +20,7 @@ contribute any additions, deletions, or corrections to the documentation. Enjoy the CakePHP cookbook almost anywhere. Available as both a PDF and EPUB, you can now read it on more devices, as well as offline. - - `PDF <../_downloads/en/CakePHPCookbook.pdf>`_ + - `PDF <../_downloads/en/CakePHPBook.pdf>`_ - `EPUB <../_downloads/en/CakePHP.epub>`_ - `Original Source `_ diff --git a/es/index.rst b/es/index.rst index 41f437ee6e..950c87afb4 100644 --- a/es/index.rst +++ b/es/index.rst @@ -19,7 +19,7 @@ o corrección de la documentación. Disfruta del manual de CakePHP en cualquier sitio. Disponible tanto en PDF como en EPUB, puedes leerlo en más dispositivos y de manera offline. - - `PDF <../_downloads/es/CakePHPCookbook.pdf>`_ + - `PDF <../_downloads/es/CakePHPBook.pdf>`_ - `EPUB <../_downloads/es/CakePHP.epub>`_ - `Original Source `_ diff --git a/fr/index.rst b/fr/index.rst index bc953986fc..19c329d285 100644 --- a/fr/index.rst +++ b/fr/index.rst @@ -22,7 +22,7 @@ la documentation. EPUB, vous pouvez maintenant lire les docs sur plus d'appareils et hors-ligne. - - `PDF <../_downloads/fr/CakePHPCookbook.pdf>`_. + - `PDF <../_downloads/fr/CakePHPBook.pdf>`_. - `EPUB <../_downloads/fr/CakePHP.epub>`_. - `Source originale `_. diff --git a/ja/index.rst b/ja/index.rst index a0ce8e6676..e7f4a49720 100644 --- a/ja/index.rst +++ b/ja/index.rst @@ -20,7 +20,7 @@ CakePHP クックブックは、オープンに開発されている、コミュ どこでも CakePHP のレシピをお楽しみいただけます。PDF と EPUB をご用意しましたので、 多くのデバイス上でオフラインでドキュメントを読むことができます。 - - `PDF (英語) <../_downloads/en/CakePHPCookbook.pdf>`_ + - `PDF (英語) <../_downloads/en/CakePHPBook.pdf>`_ - `EPUB <../_downloads/ja/CakePHP.epub>`_ - `オリジナルソース `_ diff --git a/pt/index.rst b/pt/index.rst index 048965aa2f..fd8f81e3a9 100644 --- a/pt/index.rst +++ b/pt/index.rst @@ -20,7 +20,7 @@ quaisquer adições, exclusões ou correções para a documentação. Consulte o *cookbook* do CakePHP praticamente em qualquer lugar. Disponível como PDF e EPUB, você pode lê-lo em diversos dispositivos, e também offline. - - `PDF <../_downloads/pt/CakePHPCookbook.pdf>`_ + - `PDF <../_downloads/pt/CakePHPBook.pdf>`_ - `EPUB <../_downloads/pt/CakePHP.epub>`_ - `Código-fonte Original `_ From 941f4c8e323f728a037c6642143ad886da494b77 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Mon, 12 Aug 2024 08:49:45 -0400 Subject: [PATCH 57/68] Remove cookbook references --- en/index.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/en/index.rst b/en/index.rst index e9088ac3fc..6d43b6a4e3 100644 --- a/en/index.rst +++ b/en/index.rst @@ -6,7 +6,7 @@ CakePHP 4 is a web development framework running on PHP |phpversion| (min. PHP | Read :doc:`CakePHP at a Glance ` to get an introduction to the fundamentals of CakePHP. -The CakePHP cookbook is an openly developed and community editable documentation +The CakePHP book is an openly developed and community editable documentation project. Notice the pencil icon button fixated against the right wall; it will direct you to the GitHub online editor of the active page, allowing you to contribute any additions, deletions, or corrections to the documentation. @@ -17,7 +17,7 @@ contribute any additions, deletions, or corrections to the documentation. .. image:: /_static/img/read-the-book.jpg - Enjoy the CakePHP cookbook almost anywhere. Available as both a PDF and + Enjoy the CakePHP book almost anywhere. Available as both a PDF and EPUB, you can now read it on more devices, as well as offline. - `PDF <../_downloads/en/CakePHPBook.pdf>`_ @@ -54,5 +54,5 @@ elements in a CakePHP application: validation, and domain logic within your application. .. meta:: - :title lang=en: .. CakePHP Cookbook documentation master file, created by - :keywords lang=en: doc models,documentation master,presentation layer,documentation project,quickstart,original source,sphinx,liking,cookbook,validity,conventions,validation,cakephp,accuracy,storage and retrieval,heart,blog,project hope + :title lang=en: .. CakePHP Book documentation master file, created by + :keywords lang=en: doc models,documentation master,presentation layer,documentation project,quickstart,original source,sphinx,liking,book,validity,conventions,validation,cakephp,accuracy,storage and retrieval,heart,blog,project hope From fb4e583325dfc7318ffd3825be238a4ffd0d955a Mon Sep 17 00:00:00 2001 From: Arhell Date: Wed, 14 Aug 2024 00:21:25 +0300 Subject: [PATCH 58/68] Remove more cookbook (es, ja, pt) --- es/index.rst | 4 ++-- ja/index.rst | 4 ++-- pt/index.rst | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/es/index.rst b/es/index.rst index 950c87afb4..9f81c22500 100644 --- a/es/index.rst +++ b/es/index.rst @@ -48,5 +48,5 @@ elementos claves en una aplicación de CakePHP: * Los :doc:`modelos `, que son el ingrediente clave en cualquier aplicación. Manejan la validación y la lógica de dominio dentro de tu aplicación. .. meta:: - :title lang=es: .. CakePHP Cookbook archivo de documentación, creado por - :keywords lang=es: documento modelos,master documentación,capa presentación,proyecto documentación,guia de inicio rápido,fuente original,sphinx,liking,cookbook,validez,convenciones,validación,cakephp,exactitud,almacenaje y recuperación,corazón,blog + :title lang=es: .. CakePHP Book archivo de documentación, creado por + :keywords lang=es: documento modelos,master documentación,capa presentación,proyecto documentación,guia de inicio rápido,fuente original,sphinx,liking,book,validez,convenciones,validación,cakephp,exactitud,almacenaje y recuperación,corazón,blog diff --git a/ja/index.rst b/ja/index.rst index e7f4a49720..1f4781ad05 100644 --- a/ja/index.rst +++ b/ja/index.rst @@ -51,5 +51,5 @@ CakePHP クックブックは、オープンに開発されている、コミュ バリデーションやあなたのアプリケーションのドメインロジックを処理します。 .. meta:: - :title lang=ja: .. CakePHP Cookbook documentation master file, created by - :keywords lang=ja: doc models,documentation master,presentation layer,documentation project,quickstart,original source,sphinx,liking,cookbook,validity,conventions,validation,cakephp,accuracy,storage and retrieval,heart,blog,project hope + :title lang=ja: .. CakePHP Book documentation master file, created by + :keywords lang=ja: doc models,documentation master,presentation layer,documentation project,quickstart,original source,sphinx,liking,book,validity,conventions,validation,cakephp,accuracy,storage and retrieval,heart,blog,project hope diff --git a/pt/index.rst b/pt/index.rst index fd8f81e3a9..49f4ee6183 100644 --- a/pt/index.rst +++ b/pt/index.rst @@ -54,5 +54,5 @@ principais elementos existentes em uma aplicação construída com o CakePHP: lidam com a validação e a lógica de domínio em sua aplicação. .. meta:: - :title lang=pt: .. CakePHP Cookbook arquivo mestre de documentação, criado por - :keywords lang=pt: modelo de documentos,documentação principal,camada de apresentação,documentação de projeto,guia rápido,código-fonte original,sphinx,liking,cookbook,validade,convenções,validação,cakephp,precisão,armazenamento e recuperação,coração,blog,projeto + :title lang=pt: .. CakePHP Book arquivo mestre de documentação, criado por + :keywords lang=pt: modelo de documentos,documentação principal,camada de apresentação,documentação de projeto,guia rápido,código-fonte original,sphinx,liking,book,validade,convenções,validação,cakephp,precisão,armazenamento e recuperação,coração,blog,projeto From 58b86c315dbfcfd38c27fa9bb0f0624b7457ccb3 Mon Sep 17 00:00:00 2001 From: Vincent MB <44963036+vincentTSSB@users.noreply.github.com> Date: Thu, 22 Aug 2024 19:22:23 +0800 Subject: [PATCH 59/68] The `replaceToken()` method was added in version 4.5.0 instead of 4.3.0 (#7909) --- en/security/csrf.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/security/csrf.rst b/en/security/csrf.rst index 02d9fcae21..7f06d43dc7 100644 --- a/en/security/csrf.rst +++ b/en/security/csrf.rst @@ -107,7 +107,7 @@ Should you need to rotate or replace the session CSRF token you can do so with:: $this->request = SessionCsrfProtectionMiddleware::replaceToken($this->request); -.. versionadded:: 4.3.0 +.. versionadded:: 4.5.0 The ``replaceToken`` method was added. Skipping CSRF checks for specific actions From 13d95ac1d64d09cbb5449fa6c21090fa68ffbc47 Mon Sep 17 00:00:00 2001 From: yosus <5551430+yosus@users.noreply.github.com> Date: Tue, 3 Sep 2024 21:53:32 +0800 Subject: [PATCH 60/68] Update 4-0-upgrade-guide.rst More skeleton-files need to be updated during 3.x to 4.x upgrade --- en/appendices/4-0-upgrade-guide.rst | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/en/appendices/4-0-upgrade-guide.rst b/en/appendices/4-0-upgrade-guide.rst index 28cbd6cf89..a156ad3ddd 100644 --- a/en/appendices/4-0-upgrade-guide.rst +++ b/en/appendices/4-0-upgrade-guide.rst @@ -89,13 +89,17 @@ composer commands: php composer.phar require --dev --update-with-dependencies "phpunit/phpunit:^8.0" php composer.phar require --update-with-dependencies "cakephp/cakephp:4.0.*" -Application.php +Others =============== -Next, ensure your ``src/Application.php`` has been updated to have the same -method signatures as the one found in cakephp/app. You can find the current -`Application.php -`__ on GitHub. +Next, ensure your files has been updated to have the same +method signatures as those found in cakephp/app. + +#. ``src/Application.php`` at `Application.php `__ on GitHub. +#. ``config/app.php`` at `app.php `__ on GitHub. +#. ``config/bootstrap.php`` at `bootstrap.php `__ on GitHub. +#. ``config/paths.php`` at `paths.php `__ on GitHub, where ``RESOURCES`` needs to be defined. +#. ``config/routes.php`` at `routes.php `__ on GitHub. If you are providing some kind of REST API, don't forget to include the :ref:`body-parser-middleware`. Finally, you should consider upgrading to the new From 9f841e71c16924005d9de123741ffb7d619642da Mon Sep 17 00:00:00 2001 From: yosus <5551430+yosus@users.noreply.github.com> Date: Thu, 5 Sep 2024 11:43:21 +0800 Subject: [PATCH 61/68] Update en/appendices/4-0-upgrade-guide.rst has -> have Co-authored-by: Mark Story --- en/appendices/4-0-upgrade-guide.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/appendices/4-0-upgrade-guide.rst b/en/appendices/4-0-upgrade-guide.rst index a156ad3ddd..a0a69a8a1e 100644 --- a/en/appendices/4-0-upgrade-guide.rst +++ b/en/appendices/4-0-upgrade-guide.rst @@ -92,7 +92,7 @@ composer commands: Others =============== -Next, ensure your files has been updated to have the same +Next, ensure your files have been updated to have the same method signatures as those found in cakephp/app. #. ``src/Application.php`` at `Application.php `__ on GitHub. From 5ae88a6d0d911d9d2ea2d3a09e9ae3fd3859acad Mon Sep 17 00:00:00 2001 From: Murl080 <141338078+Murl080@users.noreply.github.com> Date: Fri, 27 Sep 2024 15:06:22 +0200 Subject: [PATCH 62/68] Move entry from breaking changes to new feature --- en/appendices/4-0-migration-guide.rst | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/en/appendices/4-0-migration-guide.rst b/en/appendices/4-0-migration-guide.rst index 59c4549c29..1ae2393672 100644 --- a/en/appendices/4-0-migration-guide.rst +++ b/en/appendices/4-0-migration-guide.rst @@ -319,8 +319,6 @@ Utility path extracted as first argument. * The ``readFile`` option of ``Xml::build()`` is no longer true by default. Instead you must enable ``readFile`` to read local files. -* ``Hash::sort()`` now accepts the ``SORT_ASC`` and ``SORT_DESC`` constants in - the direction parameter. * ``Inflector::pluralize()`` now inflects ``index`` to ``indexes`` instead of ``indices``. This reflects the technical usage of this plural in the core as well as the ecosystem. @@ -518,6 +516,12 @@ TestSuite * ``TestSuite\EmailTrait::assertMailContainsAttachment()`` was added. +Utility +------- + +* ``Hash::sort()`` now accepts the ``SORT_ASC`` and ``SORT_DESC`` constants in + the direction parameter. + Validation ---------- From 15084a95b9a6b393803af1b9486d1c02fa482330 Mon Sep 17 00:00:00 2001 From: Arhell Date: Sat, 5 Oct 2024 11:14:00 +0300 Subject: [PATCH 63/68] Update 4-4-migration-guide (fr, ja) --- fr/appendices/4-4-migration-guide.rst | 6 +++--- ja/appendices/4-4-migration-guide.rst | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/fr/appendices/4-4-migration-guide.rst b/fr/appendices/4-4-migration-guide.rst index abc8daa010..def533db52 100644 --- a/fr/appendices/4-4-migration-guide.rst +++ b/fr/appendices/4-4-migration-guide.rst @@ -105,10 +105,10 @@ mais il **sera** supprimé dans 5.0. classes de vues dans ``RequestHandlerComponent``. -PaginationComponent -------------------- +PaginatorComponent +------------------ -Le ``PaginationComponent`` est déprécié et sera supprimé dans 5.0. Utilisez la +Le ``PaginatorComponent`` est déprécié et sera supprimé dans 5.0. Utilisez la propriété ``Controller::$paginate`` ou le paramètre ``$settings`` de la méthode ``Controller::paginate()`` pour spécifier les réglages de pagination nécessaires. diff --git a/ja/appendices/4-4-migration-guide.rst b/ja/appendices/4-4-migration-guide.rst index 7b153a65af..389c1de5ce 100644 --- a/ja/appendices/4-4-migration-guide.rst +++ b/ja/appendices/4-4-migration-guide.rst @@ -78,10 +78,10 @@ RequestHandlerComponent - ``RequestHandlerComponent`` でビュークラスマッピングを定義する代わりに、 :ref:`controller-viewclasses` を使用してください。 -PaginationComponent -------------------- +PaginatorComponent +------------------ -``PaginationComponent`` は非推奨で、5.0で削除される予定です。 +``PaginatorComponent`` は非推奨で、5.0で削除される予定です。 必要なページング設定を行うには、 ``Controller::$paginate`` プロパティ、 または ``Controller::paginate()`` メソッドの ``$settings`` パラメータを使用します。 From 65f969d8ae12fe8365f881d0c3c0898f6b16ec13 Mon Sep 17 00:00:00 2001 From: Arhell Date: Sun, 6 Oct 2024 00:22:44 +0300 Subject: [PATCH 64/68] Update query-builder.rst (fr) --- fr/orm/query-builder.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr/orm/query-builder.rst b/fr/orm/query-builder.rst index 4e44be3748..ab4225a539 100644 --- a/fr/orm/query-builder.rst +++ b/fr/orm/query-builder.rst @@ -215,7 +215,7 @@ activer les :ref:`logs de requête `. Récupérer vos Données ===================== -CakePHP permet de construire simplement des requêtes ``SELECT``. La +CakePHP permet de construire simplement des requêtes ``SELECT``. La méthode ``select()`` vous permet de ne récupérer que les champs qui vous sont nécessaires:: @@ -607,7 +607,7 @@ Vous pouvez créer des conditions ``if ... then ... else`` en utilisant $published = $query->newExpr() ->case() ->when(['published' => true]) - ->then('Y'); + ->then('Y') ->else('N'); # CASE WHEN published = true THEN 'Y' ELSE 'N' END; From f86c63acdac0a97f1060c1822a0ce83c6be43039 Mon Sep 17 00:00:00 2001 From: yosus <5551430+yosus@users.noreply.github.com> Date: Tue, 22 Oct 2024 12:22:35 +0800 Subject: [PATCH 65/68] Update views.rst Added an example of modified contents --- en/views.rst | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/en/views.rst b/en/views.rst index 8b766bbbc4..33ba34bd21 100644 --- a/en/views.rst +++ b/en/views.rst @@ -308,6 +308,17 @@ title, and sometimes assign the title as a view variable in the controller:: // In view file or layout above $this->fetch('title') $this->assign('title', $title); + // Example where block contents are modified + $this->start('test_view_block'); + echo 'default contents'; + $this->end(); + // Output : default contents + echo $this->fetch('test_view_block'); + $this->assign('test_view_block', 'modified contents'); + // Output : modified contents + echo $this->fetch('test_view_block'); + + The ``prepend()`` method allows you to prepend content to an existing block:: // Prepend to sidebar From 684b03b1d6277c8d827077ecc67ec02b64a4eb53 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sun, 3 Nov 2024 00:02:02 -0400 Subject: [PATCH 66/68] Bump theme version --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index f6d654ebf0..94ffd6fe13 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ docutils==0.20.1 sphinx==7.0.1 sphinxcontrib-phpdomain==0.11.1 -cakephpsphinx>=0.1.58,<1.0 +cakephpsphinx>=0.1.59,<1.0 From 955f337b1013ac747563b87eb770ae7f53bd344a Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sat, 22 Mar 2025 22:40:01 -0400 Subject: [PATCH 67/68] Update branch link --- config/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/conf.py b/config/conf.py index a3c6424d6c..fdbc38673f 100644 --- a/config/conf.py +++ b/config/conf.py @@ -40,7 +40,7 @@ # The GitHub branch name for this version of the docs # for edit links to point at. -branch = '4.next' +branch = '4.x' # Add any paths that contain custom themes here, relative to this directory. html_theme_path = [] From 0eef38a60db6f590be7e5a581d46691f3beeb81b Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sat, 22 Mar 2025 22:42:37 -0400 Subject: [PATCH 68/68] Update for 4.7 --- config/conf.py | 4 ++-- en/appendices.rst | 4 ++++ en/appendices/4-7-migration-guide.rst | 20 ++++++++++++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 en/appendices/4-7-migration-guide.rst diff --git a/config/conf.py b/config/conf.py index fdbc38673f..d820529f12 100644 --- a/config/conf.py +++ b/config/conf.py @@ -33,14 +33,14 @@ ] # 4.next is a pre-release branch -is_prerelease = False +is_prerelease = True # Languages available. languages = ['en', 'pt_BR', 'es', 'ja', 'fr'] # The GitHub branch name for this version of the docs # for edit links to point at. -branch = '4.x' +branch = '4.next' # Add any paths that contain custom themes here, relative to this directory. html_theme_path = [] diff --git a/en/appendices.rst b/en/appendices.rst index 45c3d8bf6f..05b0a88db3 100644 --- a/en/appendices.rst +++ b/en/appendices.rst @@ -14,6 +14,10 @@ introduced in each version and the migration path between versions. appendices/4-1-migration-guide appendices/4-2-migration-guide appendices/4-3-migration-guide + appendices/4-4-migration-guide + appendices/4-5-migration-guide + appendices/4-6-migration-guide + appendices/4-7-migration-guide appendices/fixture-upgrade Backwards Compatibility Shimming diff --git a/en/appendices/4-7-migration-guide.rst b/en/appendices/4-7-migration-guide.rst new file mode 100644 index 0000000000..295354f2e9 --- /dev/null +++ b/en/appendices/4-7-migration-guide.rst @@ -0,0 +1,20 @@ +4.7 Migration Guide +################### + +CakePHP 4.7 is an API compatible upgrade from 4.0. This page outlines the +deprecations and features added in 4.7. + +Upgrading to 4.7.0 +================== + +You can can use composer to upgrade to CakePHP 4.7.0:: + + php composer.phar require --update-with-dependencies "cakephp/cakephp:^4.7" + +.. note:: + CakePHP 4.7 requires PHP 7.4 or greater. + +New Features +============ + +TODO