diff --git a/.github/workflows/deploy_docs_5x.yml b/.github/workflows/deploy_docs_5x.yml index b76e45d08..691f2fbb4 100644 --- a/.github/workflows/deploy_docs_5x.yml +++ b/.github/workflows/deploy_docs_5x.yml @@ -22,3 +22,4 @@ jobs: git_remote_url: 'ssh://dokku@apps.cakephp.org:22/debugkit-docs-5' git_push_flags: '-f' ssh_private_key: ${{ secrets.DOKKU_SSH_PRIVATE_KEY }} + branch: '5.x' diff --git a/.github/workflows/docs-validation.yml b/.github/workflows/docs-validation.yml new file mode 100644 index 000000000..439a52c18 --- /dev/null +++ b/.github/workflows/docs-validation.yml @@ -0,0 +1,27 @@ +name: Documentation Validation + +on: + push: + branches: + - 5.x + paths: + - 'docs/**' + - '.github/**' + pull_request: + paths: + - 'docs/**' + - '.github/**' + +jobs: + validate: + uses: cakephp/.github/.github/workflows/docs-validation.yml@5.x + with: + docs-path: 'docs' + vitepress-path: 'docs/.vitepress' + enable-config-js-check: true + enable-json-lint: true + enable-toc-check: true + enable-spell-check: true + enable-markdown-lint: true + enable-link-check: true + tools-ref: '5.x' diff --git a/Dockerfile b/Dockerfile index 7acfb27ee..832f6bc1c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,26 +1,36 @@ -# Basic docker based environment -# Necessary to trick dokku into building the documentation -# using dockerfile instead of herokuish -FROM ubuntu:22.04 - -# Add basic tools -RUN apt-get update && \ - apt-get install -y build-essential \ - software-properties-common \ - curl \ - git \ - libxml2 \ - libffi-dev \ - libssl-dev - -# Prevent interactive timezone input -ENV DEBIAN_FRONTEND=noninteractive -RUN LC_ALL=C.UTF-8 add-apt-repository ppa:ondrej/php && \ - apt-get update && \ - apt-get install -y php8.1-cli php8.1-mbstring php8.1-xml php8.1-zip php8.1-intl php8.1-opcache php8.1-sqlite - -WORKDIR /code - -VOLUME ["/code"] - -CMD [ '/bin/bash' ] +# ---------------------- +# 1. Build stage +# ---------------------- +FROM node:22-alpine AS builder + +# Git is required because docs/package.json pulls a dependency from GitHub. +RUN apk add --no-cache git openssh-client + +WORKDIR /app/docs + +# Copy dependency manifests first to preserve Docker layer caching. +COPY docs/ ./ +RUN npm ci + +# Increase max-old-space-size to avoid memory issues during build +ENV NODE_OPTIONS="--max-old-space-size=8192" + +# Build the site. +RUN npm run docs:build + +# ---------------------- +# 2. Runtime stage (nginx) +# ---------------------- +FROM nginx:1.27-alpine AS runner + +# Copy built files +COPY --from=builder /app/docs/.vitepress/dist /usr/share/nginx/html + +# Expose port +EXPOSE 80 + +# Health check (optional) +HEALTHCHECK CMD wget --quiet --tries=1 --spider http://localhost:80/ || exit 1 + +# Start nginx +CMD ["nginx", "-g", "daemon off;"] diff --git a/docs/.gitignore b/docs/.gitignore new file mode 100644 index 000000000..974d64e40 --- /dev/null +++ b/docs/.gitignore @@ -0,0 +1,4 @@ +node_modules +*/public/ +.vitepress/cache +.vitepress/dist diff --git a/docs/.vitepress/config.js b/docs/.vitepress/config.js new file mode 100644 index 000000000..55010f7f3 --- /dev/null +++ b/docs/.vitepress/config.js @@ -0,0 +1,75 @@ +import baseConfig from '@cakephp/docs-skeleton/config' +import { createRequire } from 'module' + +const require = createRequire(import.meta.url) +const tocEn = require('./toc_en.json') +const tocFr = require('./toc_fr.json') +const tocJa = require('./toc_ja.json') +const tocPt = require('./toc_pt.json') + +const versions = { + text: '5.x', + items: [ + { text: '5.x (current)', link: 'https://book.cakephp.org/debugkit/5/', target: '_self' }, + { text: '4.x', link: 'https://book.cakephp.org/debugkit/4/en/', target: '_self' }, + ], +} + +export default { + extends: baseConfig, + srcDir: '.', + title: 'DebugKit', + description: 'CakePHP DebugKit Documentation', + base: '/debugkit/5/', + rewrites: { + 'en/:slug*': ':slug*', + }, + sitemap: { + hostname: 'https://book.cakephp.org/debugkit/5/', + }, + themeConfig: { + socialLinks: [ + { icon: 'github', link: 'https://github.com/cakephp/debug_kit' }, + ], + editLink: { + pattern: 'https://github.com/cakephp/debug_kit/edit/5.x/docs/:path', + text: 'Edit this page on GitHub', + }, + sidebar: tocEn, + nav: [ + { text: 'CakePHP', link: 'https://cakephp.org' }, + { text: 'API', link: 'https://api.cakephp.org/debugkit/' }, + { ...versions }, + ], + }, + locales: { + root: { + label: 'English', + lang: 'en', + themeConfig: { + sidebar: tocEn, + }, + }, + fr: { + label: 'Français', + lang: 'fr', + themeConfig: { + sidebar: tocFr, + }, + }, + ja: { + label: '日本語', + lang: 'ja', + themeConfig: { + sidebar: tocJa, + }, + }, + pt: { + label: 'Português', + lang: 'pt', + themeConfig: { + sidebar: tocPt, + }, + }, + }, +} diff --git a/docs/.vitepress/theme/index.js b/docs/.vitepress/theme/index.js new file mode 100644 index 000000000..e33e19ec9 --- /dev/null +++ b/docs/.vitepress/theme/index.js @@ -0,0 +1 @@ +export { default } from '@cakephp/docs-skeleton' diff --git a/docs/.vitepress/toc_en.json b/docs/.vitepress/toc_en.json new file mode 100644 index 000000000..d86086e6d --- /dev/null +++ b/docs/.vitepress/toc_en.json @@ -0,0 +1,31 @@ +{ + "/": [ + { + "text": "Getting Started", + "collapsed": false, + "items": [ + { "text": "Overview", "link": "/" }, + { "text": "Configuration", "link": "/configuration" }, + { "text": "Toolbar Usage", "link": "/toolbar" } + ] + }, + { + "text": "Panels", + "collapsed": false, + "items": [ + { "text": "History Panel", "link": "/history-panel" }, + { "text": "Mail Panel", "link": "/mail-panel" }, + { "text": "Custom Panels", "link": "/custom-panels" } + ] + }, + { + "text": "Advanced", + "collapsed": false, + "items": [ + { "text": "API Requests", "link": "/api-requests" }, + { "text": "Helper Functions", "link": "/helper-functions" }, + { "text": "API", "link": "https://api.cakephp.org/debugkit/" } + ] + } + ] +} diff --git a/docs/.vitepress/toc_fr.json b/docs/.vitepress/toc_fr.json new file mode 100644 index 000000000..3717ce333 --- /dev/null +++ b/docs/.vitepress/toc_fr.json @@ -0,0 +1,12 @@ +{ + "/fr/": [ + { + "text": "CakePHP DebugKit", + "collapsed": false, + "items": [ + { "text": "Aperçu", "link": "/fr/" }, + { "text": "API", "link": "https://api.cakephp.org/debugkit/" } + ] + } + ] +} diff --git a/docs/.vitepress/toc_ja.json b/docs/.vitepress/toc_ja.json new file mode 100644 index 000000000..b83f1c4ca --- /dev/null +++ b/docs/.vitepress/toc_ja.json @@ -0,0 +1,12 @@ +{ + "/ja/": [ + { + "text": "CakePHP DebugKit", + "collapsed": false, + "items": [ + { "text": "概要", "link": "/ja/" }, + { "text": "API", "link": "https://api.cakephp.org/debugkit/" } + ] + } + ] +} diff --git a/docs/.vitepress/toc_pt.json b/docs/.vitepress/toc_pt.json new file mode 100644 index 000000000..31325c5a5 --- /dev/null +++ b/docs/.vitepress/toc_pt.json @@ -0,0 +1,12 @@ +{ + "/pt/": [ + { + "text": "CakePHP DebugKit", + "collapsed": false, + "items": [ + { "text": "Visão geral", "link": "/pt/" }, + { "text": "API", "link": "https://api.cakephp.org/debugkit/" } + ] + } + ] +} diff --git a/docs/config/__init__.py b/docs/config/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs/config/all.py b/docs/config/all.py deleted file mode 100644 index 167124fab..000000000 --- a/docs/config/all.py +++ /dev/null @@ -1,53 +0,0 @@ -# Global configuration information used across all the -# translations of documentation. -# -# Import the base theme configuration -from cakephpsphinx.config.all import * - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# - -# The full version, including alpha/beta/rc tags. -release = '5.x' - -# The search index version. -search_version = 'debugkit-5' - -# The marketing display name for the book. -version_name = '' - -# Project name shown in the black header bar -project = 'CakePHP DebugKit' - -# Other versions that display in the version picker menu. -version_list = [ - {'name': '3.x', 'number': 'debugkit/3.x', 'title': '3.x'}, - {'name': '4.x', 'number': 'debugkit/4.x', 'title': '4.x'}, - {'name': '5.x', 'number': 'debugkit/5.x', 'title': '5.x', 'current': True}, -] - -# Languages available. -languages = ['en', 'fr', 'ja', 'pt'] - -# The GitHub branch name for this version of the docs -# for edit links to point at. -branch = '5.x' - -# Current version being built -version = '5.x' - -# Language in use for this directory. -language = 'en' - -show_root_link = True - -repository = 'cakephp/debug_kit' - -source_path = 'docs/' - -hide_page_contents = ('search', '404', 'contents') - -# DebugKit docs use mp4 videos to show the UI -extensions.append('sphinxcontrib.video') diff --git a/docs/en/api-requests.md b/docs/en/api-requests.md new file mode 100644 index 000000000..57a96be56 --- /dev/null +++ b/docs/en/api-requests.md @@ -0,0 +1,21 @@ +# API Requests + +If your application is API-only and does not render a frontend, you can still inspect DebugKit toolbar data directly. + +Open the toolbar endpoint with the request's DebugKit ID: + +```text +http://localhost/debug-kit/toolbar/ +``` + +The `` value is returned in the response headers: + +```text +X-DEBUGKIT-ID: 5ef39604-ad5d-4ca4-85d8-8595e52373bb +``` + +For example: + +```text +http://localhost/debug-kit/toolbar/5ef39604-ad5d-4ca4-85d8-8595e52373bb +``` diff --git a/docs/en/conf.py b/docs/en/conf.py deleted file mode 100644 index f638bda22..000000000 --- a/docs/en/conf.py +++ /dev/null @@ -1,9 +0,0 @@ -import sys, os - -# Append the top level directory of the docs, so we can import from the config dir. -sys.path.insert(0, os.path.abspath('..')) - -# Pull in all the configuration options defined in the global config file.. -from config.all import * - -language = 'en' diff --git a/docs/en/configuration.md b/docs/en/configuration.md new file mode 100644 index 000000000..6be72c48b --- /dev/null +++ b/docs/en/configuration.md @@ -0,0 +1,68 @@ +# Configuration + +DebugKit supports several configuration keys that let you tailor the toolbar for local development. + +* `DebugKit.panels` enables or disables individual panels: + +```php +// Before loading DebugKit +Configure::write('DebugKit.panels', ['DebugKit.Packages' => false]); +``` + +* `DebugKit.includeSchemaReflection` enables logging for schema reflection queries. It is disabled by default. +* `DebugKit.safeTld` defines additional local TLDs that should be considered safe: + +```php +Configure::write('DebugKit.safeTld', ['test', 'local', 'example']); +``` + +* `DebugKit.forceEnable` forces the toolbar to display. Whitelisting local TLDs is usually safer: + +```php +Configure::write('DebugKit.forceEnable', true); + +Configure::write('DebugKit.forceEnable', function () { + return $_SERVER['REMOTE_ADDR'] === '192.168.2.182'; +}); +``` + +* `DebugKit.ignorePathsPattern` skips requests whose URL matches a regex: + +```php +Configure::write('DebugKit.ignorePathsPattern', '/\.(jpg|png|gif)$/'); +``` + +* `DebugKit.ignoreAuthorization` tells DebugKit to ignore the Cake Authorization plugin for toolbar requests. It is disabled by default. +* `DebugKit.maxDepth` controls how many levels of nested data are rendered in general debug output. The default is `5`. +* `DebugKit.variablesPanelMaxDepth` controls how many levels of nested data are rendered in the Variables panel. The default is `5`. + +Increasing either depth value can cause out-of-memory errors: + +```php +Configure::write('DebugKit.maxDepth', 8); +Configure::write('DebugKit.variablesPanelMaxDepth', 8); +``` + +## Database Configuration + +By default DebugKit stores panel data in a SQLite database in your application's `tmp` directory. If `pdo_sqlite` is unavailable, define a `debug_kit` connection in `config/app.php`: + +```php +'debug_kit' => [ + 'className' => 'Cake\Database\Connection', + 'driver' => 'Cake\Database\Driver\Mysql', + 'persistent' => false, + 'host' => 'localhost', + //'port' => 'nonstandard_port_number', + 'username' => 'dbusername', + 'password' => 'dbpassword', + 'database' => 'debug_kit', + 'encoding' => 'utf8', + 'timezone' => 'UTC', + 'cacheMetadata' => true, + 'quoteIdentifiers' => false, + //'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'], +], +``` + +You can safely remove `tmp/debug_kit.sqlite` at any time. DebugKit will recreate it as needed. diff --git a/docs/en/contents.rst b/docs/en/contents.rst deleted file mode 100644 index 423e20aa4..000000000 --- a/docs/en/contents.rst +++ /dev/null @@ -1,5 +0,0 @@ -.. toctree:: - :maxdepth: 2 - :caption: CakePHP DebugKit - - /index diff --git a/docs/en/custom-panels.md b/docs/en/custom-panels.md new file mode 100644 index 000000000..a8ee18188 --- /dev/null +++ b/docs/en/custom-panels.md @@ -0,0 +1,75 @@ +# Custom Panels + +You can create custom DebugKit panels to expose application-specific debugging data. + +## Creating a Panel Class + +Place panel classes in `src/Panel`. The filename must match the class name. For example, `MyCustomPanel` should live in `src/Panel/MyCustomPanel.php`: + +```php +namespace App\Panel; + +use DebugKit\DebugPanel; + +class MyCustomPanel extends DebugPanel +{ + // ... +} +``` + +Custom panels must extend `DebugPanel`. + +## Callbacks + +Panel objects hook into the current request through the `Controller.initialize` and `Controller.shutdown` events by default. If your panel needs additional events, implement `implementedEvents()` and return the full event map your panel requires. + +The built-in panels are the best reference when you need examples. + +## Panel Elements + +Each panel should have a matching view element that renders the panel content. The element name is the underscored form of the class name: + +* `SessionPanel` maps to `session_panel.php` +* `SqllogPanel` maps to `sqllog_panel.php` + +Store panel elements in `templates/element`. + +## Custom Titles and Elements + +Panels usually infer their toolbar title and element name by convention. Override these methods when you need custom behavior: + +* `title()` sets the label shown in the toolbar. +* `elementName()` sets the element name used for rendering. + +## Panel Hook Methods + +You can implement these methods to customize collection and rendering: + +* `shutdown(EventInterface $event)` collects and prepares panel data, usually into `$this->_data`. +* `summary()` returns short summary text for the collapsed toolbar state. +* `data()` returns the serialized data exposed to the panel element. + +## Panels in Other Plugins + +Panels shipped by plugins work the same way as application panels, with one extra requirement: set `public string $plugin` to the plugin directory name so that the panel element can be resolved when rendering. + +```php +namespace MyPlugin\Panel; + +use DebugKit\DebugPanel; + +class MyCustomPanel extends DebugPanel +{ + public string $plugin = 'MyPlugin'; +} +``` + +To register application or plugin panels, update your DebugKit configuration: + +```php +// In src/Application.php bootstrap() +Configure::write('DebugKit.panels', ['App', 'MyPlugin.MyCustom']); +$this->addPlugin('DebugKit', ['bootstrap' => true]); +``` + +This keeps the default panels enabled and adds `AppPanel` plus `MyCustomPanel` from `MyPlugin`. diff --git a/docs/en/helper-functions.md b/docs/en/helper-functions.md new file mode 100644 index 000000000..3e38777cc --- /dev/null +++ b/docs/en/helper-functions.md @@ -0,0 +1,44 @@ +# Helper Functions + +DebugKit includes a few helpers for investigating queries and timing custom code paths. + +## SQL Helpers + +* `sql()` dumps the SQL for an ORM query. +* `sqld()` dumps the SQL for an ORM query and stops execution. + +## Using DebugTimer + +Use `DebugKit\DebugTimer` when you want to measure code paths that are not covered by the default timers, such as application services, controller branches, or view rendering: + +```php +use DebugKit\DebugTimer; + +public function view($id) +{ + DebugTimer::start('load_article', 'Fetching article from database'); + // Code to measure. + DebugTimer::stop('load_article'); +} +``` + +Completed custom timers appear in the Timer panel for the request. + +## Tracing Query Execution + +When you need to know where a query originated, add `SqlTraceTrait` to a table class: + +```php +use DebugKit\Model\Table\SqlTraceTrait; + +class CategoriesTable extends Table +{ + use SqlTraceTrait; +} +``` + +DebugKit adds location comments to the SQL log: + +```text +/* APP/Controller/CategoriesController.php (line 20) */ +``` diff --git a/docs/en/history-panel.md b/docs/en/history-panel.md new file mode 100644 index 000000000..90648aad8 --- /dev/null +++ b/docs/en/history-panel.md @@ -0,0 +1,9 @@ +# History Panel + +The History panel is one of DebugKit's most useful features. It lets you inspect toolbar data from previous requests, including redirects and requests that ended in errors. + +![Screenshot of the history panel](/history-panel.png) + +The panel contains a list of requests. The dot on the left marks the currently active request. Selecting any earlier request loads the panel data captured for that request. When historical data is active, the panel titles transition to make it clear that you are no longer viewing the latest request. + + diff --git a/docs/en/index.md b/docs/en/index.md new file mode 100644 index 000000000..99401eb01 --- /dev/null +++ b/docs/en/index.md @@ -0,0 +1,45 @@ +# DebugKit + +DebugKit provides a debugging toolbar and enhanced debugging tools for CakePHP applications. It lets you quickly inspect configuration data, log messages, SQL queries, timers, mail previews, request history, and more while developing locally. + +::: warning +DebugKit is only intended for use in single-user local development environments. Avoid using DebugKit in shared development, staging, or production-like environments where configuration and environment data must remain private. +::: + +## Requirements + +DebugKit stores panel data in a database. The default setup uses SQLite through `pdo_sqlite`. If SQLite is not available, define a dedicated `debug_kit` datasource instead. + +## Installation + +Install the plugin with Composer from your application's root directory: + +```bash +php composer.phar require --dev cakephp/debug_kit:"^5.0" +``` + +Then load the plugin in debug mode: + +```bash +bin/cake plugin load DebugKit --only-debug +``` + +## Troubleshooting + +If the toolbar icon does not appear in the bottom-right corner of the page, check these common issues: + +1. SQLite is not installed, and DebugKit cannot persist panel data. +2. Your hostname is not recognized as a safe development host. Add the TLD to `DebugKit.safeTld`. +3. You are using the Authorization plugin and need to set `DebugKit.ignoreAuthorization` to `true`. + +## Documentation Map + +The English documentation is split into focused sections: + +* [Configuration](/configuration) covers the available settings and database storage. +* [Toolbar Usage](/toolbar) introduces the built-in panels. +* [History Panel](/history-panel) explains request history and replaying prior requests. +* [Mail Panel](/mail-panel) shows mail capture and preview support. +* [Custom Panels](/custom-panels) explains how to build your own panels. +* [API Requests](/api-requests) covers toolbar access for API-only applications. +* [Helper Functions](/helper-functions) documents the SQL helpers, timers, and query tracing. diff --git a/docs/en/index.rst b/docs/en/index.rst deleted file mode 100644 index c3dd2abc5..000000000 --- a/docs/en/index.rst +++ /dev/null @@ -1,358 +0,0 @@ -Debug Kit -######### - -DebugKit provides a debugging toolbar and enhanced debugging tools for CakePHP -applications. It lets you quickly see configuration data, log messages, SQL -queries, and timing data for your application. - -.. warning:: - - DebugKit is only intended for use in single-user local development - environments. You should avoid using DebugKit in shared development - environments, staging environments, or any environment where you need to - keep configuration data and environment variables hidden. - -Installation -============ - -By default DebugKit is installed with the default application skeleton. If -you've removed it and want to re-install it, you can do so by running the -following from your application's ROOT directory (where composer.json file is -located):: - - php composer.phar require --dev cakephp/debug_kit "~5.0" - -Then, you need to enable the plugin by executing the following line:: - - bin/cake plugin load DebugKit - -Configuration -============= - -* ``DebugKit.panels`` - Enable or disable panels for DebugKit. You can disable any of the - standard panels by:: - - // Before loading DebugKit - Configure::write('DebugKit.panels', ['DebugKit.Packages' => false]); - -* ``DebugKit.includeSchemaReflection`` - Set to true to enable logging of schema - reflection queries. Disabled by default. - -* ``DebugKit.safeTld`` - Set an array of whitelisted TLDs for local development. - This can be used to make sure DebugKit displays on hosts it otherwise determines unsafe. :: - - // Allow e.g. http://foo.bar.test or http://my-shop.local domains locally - Configure::write('DebugKit.safeTld', ['test', 'local', 'example']); - -* ``DebugKit.forceEnable`` - Force DebugKit to display. Careful with this, it is usually - safer to simply whitelist your local TLDs. Example usage:: - - // Before loading DebugKit - Configure::write('DebugKit.forceEnable', true); - - You can also provide a callable:: - - Configure::write('DebugKit.forceEnable', function() { - return $_SERVER['REMOTE_ADDR'] === '192.168.2.182'; - }); - -* ``DebugKit.ignorePathsPattern`` - Regex pattern (including delimiter) to ignore paths. - DebugKit won't save data for request URLs that match this regex. Defaults to ``null``:: - - // Ignore image paths - Configure::write('DebugKit.ignorePathsPattern', '/\.(jpg|png|gif)$/'); - -* ``DebugKit.ignoreAuthorization`` - Set to true to ignore Cake Authorization plugin for DebugKit requests. Disabled by default. - -* ``DebugKit.maxDepth`` - Defines how many levels of nested data should be shown in general for debug output. Default is 5. - WARNING: Increasing the max depth level can lead to an out of memory error.:: - - // Show more levels - Configure::write('DebugKit.maxDepth', 8); - -* ``DebugKit.variablesPanelMaxDepth`` - Defines how many levels of nested data should be shown in the variables tab. Default is 5. - WARNING: Increasing the max depth level can lead to an out of memory error.:: - - // Show more levels - Configure::write('DebugKit.variablesPanelMaxDepth', 8); - -Database Configuration ----------------------- - -By default DebugKit will store panel data into a SQLite database in your -application's ``tmp`` directory. If you cannot install pdo_sqlite, you can -configure DebugKit to use a different database by defining a ``debug_kit`` -connection in the ``Datasources`` variable in your **config/app.php** file. For example:: - - /** - * The debug_kit connection stores DebugKit meta-data. - */ - 'debug_kit' => [ - 'className' => 'Cake\Database\Connection', - 'driver' => 'Cake\Database\Driver\Mysql', - 'persistent' => false, - 'host' => 'localhost', - //'port' => 'nonstandard_port_number', - 'username' => 'dbusername', // Your DB username here - 'password' => 'dbpassword', // Your DB password here - 'database' => 'debug_kit', - 'encoding' => 'utf8', - 'timezone' => 'UTC', - 'cacheMetadata' => true, - 'quoteIdentifiers' => false, - //'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'], - ], - -You can safely remove the **tmp/debug_kit.sqlite** file at any point. -DebugKit will regenerate it when necessary. - -Toolbar Usage -============= - -The DebugKit Toolbar is comprised of several panels, which are shown by clicking -the CakePHP icon in the bottom right-hand corner of your browser after DebugKit -has been installed and loaded. Each panel is comprised of a panel class and view -element. Typically, a panel handles the collection and display of a single type -of information such as Logs or Request information. You can choose to view panels -from the toolbar or add your own custom panels. - -Each panel lets you look at a different aspect of your application: - -* **Cache** See cache usage during a request and clear caches. -* **Environment** Display environment variables related to PHP + CakePHP. -* **History** Displays a list of previous requests, and allows you to load - and view toolbar data from previous requests. -* **Include** View the included files grouped by type. -* **Log** Display any entries made to the log files this request. -* **Packages** Display the list of packages dependencies with their actual - version and allow you to check for outdated packages. -* **Mail** Display all emails sent during the request and allow to preview - emails during development without sending them. -* **Request** Displays information about the current request, GET, POST, Cake - Parameters, Current Route information and Cookies. -* **Session** Display the information currently in the Session. -* **Sql Logs** Displays SQL logs for each database connection. -* **Timer** Display any timers that were set during the request with - ``DebugKit\DebugTimer``, and memory usage collected with - ``DebugKit\DebugMemory``. -* **Variables** Display View variables set in controller. -* **Deprecations** Display deprecation warnings in a more readable and less - disruptive format. - -Using the History Panel -======================= - -The history panel is one of the most frequently misunderstood features of -DebugKit. It provides a way to view toolbar data from previous requests, -including errors and redirects. - -.. figure:: ../_static/history-panel.png - :alt: Screenshot of the history panel in debug kit. - -As you can see, the panel contains a list of requests. On the left you can see -a dot marking the active request. Clicking any request data will load the panel -data for that request. When historical data is loaded the panel titles will -transition to indicate that alternative data has been loaded. - -.. only:: html or epub - - .. video:: ../_static/history-panel-use.mp4 - :alt: Video of history panel in action. - -Using The Mail Panel -==================== - -The mail panel allow you to track all emails sent during a request. - -.. only:: html or epub - - .. video:: ../_static/mail-panel.mp4 - :alt: Video of Mail panel in action. - -The mailer preview allows you to easily check emails during development. - -.. only:: html or epub - - .. video:: ../_static/mail-previewer.mp4 - :alt: Video of Mail panel in action. - -Creating Preview Classes ------------------------- - -In order to preview emails before sending them, you need to create a preview -class that defines the recipient and required template variables for your -mailer methods:: - - // in src/Mailer/Preview/WelcomePreview.php - namespace App\Mailer\Preview; - - use DebugKit\Mailer\MailPreview; - - class WelcomePreview extends MailPreview - { - public function welcome(): \Cake\Mailer\Mailer - { - $mailer = $this->getMailer('Welcome'); - // set any template variables and recipients for the mailer. - - return $mailer; - } - } - -MailPreview classes should live in the ``Mailer\Preview`` namespace of your -application or plugin, and use the ``Preview`` class suffix. - -Developing Your Own Panels -========================== - -You can create your own custom panels for DebugKit to help in debugging your -applications. - -Creating a Panel Class ----------------------- - -Panel Classes simply need to be placed in the **src/Panel** directory. The -filename should match the classname, so the class ``MyCustomPanel`` would be -expected to have a filename of **src/Panel/MyCustomPanel.php**:: - - namespace App\Panel; - - use DebugKit\DebugPanel; - - /** - * My Custom Panel - */ - class MyCustomPanel extends DebugPanel - { - ... - } - -Notice that custom panels are required to extend the ``DebugPanel`` class. - -Callbacks ---------- - -By default Panel objects have two callbacks, allowing them to hook into the -current request. Panels subscribe to the ``Controller.initialize`` and -``Controller.shutdown`` events. If your panel needs to subscribe to additional -events, you can use the ``implementedEvents()`` method to define all of the events -your panel is interested in. - -You should refer to the built-in panels for some examples on how you can build -panels. - -Panel Elements --------------- - -Each Panel is expected to have a view element that renders the content from the -panel. The element name must be the underscored inflection of the class name. -For example ``SessionPanel`` has an element named **session_panel.php**, and -SqllogPanel has an element named **sqllog_panel.php**. These elements should be -located in the root of your **templates/element** directory. - -Custom Titles and Elements --------------------------- - -Panels should pick up their title and element name by convention. However, if -you need to choose a custom element name or title, you can define methods to -customize your panel's behavior: - -- ``title()`` - Configure the title that is displayed in the toolbar. -- ``elementName()`` - Configure which element should be used for a given panel. - -Panel Hook Methods ------------------- - -You can also implement the following hook methods to customize how your panel -behaves and appears: - -* ``shutdown(Event $event)`` This method typically collects and prepares the - data for the panel. Data is generally stored in ``$this->_data``. -* ``summary()`` Can return a string of summary data to be displayed in the - toolbar even when a panel is collapsed. Often this is a counter, or short - summary information. -* ``data()`` Returns the panel's data to be used as element context. This hook - method lets you further manipulate the data collected in the ``shutdown()`` - method. This method **must** return data that can be serialized. - -Panels in Other Plugins ------------------------ - -Panels provided by `plugins `_ work -almost entirely the same as other plugins, with one minor difference: You must -set ``public $plugin`` to be the name of the plugin directory, so that the -panel's Elements can be located at render time:: - - namespace MyPlugin\Panel; - - use DebugKit\DebugPanel; - - class MyCustomPanel extends DebugPanel - { - public string $plugin = 'MyPlugin'; - ... - } - -To use a plugin or app panel, update your application's DebugKit configuration -to include the panel:: - - // in src/Application.php bootstrap() method add - Configure::write('DebugKit.panels', ['App', 'MyPlugin.MyCustom']); - $this->addPlugin('DebugKit', ['bootstrap' => true]); - -The above would load all the default panels as well as the ``AppPanel``, and -``MyCustomPanel`` panel from ``MyPlugin``. - -Accessing Toolbar without a frontend -==================================== - -If you have an application which only provides an API (and therefore no frontend) -the usual way of accessing the toolbar can't be used. - -Instead you have to call http://localhost/debug-kit/toolbar/```` - -The ```` can be found inside the HTTP headers of your API response. It should look something like that:: - - X-DEBUGKIT-ID: 5ef39604-ad5d-4ca4-85d8-8595e52373bb - -So you would have to call http://localhost/debug-kit/toolbar/5ef39604-ad5d-4ca4-85d8-8595e52373bb - -Helper Functions -================ - -* ``sql()`` Dumps out the SQL from an ORM query. -* ``sqld()`` Dumps out the SQL from an ORM query, and exits. - -Using DebugTimer ----------------- - -Use the `DebugTimer` to measure parts of the code that are not captured by the default timers, -such as portions of a controller action, service logic or view rendering:: - - use DebugKit\DebugTimer; - - public function view($id) - { - DebugTimer::start('load_article', 'Fetching article from database'); - // Code to measure the execution time for - DebugTimer::stop('load_article'); - } - -When that request finishes, the Timer panel will include the custom timers. - -Tracing query execution -======================= - -Sometimes you need to know where specific queries are being executed in your app. -To get this kind of information you can add the ``SqlTraceTrait`` to your Table class like so:: - - use DebugKit\Model\Table\SqlTraceTrait; - - class CategoriesTable extends Table - { - use SqlTraceTrait; - } - -This will add the following information to the SQL log:: - - /* APP/Controller/CategoriesController.php (line 20) */ diff --git a/docs/en/mail-panel.md b/docs/en/mail-panel.md new file mode 100644 index 000000000..d2a1ea17e --- /dev/null +++ b/docs/en/mail-panel.md @@ -0,0 +1,32 @@ +# Mail Panel + +The Mail panel captures all mail sent during a request so that you can inspect it safely during development. + + + +DebugKit also supports preview classes so that you can render mails without sending them. + + + +## Creating Preview Classes + +To preview mail before sending it, create a preview class that defines the recipient and any template variables required by the mailer method: + +```php +namespace App\Mailer\Preview; + +use DebugKit\Mailer\MailPreview; + +class WelcomePreview extends MailPreview +{ + public function welcome(): \Cake\Mailer\Mailer + { + $mailer = $this->getMailer('Welcome'); + // Set any template variables and recipients for the mailer. + + return $mailer; + } +} +``` + +Preview classes should live in the `Mailer\Preview` namespace of your application or plugin and use the `Preview` suffix. diff --git a/docs/en/toolbar.md b/docs/en/toolbar.md new file mode 100644 index 000000000..f4b87be52 --- /dev/null +++ b/docs/en/toolbar.md @@ -0,0 +1,21 @@ +# Toolbar Usage + +The DebugKit toolbar appears after you click the CakePHP icon in the lower-right corner of the browser. Each panel combines a panel class with a view element and focuses on a specific kind of runtime information. + +Built-in panels include: + +* **Cache** shows cache usage during the request and lets you clear caches. +* **Environment** shows PHP and CakePHP environment details. +* **History** lists previous requests and lets you inspect their panel data. +* **Include** groups included files by type. +* **Log** shows log entries created during the request. +* **Packages** lists installed dependencies, their versions, and outdated packages. +* **Mail** captures mail sent during the request and supports previews. +* **Request** shows request data, route information, cookies, and request parameters. +* **Session** displays the active session contents. +* **Sql Logs** shows SQL logs for each datasource. +* **Timer** displays timers from `DebugKit\DebugTimer` and memory readings from `DebugKit\DebugMemory`. +* **Variables** shows view variables set in the controller. +* **Deprecations** renders deprecation warnings in a less disruptive format. + +You can use the built-in panels as-is or register your own custom panels alongside them. diff --git a/docs/fr/conf.py b/docs/fr/conf.py deleted file mode 100644 index b02032efa..000000000 --- a/docs/fr/conf.py +++ /dev/null @@ -1,9 +0,0 @@ -import sys, os - -# Append the top level directory of the docs, so we can import from the config dir. -sys.path.insert(0, os.path.abspath('..')) - -# Pull in all the configuration options defined in the global config file.. -from config.all import * - -language = 'fr' diff --git a/docs/fr/contents.rst b/docs/fr/contents.rst deleted file mode 100644 index 423e20aa4..000000000 --- a/docs/fr/contents.rst +++ /dev/null @@ -1,5 +0,0 @@ -.. toctree:: - :maxdepth: 2 - :caption: CakePHP DebugKit - - /index diff --git a/docs/fr/index.md b/docs/fr/index.md new file mode 100644 index 000000000..8cb020767 --- /dev/null +++ b/docs/fr/index.md @@ -0,0 +1,128 @@ +# Debug Kit + +DebugKit est un plugin supporté par la core team qui fournit une toolbar et des outils de débogage avancés pour les applications CakePHP. Il permet d'inspecter rapidement la configuration, les logs, les requêtes SQL et les données de temps d'exécution. + +::: warning +DebugKit est destiné uniquement aux environnements de développement local à utilisateur unique. Évitez de l'utiliser sur un environnement partagé, de préproduction ou tout autre environnement où les variables d'environnement et la configuration doivent rester privées. +::: + +## Installation + +Par défaut, DebugKit est installé avec le squelette d'application. Si vous l'avez retiré, réinstallez-le depuis le répertoire racine de l'application : + +```bash +php composer.phar require --dev cakephp/debug_kit:"^5.0" +``` + +Chargez ensuite le plugin : + +```bash +bin/cake plugin load DebugKit --only-debug +``` + +## Configuration + +* `DebugKit.ignoreAuthorization` doit être défini à `true` si vous souhaitez ignorer le plugin Cake Authorization pour les requêtes DebugKit. + +## Stockage de DebugKit + +Par défaut, DebugKit utilise une base SQLite dans le répertoire `tmp` de l'application pour stocker les données des panneaux. Si vous souhaitez utiliser une autre base, définissez une connexion `debug_kit` dans `config/app.php`. + +## Utilisation de la Toolbar + +La toolbar DebugKit comprend plusieurs panneaux accessibles depuis l'icône CakePHP en bas à droite du navigateur. + +Chaque panneau inspecte un aspect différent de l'application : + +* **Cache** montre l'utilisation du cache et permet de le vider. +* **Environment** affiche les variables d'environnement liées à PHP et CakePHP. +* **History** affiche la liste des requêtes précédentes et permet de recharger leurs données. +* **Include** montre les fichiers inclus par type. +* **Log** affiche les écritures de log de la requête. +* **Packages** affiche les dépendances installées et les versions obsolètes. +* **Mail** affiche les emails envoyés pendant la requête. +* **Request** affiche les informations de requête, de route et les cookies. +* **Session** affiche le contenu de la session. +* **Sql Logs** affiche les logs SQL pour chaque connexion. +* **Timer** affiche les timers créés avec `DebugKit\\DebugTimer` ainsi que l'usage mémoire via `DebugKit\\DebugMemory`. +* **Variables** affiche les variables de vue définies par le contrôleur. + +## Utiliser le panneau History + +Le panneau History permet de consulter les données de requêtes précédentes, y compris après une erreur ou une redirection. + +![Capture d'écran du panneau History](/history-panel.png) + +Lorsque des données historiques sont chargées, les titres des panneaux changent pour indiquer que vous ne regardez plus la requête active. + + + +## Utiliser le panneau Mail + +Le panneau Mail permet de suivre tous les emails envoyés pendant une requête. + + + +## Développer vos propres panneaux + +Vous pouvez créer vos propres panneaux personnalisés pour DebugKit. + +### Créer une classe de panneau + +Les classes doivent être placées dans `src/Panel` et étendre `DebugKit\\DebugPanel` : + +```php +namespace App\Panel; + +use DebugKit\DebugPanel; + +class MyCustomPanel extends DebugPanel +{ + // ... +} +``` + +### Callbacks + +Par défaut, les panneaux s'abonnent aux événements `Controller.initialize` et `Controller.shutdown`. Si vous avez besoin d'autres événements, implémentez `implementedEvents()`. + +### Éléments de panneau + +Chaque panneau s'appuie sur un élément de vue. Le nom suit la convention underscore de la classe, par exemple `SessionPanel` devient `session_panel.php`. + +### Titres et éléments personnalisés + +Vous pouvez redéfinir : + +* `title()` pour configurer le titre de la toolbar. +* `elementName()` pour choisir l'élément utilisé. + +### Méthodes de hook + +Les méthodes suivantes permettent de personnaliser le comportement du panneau : + +* `shutdown(Event $event)` collecte les données. +* `summary()` retourne un résumé affiché dans la toolbar réduite. +* `data()` retourne des données sérialisables pour l'élément. + +### Panneaux dans d'autres plugins + +Pour un panneau fourni par un plugin, définissez `public $plugin` avec le nom du répertoire du plugin : + +```php +namespace MyPlugin\Panel; + +use DebugKit\DebugPanel; + +class MyCustomPanel extends DebugPanel +{ + public string $plugin = 'MyPlugin'; +} +``` + +Pour enregistrer un panneau applicatif ou plugin : + +```php +Configure::write('DebugKit.panels', ['App', 'MyPlugin.MyCustom']); +$this->addPlugin('DebugKit', ['bootstrap' => true]); +``` diff --git a/docs/fr/index.rst b/docs/fr/index.rst deleted file mode 100644 index bbfd7981a..000000000 --- a/docs/fr/index.rst +++ /dev/null @@ -1,239 +0,0 @@ -Debug Kit -######### - -DebugKit est un plugin supporté par la core team qui fournit une toolbar pour -vous aider à debugger les applications CakePHP plus facilement. -DebugKit fournit une barre d'outils de débuggage et des outils de débuggage -améliorés pour les applications CakePHP. Il vous permet de voir rapidement les -données de configuration, les messages de logs, les requêtes SQL et des données -de temps d'exécution pour votre application. - -.. warning:: - - DebugKit est uniquement destiné à être utilisé dans des environnements de - développement local à un seul utilisateur. Vous devez éviter d'utiliser - DebugKit dans les environnements de développement partagés, les - environnements de stagging où vous devez garder les données de configuration - et les variables d'environnement cachées. - -Installation -============ - -Par défaut DebugKit est installé avec le squelette d'application. Si vous -le retirez et voulez le réinstaller, vous pouvez le faire en lançant ce qui -suit à partir du répertoire ROOT de votre application (où le fichier -composer.json est localisé):: - - php composer.phar require --dev cakephp/debug_kit "~4.0" - -Ensuite, vous devez activer le plugin en exécutant la ligne suivante:: - - bin/cake plugin load DebugKit - -Configuration -============= - -* ``DebugKit.ignoreAuthorization`` - Définie à true pour ignorer le plugin Cake Authorization uniquement pour les requêtes DebugKit. Par défaut à false. - -Stockage de DebugKit -==================== - -Par défaut, DebugKit utilise une petite base de données SQLite dans le -répertoire ``/tmp`` de votre application pour stocker les données du panneau. -Si vous voulez que DebugKit stocke ses données ailleurs, vous pouvez définir -une connexion ``debug_kit``. - -Configuration de Base de Données --------------------------------- - -Par défaut DebugKit va stocker les données du panneau dans une base de données -SQLite dans le répertoire ``tmp`` de votre application. Si vous ne pouvez pas -installer pdo_sqlite, vous pouvez configurer DebugKit pour utiliser une base -de données différente en définissant une connexion ``debug_kit`` dans votre -fichier **config/app.php**. - -Utilisation de la Toolbar -========================= - -La Toolbar de DebugKit comprend plusieurs panneaux, qui apparaissent en -cliquant sur l'icone CakePHP dans le coin en bas à droite de la fenêtre de -votre navigateur. Une fois que la toolbar est ouverte, vous devriez voir une -série de boutons. Chacun de ces boutons s'agrandit en un panneau avec des -informations liées. - -Chaque panneau vous permet d'inspecter plusieurs aspects de votre application: - -* **Cache** Voir l'utilisation du cache pendant une requête et nettoyer les - caches. -* **Environment** Affiche les variables d'environnement liées à PHP + CakePHP. -* **History** Affiche une liste des requêtes précédentes, et vous permet de - charger et de voir les données de la toolbar des requêtes précédentes. -* **Include** Voir les fichiers inclus groupés par type. -* **Log** Affiche toute entrée faite dans les fichiers de log par cette requête. -* **Packages** Affiche la liste des dépendances avec leur version courante et - vous permet de vérifier les packages qui ne sont pas à jour. -* **Mail** Affiche tous les emails envoyés pendant la requête et permet de - prévisualiser les emails pendant le développement sans les envoyer. -* **Request** Affiche les informations sur la requête courante, GET, POST, les - paramètre de Cake, sur la Route Courante et les Cookies. -* **Session** Affiche les informations actuellement dans la Session. -* **Sql Logs** Affiche les logs SQL pour chaque connexion à la base de données. -* **Timer** Affiche tout timers qui a été défini pendant la requête avec - ``DebugKit\DebugTimer``, et l'utilisation de la mémoire collectée avec - ``DebugKit\DebugMemory``. -* **Variables** Affiche les variables de View définies dans le controller. - -Typiquement, un panneau gère la collection et affiche un type unique -d'information comme les Logs ou les informations de la Requête. Vous pouvez -choisir de voir les panneaux de la toolbar ou ajouter vos panneaux -personnalisés. - -Utiliser le Panneau d'Historique -================================ - -Le panneau d'historique est l'une des fonctionnalités les plus souvent mal -comprise de DebugKit. Elle est un moyen de voir les données de la toolbar des -requêtes précédentes, d'inclure les erreurs et les redirects. - -.. figure:: ../_static/history-panel.png - :alt: Capture d'écran du panneau historique dans debug kit. - -Comme vous pouvez le voir, le panneau contient une liste des requêtes. Sur la -gauche, vous pouvez voir un point marquant la requête actuelle. Cliquer -sur n'importe quelles données de requête va charger les données du panneau -pour cette requête. Quand les données historiques sont chargées, les titres -du panneau seront colorés pour indiquer que des données alternatives ont été -chargées. - -.. only:: html or epub - - .. video:: ../_static/history-panel-use.mp4 - :alt: Video du panneau historique en action. - -Utiliser le Panneau Mail -======================== - -Le panneau de mail vous permet de pister tous les emails envoyés pendant une -requête. - -.. only:: html or epub - - .. video:: ../_static//mail-panel.mp4 - :alt: Video du panneau Mail en action. - -La prévisualisation de mail vous permet de facilement vérifier les emails -pendant le développement. - -.. only:: html or epub - - .. video:: ../_static/img/mail-previewer.gif - :alt: Video du panneau Mail en action. - -Développer vos Propres Panneaux -=============================== - -Vous pouvez créer vos propres panneaux personnalisés pour DebugKit pour -améliorer le debug de vos applications. - -Créer une Classe Panel ----------------------- - -Les Classes Panel doivent simplement être placées dans le répertoire -**src/Panel**. Le nom de fichier doit correspondre au nom de la classe, pour -que la classe ``MyCustomPanel`` s'attende à avoir un fichier au nom -**src/Panel/MyCustomPanel.php**:: - - namespace App\Panel; - - use DebugKit\DebugPanel; - - /** - * Mon panneau Personnalisé - */ - class MyCustomPanel extends DebugPanel - { - ... - } - -Remarquez que les panneaux personnalisés doivent étendre la classe -``DebugPanel``. - -Callbacks ---------- - -Par défaut, les objets Panel ont deux callbacks, leur permettant de s'insérer -dans la requête actuelle. Les panneaux s'inscrivent aux events -``Controller.initialize`` et ``Controller.shutdown``. Si votre panneau doit -s'inscrire à des events supplémentaires, vous pouvez utiliser la méthode -``implementedEvents()`` pour définir tous les events auxquels votre panneau -doit s'intéresser. - -Vous devez vous référer aux panneaux intégrés pour avoir quelques exemples sur -la façon de construire des panneaux. - -Elements de Panneau -------------------- - -Chaque panneau s'attend à avoir un element de view qui rend le contenu du -panneau. Le nom de l'element doit être avec une inflection en underscore du -nom de la classe. -Par exemple ``SessionPanel`` a un element nommé **session_panel.ctp**, et -SqllogPanel a un element nommé **sqllog_panel.ctp**. Ces elements doivent être -localisés à la racine de votre répertoire **src/Template/Element**. - -Titres Personnalisés et Elements --------------------------------- - -Les panneaux doivent choisir leur titre et leur nom d'element par convention. -Cependant, si vous avez besoin de choisir un nom ou un titre d'element -personnalisé, vous pouvez définir des méthodes pour personnaliser le -comportement de votre panneau: - -- ``title()`` - Configure le titre qui est affiché dans la toolbar. -- ``elementName()`` Configure l'element qui doit être utilisé pour un panneau - donné. - -Méthodes de Hook pour Panneaux ------------------------------- - -Vous pouvez également implémenter les méthodes suivantes pour personnaliser -la manière dont votre panneau se comporte et s'affiche: - -* ``shutdown(Event $event)`` Cette méthode collecte et prépare les données pour - panneau. Les données sont généralement stockées dans ``$this->_data``. -* ``summary()`` Peut retourner une chaine de caractères contenu un résumé de - données qui sera affiché dans la barre lorsque le panneau est replié. C'est - souvent un compteur ou un court résumé. -* ``data()`` Retourne les données du panneau pour être utilisées dans un - element. Cette méthode vous laisse manipuler les données collectées dans - la méthode ``shutdown()``. cette méthode **doit** retourner des données - sérializables. - -Panneaux dans d'autres Plugins ------------------------------- - -Les panneaux fournis par les `plugins -`_ fonctionnent presque entièrement de -la même façon que les autres plugins, avec quelques différences mineures: Vous -devez définir ``public $plugin`` comme nom de répertoire de plugin, pour -que les elements du panneau puissent être localisés au moment de les afficher:: - - namespace MyPlugin\Panel; - - use DebugKit\DebugPanel; - - class MyCustomPanel extends DebugPanel - { - public $plugin = 'MyPlugin'; - ... - } - -Pour utiliser un panneau de plugin ou de l'application, mettez à jour -la configuration du DebugKit de votre application pour ajouter le panneau:: - - // dans config/bootstrap.php - Configure::write('DebugKit.panels', ['App', 'MyPlugin.MyCustom']); - Plugin::load('DebugKit', ['bootstrap' => true]); - -Ce qui est au-dessus charge tous les panneaux par défaut ainsi que le panneau -``AppPanel``et le panneau ``MyCustomPanel`` depuis ``MyPlugin``. diff --git a/docs/ja/conf.py b/docs/ja/conf.py deleted file mode 100644 index 5871da648..000000000 --- a/docs/ja/conf.py +++ /dev/null @@ -1,9 +0,0 @@ -import sys, os - -# Append the top level directory of the docs, so we can import from the config dir. -sys.path.insert(0, os.path.abspath('..')) - -# Pull in all the configuration options defined in the global config file.. -from config.all import * - -language = 'ja' diff --git a/docs/ja/contents.rst b/docs/ja/contents.rst deleted file mode 100644 index 423e20aa4..000000000 --- a/docs/ja/contents.rst +++ /dev/null @@ -1,5 +0,0 @@ -.. toctree:: - :maxdepth: 2 - :caption: CakePHP DebugKit - - /index diff --git a/docs/ja/index.md b/docs/ja/index.md new file mode 100644 index 000000000..4715ae4ea --- /dev/null +++ b/docs/ja/index.md @@ -0,0 +1,150 @@ +# Debug Kit + +DebugKit は CakePHP アプリケーション向けのデバッグツールバーと拡張デバッグツールを提供します。設定データ、ログメッセージ、SQL クエリー、実行時間情報をすばやく確認できます。 + +::: warning +DebugKit は単一ユーザーのローカル開発環境でのみ使用してください。共有開発環境、ステージング環境、本番に近い環境では使用しないでください。 +::: + +## インストール + +アプリケーションのルートディレクトリーで次を実行します。 + +```bash +php composer.phar require --dev cakephp/debug_kit:"^5.0" +``` + +続いてプラグインを有効化します。 + +```bash +bin/cake plugin load DebugKit --only-debug +``` + +## 設定 + +* `DebugKit.panels` で各パネルの有効化と無効化ができます。 +* `DebugKit.includeSchemaReflection` を `true` にするとスキーマリフレクションのクエリーを記録します。 +* `DebugKit.safeTld` でローカル開発用の TLD を追加できます。 +* `DebugKit.forceEnable` で DebugKit を強制表示できます。 + +## データベース設定 + +デフォルトでは `tmp` ディレクトリー内の SQLite データベースにパネルデータを保存します。`pdo_sqlite` が使えない場合は、`config/app.php` に `debug_kit` コネクションを定義してください。 + +## ツールバーの使い方 + +DebugKit ツールバーはブラウザー右下の CakePHP アイコンから開けます。各パネルはアプリケーションの異なる側面を表示します。 + +* **Cache** キャッシュ使用状況の確認と削除。 +* **Environment** PHP と CakePHP の環境情報。 +* **History** 過去のリクエスト一覧とそのデータの再表示。 +* **Include** 読み込まれたファイル一覧。 +* **Log** リクエスト中に書かれたログ。 +* **Packages** 依存パッケージとバージョン情報。 +* **Mail** 送信メールの確認とプレビュー。 +* **Request** 現在のリクエスト情報、ルート、Cookie。 +* **Session** セッション内容。 +* **Sql Logs** 接続ごとの SQL ログ。 +* **Timer** `DebugKit\\DebugTimer` と `DebugKit\\DebugMemory` の情報。 +* **Variables** ビュー変数。 + +## 履歴パネルを使う + +履歴パネルではエラーやリダイレクトを含む過去のリクエストを確認できます。 + +![履歴パネルのスクリーンショット](/history-panel.png) + +過去のデータが読み込まれると、パネルタイトルが切り替わり、現在のリクエストではないことが分かります。 + + + +## メールパネルを使う + +メールパネルではリクエスト中に送信されたすべてのメールを確認できます。 + + + +メールプレビューを使うと、送信前に内容を確認できます。 + + + +### プレビュークラスの作成 + +```php +namespace App\Mailer\Preview; + +use DebugKit\Mailer\MailPreview; + +class WelcomePreview extends MailPreview +{ + public function welcome(): \Cake\Mailer\Mailer + { + $mailer = $this->getMailer('Welcome'); + + return $mailer; + } +} +``` + +`MailPreview` クラスは `Mailer\Preview` 名前空間に配置し、クラス名は `Preview` で終える必要があります。 + +## 独自パネルの開発 + +### パネルクラスを作成する + +パネルクラスは `src/Panel` に配置し、`DebugPanel` を継承します。 + +```php +namespace App\Panel; + +use DebugKit\DebugPanel; + +class MyCustomPanel extends DebugPanel +{ + // ... +} +``` + +### コールバック + +デフォルトでは `Controller.initialize` と `Controller.shutdown` を購読します。追加イベントが必要なら `implementedEvents()` を定義してください。 + +### パネル要素 + +パネル表示用のビュー要素を用意します。名前はクラス名のアンダースコア形式です。例えば `SessionPanel` は `session_panel.php` を使います。 + +### カスタムタイトルとエレメント + +* `title()` はツールバー上のタイトルを設定します。 +* `elementName()` は使用するエレメント名を設定します。 + +### パネルフックメソッド + +* `shutdown(Event $event)` はデータを収集します。 +* `summary()` は折りたたみ時のサマリー文字列を返します。 +* `data()` はシリアライズ可能なパネルデータを返します。 + +### 他のプラグインのパネル + +```php +namespace MyPlugin\Panel; + +use DebugKit\DebugPanel; + +class MyCustomPanel extends DebugPanel +{ + public string $plugin = 'MyPlugin'; +} +``` + +アプリケーションまたはプラグインのパネルを追加するには、DebugKit 設定を更新します。 + +```php +Configure::write('DebugKit.panels', ['App', 'MyPlugin.MyCustom']); +$this->addPlugin('DebugKit', ['bootstrap' => true]); +``` + +## ヘルパー関数 + +* `sql()` は ORM クエリーの SQL をダンプします。 +* `sqld()` は ORM クエリーの SQL をダンプして終了します。 diff --git a/docs/ja/index.rst b/docs/ja/index.rst deleted file mode 100644 index 5ff72bc20..000000000 --- a/docs/ja/index.rst +++ /dev/null @@ -1,267 +0,0 @@ -Debug Kit -######### - -DebugKit は、CakePHP アプリケーション用のデバッグツールバーと拡張デバッグツールを提供します。 -アプリケーションの設定データ、ログメッセージ、SQL クエリー、およびタイミングデータをすばやく -確認できます。 - -.. warning:: - - DebugKit は、シングルユーザーのローカル開発環境での使用を目的としています。 - 共有開発環境、ステージング環境、または設定データと環境変数を隠しておく必要がある環境では、 - DebugKit を使用しないでください。 - -インストール -============ - -デフォルトで、DebugKit はデフォルトのアプリケーションスケルトンにインストールされています。 -もし削除してしまって再インストールしたい場合は、以下のコマンドをアプリケーションの -ルートディレクトリー (composer.json ファイルのある場所) で実行してください。 :: - - php composer.phar require --dev cakephp/debug_kit "~4.0" - -そして以下のコマンドでプラグインを有効化する必要があります。 :: - - bin/cake plugin load DebugKit - -設定 -==== - -* ``DebugKit.panels`` - DebugKit のパネルを有効化または無効化します。 - 次のようにして、任意の標準パネルを無効にすることができます。 :: - - // DebugKit をロードする前に - Configure::write('DebugKit.panels', ['DebugKit.Packages' => false]); - -* ``DebugKit.includeSchemaReflection`` - スキーマリフレクションクエリーの - ロギングを有効にするには、true に設定します。デフォルトは無効になっています。 - -* ``DebugKit.safeTld`` - ローカル開発用のトップレベルドメインのホワイトリストを設定します。 - これにより安全でないと判断したホスト上で DebugKit を表示できるようになります。 :: - - // 例: http://foo.bar.dev または http://my-shop.local のドメインはローカルとして許可する - Configure::write('DebugKit.safeTld', ['dev', 'local', 'example']); - -* ``DebugKit.forceEnable`` - DebugKit を強制的に表示します。これを使うときは注意してください。 - 通常は単純にローカルのトップレベルドメインをホワイトリストに追加したほうが安全です。 使用例:: - - // DebugKit をロードする前に - Configure::write('DebugKit.forceEnable', true); - -データベース設定 ----------------- - -デフォルトでは DebugKit はアプリケーションの ``/tmp`` 内の SQLite データベースに -パネルデータを保持します。もし pdo_sqlite をインストールできない場合は、 -**config/app.php** ファイル に ``debug_kit`` コネクションを定義すると -DebugKit が異なるデータベースを使用するように設定できます。例:: - - /** - * debug_kit コネクションは DebugKit のメタデータを格納します。 - */ - 'debug_kit' => [ - 'className' => 'Cake\Database\Connection', - 'driver' => 'Cake\Database\Driver\Mysql', - 'persistent' => false, - 'host' => 'localhost', - //'port' => 'nonstandard_port_number', - 'username' => 'dbusername', // Your DB username here - 'password' => 'dbpassword', // Your DB password here - 'database' => 'debug_kit', - 'encoding' => 'utf8', - 'timezone' => 'UTC', - 'cacheMetadata' => true, - 'quoteIdentifiers' => false, - //'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'], - ], - -**tmp/debug_kit.sqlite** ファイルは、いつでも削除することができます。 -DebugKit は、必要に応じて、それを再生成します。 - -ツールバーの使い方 -================== - -DebugKit ツールバーは、いくつかのパネルで構成されています。これらのパネルは、 -DebugKit をインストールしてロードした後、ブラウザーの右下隅にある CakePHP -アイコンをクリックすると表示されます。各パネルは、パネルクラスとビューエレメントで構成されています。 -一般的に、パネルは単一の種類の情報のコレクションの処理やログやリクエスト情報の表示を行います。 -ツールバーからパネルを表示したり、独自のカスタムパネルを追加することを選択できます。 - -各パネルはアプリケーションの様々な側面を見せてくれます。 - -* **Cache** リクエスト中のキャッシュの使用状況の確認とキャッシュのクリアー。 -* **Environment** PHP 及び CakePHP に関連する環境変数の表示。 -* **History** 以前のリクエストの一覧の表示と、以前のリクエストのツールバーデータの読み込みと表示。 -* **Include** タイプごとにグループ化されたインクルードファイルを表示。 -* **Log** このリクエスト中にログファイルに加えられたすべてのエントリーを表示。 -* **Packages** 現在のバージョンのパッケージの依存関係の一覧を表示し、 - 古いパッケージをチェックすることができます。 -* **Mail** このリクエスト中の全てのメール送信を表示し、 - 送信せずに開発中のメールのプレビューができます。 -* **Request** 現在のリクエスト、GET、POST、Cake パラメーター、現在のルート情報、クッキー情報の表示。 -* **Session** 現在のセッション情報の表示。 -* **Sql Logs** 各データベースコネクションの SQL ログの表示。 -* **Timer** リクエスト中に ``DebugKit\DebugTimer`` で設定されたすべてのタイマーと、 - ``DebugKit\DebugMemory`` で収集されたメモリー使用状況の表示。 -* **Variables** コントローラーでセットされたビュー変数の表示。 - -履歴パネルを使用する -==================== - -履歴パネルは DebugKit で最も勘違いされやすい機能の一つです。 -エラーやリダイレクトを含む以前のリクエストのツールバーのデータを表示することができます。 - -.. figure:: ../_static/history-panel.png - :alt: Screenshot of the history panel in debug kit. - -ご覧のようにパネルにはリクエストの一覧が含まれます。左側にドットがついているのがアクティブな -リクエストです。どれかのリクエストをクリックするとそのリクエストのデータが読み込まれます。 -履歴データがロードされると代替のデータが読み込まれたことを示すようにパネルのタイトルが遷移します。 - -.. only:: html or epub - - .. video:: ../_static/history-panel-use.mp4 - :alt: Video of history panel in action. - -メールパネルを使用 -================== - -メールパネルは、リクエストの間に送信された全てのメールを追跡することができます。 - -.. only:: html or epub - - .. video:: ../_static/mail-panel.mp4 - :alt: Video of mail panel in action - -メーラープレビューは、開発中のメールを簡単にプレビューすることができます。 - -.. only:: html or epub - - .. video:: ../_static/mail-previewer.mp4 - :alt: Video of mail panel in action - -プレビュークラスの作成 ------------------------- - -メールを送信する前にプレビューするには、受信者と mailer メソッドに必要なテンプレート変数を -定義するプレビュークラスを作成する必要があります。 :: - - // src/Mailer/MailPreview/WelcomePreview.php の中で - namespace App\Mailer\Preview; - - use DebugKit\Mailer\MailPreview; - - class WelcomePreview extends MailPreview - { - public function welcome() - { - $mailer = $this->getMailer('Welcome'); - // メーラーのテンプレート変数受信者を設定します。 - - return $mailer; - } - } - -MailPreview クラスは、 アプリケーションまたはプラグインの ``Mailer\Preview`` -名前空間に存在し、 ``Preview`` を使用する必要があります。 - -独自のパネルを開発する -====================== - -アプリケーションのデバッグを補助するための DebugKit の独自のカスタムパネルを -作成することができます。 - -パネルクラスを作成する ----------------------- - -パネルクラスは単に **src/Panel** ディレクトリーに設置してください。ファイル名はクラス名と -一致する必要があります。 つまり ``MyCustomPanel`` クラスは -**src/Panel/MyCustomPanel.php** というファイル名であることを想定しています。 :: - - namespace App\Panel; - - use DebugKit\DebugPanel; - - /** - * My Custom Panel - */ - class MyCustomPanel extends DebugPanel - { - ... - } - -カスタムパネルは ``DebugPanel`` クラスを拡張する必要があることに注意してください。 - -コールバック ------------- - -デフォルトではパネルオブジェクトには、現在のリクエストをフックすることができる -2つのコールバックがあります。パネルは ``Controller.initialize`` と -``Controller.shutdown`` のイベントを取得します。もしパネルが追加のイベントを -取得したい場合は、 ``implementedEvents()`` メソッドを使用し、 -パネルが必要とするすべてのイベントを定義できます。 - -どのようにパネルを構築するかについてのいくつかの例として、ビルトインのパネルを参照してください。 - -パネルの構成要素 ----------------- - -各パネルはパネルのコンテンツを描画するためのビューエレメントがあることを想定しています。 -エレメント名はアンダースコアー区切りのクラス名である必要があります。 -たとえば、 ``SessionPanel`` は **session_panel.ctp** という名前のエレメントを持ちます。 -また、SqllogPanelは **sqllog_panel.ctp** という名前のエレメントを持ちます。 -これらのエレメントは **src/Template/Element** ディレクトリーのルートに設置する必要があります。 - -カスタムのタイトルとエレメント ------------------------------- - -パネルは慣例を元にそのタイトルとエレメント名を補足します。もしカスタムのタイトルやエレメント名を -付けたい場合は、パネルの振る舞いをカスタムするメソッドを定義することができます。 - -- ``title()`` - ツールバー上に表示されるタイトルを設定します -- ``elementName()`` - 与えられたパネルがどのエレメントを使用するかを設定します - -パネルフックメソッド --------------------- - -また、パネルの動作や表示方法をカスタムするために以下のフックメソッドを実装することができます。 - -* ``shutdown(Event $event)`` このメソッドは通常はパネルのデータの収集と準備を行います。 -* ``summary()`` パネルが折りたたまれている時に表示されるサマリーデータの文字列を - 返すことができます。多くの場合、これは件数や短いサマリー情報です。 -* ``data()`` エレメントのコンテキストで使用されるパネルのデータを返します。 - このフックメソッドは ``shutdown()`` で収集されるデータを更に操作することができます。 - このメソッドはシリアライズ化可能なデータを **必ず** 返す必要があります。 - -他のプラグインのパネル ----------------------- - -パネルはひとつの小さな違いを除き、`plugins `_ -とほぼ同じ動作を提供します。レンダリング時にパネルのエレメントを配置できるように、 -``public $plugin`` にプラグインディレクトリーの名前を必ずセットする必要があります。 :: - - namespace MyPlugin\Panel; - - use DebugKit\DebugPanel; - - class MyCustomPanel extends DebugPanel - { - public $plugin = 'MyPlugin'; - ... - } - -プラグインやアプリケーションパネルを使用するには、アプリケーションの DebugKit の設定を -更新します。 :: - - // src/Application.php の bootstrap() メソッドの中に追加 - Configure::write('DebugKit.panels', ['App', 'MyPlugin.MyCustom']); - $this->addPlugin('DebugKit', ['bootstrap' => true]); - -上記は、すべてのデフォルトのパネルと同じように ``AppPanel`` と ``MyPlugin`` の -``MyCustomPanel`` パネルを読みこみます。 - -ヘルパー関数 -================ - -* ``sql()`` ORM クエリーから SQL をダンプします。 -* ``sqld()`` ORM クエリーから SQL をダンプして終了します。 diff --git a/docs/package.json b/docs/package.json new file mode 100644 index 000000000..f1407730a --- /dev/null +++ b/docs/package.json @@ -0,0 +1,19 @@ +{ + "name": "docs", + "version": "1.0.0", + "description": "", + "main": "config.js", + "scripts": { + "docs:dev": "vitepress dev", + "docs:build": "vitepress build", + "docs:preview": "vitepress preview" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "module", + "dependencies": { + "@cakephp/docs-skeleton": "git+ssh://git@github.com:cakephp/docs-skeleton.git#node-package", + "vitepress": "^2.0.0-alpha.16" + } +} diff --git a/docs/pt/conf.py b/docs/pt/conf.py deleted file mode 100644 index 9e22cb017..000000000 --- a/docs/pt/conf.py +++ /dev/null @@ -1,9 +0,0 @@ -import sys, os - -# Append the top level directory of the docs, so we can import from the config dir. -sys.path.insert(0, os.path.abspath('..')) - -# Pull in all the configuration options defined in the global config file.. -from config.all import * - -language = 'pt' diff --git a/docs/pt/contents.rst b/docs/pt/contents.rst deleted file mode 100644 index 423e20aa4..000000000 --- a/docs/pt/contents.rst +++ /dev/null @@ -1,5 +0,0 @@ -.. toctree:: - :maxdepth: 2 - :caption: CakePHP DebugKit - - /index diff --git a/docs/pt/index.md b/docs/pt/index.md new file mode 100644 index 000000000..460609d04 --- /dev/null +++ b/docs/pt/index.md @@ -0,0 +1,112 @@ +# Debug Kit + +DebugKit oferece uma barra de ferramentas de depuração e ferramentas avançadas para aplicações CakePHP. Ele permite visualizar rapidamente dados de configuração, mensagens de log, consultas SQL e informações de tempo de execução. + +::: warning +DebugKit deve ser usado apenas em ambientes locais de desenvolvimento para um único usuário. Evite utilizá-lo em ambientes compartilhados, de homologação ou próximos de produção. +::: + +## Instalação + +No diretório raiz da aplicação, execute: + +```bash +php composer.phar require --dev cakephp/debug_kit:"^5.0" +``` + +Depois carregue o plugin: + +```bash +bin/cake plugin load DebugKit --only-debug +``` + +## Armazenamento do DebugKit + +Por padrão, o DebugKit usa um banco SQLite no diretório `tmp` da aplicação para armazenar os dados dos painéis. Se quiser usar outro banco, defina uma conexão `debug_kit` em `config/app.php`. + +## Uso da barra de ferramentas + +A toolbar do DebugKit é exibida ao clicar no ícone do CakePHP no canto inferior direito do navegador. + +Cada painel mostra uma parte diferente da aplicação: + +* **Cache** mostra o uso de cache e permite limpá-lo. +* **Environment** exibe variáveis de ambiente relacionadas a PHP e CakePHP. +* **History** mostra requisições anteriores e permite recarregar seus dados. +* **Include** exibe os arquivos incluídos por tipo. +* **Log** mostra as entradas de log da requisição. +* **Request** exibe dados da requisição atual, rota e cookies. +* **Session** exibe o conteúdo da sessão. +* **Sql Logs** mostra logs SQL por conexão. +* **Timer** exibe timers criados com `DebugKit\\DebugTimer` e dados de memória com `DebugKit\\DebugMemory`. +* **Variables** exibe variáveis de view definidas no controller. + +## Usando o painel History + +O painel History permite revisar dados de requisições anteriores, incluindo erros e redirecionamentos. + +![Screenshot do painel History](/history-panel.png) + + + +## Desenvolvendo seus próprios painéis + +Você pode criar painéis personalizados para expor dados específicos da sua aplicação. + +### Criando uma classe de painel + +As classes devem ser colocadas em `src/Panel` e estender `DebugKit\DebugPanel`: + +```php +namespace App\Panel; + +use DebugKit\DebugPanel; + +class MyCustomPanel extends DebugPanel +{ + // ... +} +``` + +### Callbacks + +Por padrão os painéis se inscrevem nos eventos `Controller.initialize` e `Controller.shutdown`. Se precisar de eventos adicionais, implemente `implementedEvents()`. + +### Elementos do painel + +Cada painel precisa de um elemento de view. O nome deve ser a versão underscore do nome da classe, por exemplo `session_panel.php`. + +### Títulos e elementos personalizados + +Você pode sobrescrever: + +* `title()` para definir o título na toolbar. +* `elementName()` para escolher qual elemento renderizar. + +### Métodos de hook + +* `shutdown(Event $event)` coleta e prepara os dados do painel. +* `summary()` retorna um resumo curto para a toolbar recolhida. +* `data()` retorna dados serializáveis usados pelo elemento. + +### Painéis em outros plugins + +```php +namespace MyPlugin\Panel; + +use DebugKit\DebugPanel; + +class MyCustomPanel extends DebugPanel +{ + public string $plugin = 'MyPlugin'; +} +``` + +Para registrar um painel do aplicativo ou de plugin: + +```php +Configure::write( + 'DebugKit.panels', + array_merge(Configure::read('DebugKit.panels'), ['MyCustomPanel']) +); +``` diff --git a/docs/pt/index.rst b/docs/pt/index.rst deleted file mode 100644 index e5ba22bc0..000000000 --- a/docs/pt/index.rst +++ /dev/null @@ -1,216 +0,0 @@ -Debug Kit -######### - -DebugKit é um plugin suportado pelo time principal do CakePHP que oferece uma -barra de ferramentas para auxiliar na depuração de aplicações do CakePHP. - -Instalação -========== - -Por padrão o DebugKit é instalado com o esqueleto padrão da aplicação. Se -você o removeu e gostaria de reinstalá-lo, você pode executar o seguinte comando -a partir do diretório raiz da aplicação -(onde o arquivo composer.json está localizado):: - - php composer.phar require --dev cakephp/debug_kit "~4.0" - -Então, você precisará habilitar o plugin ao executar o seguinte comando:: - - bin/cake plugin load DebugKit - -Armazenamento do DebugKit -========================= - -Por padrão, o DebugKit usa um pequeno banco de dados SQLite no diretório -``/tmp`` de sua aplicação para armazenar os dados referentes ao painel -de informações. Se você quiser que o DebugKit armazene seus dados em outro -lugar, é necessário configurar uma nova conexão com o nome ``debug_kit`` . - -Configuração do banco de dados ------------------------------- - -Como informado anteriormente, por padrão, o DebugKit armazenará os dados do -painel em um banco de dados SQLite no diretório ``/tmp`` de sua aplicação. Se -você não puder instalar a extensão pdo_sqlite do PHP, você pode configurar o -DebugKit para usar um banco de dados diferente ao definir uma conexão -``debug_kit`` em seu arquivo **config/app.php**. Por exemplo:: - - /** - * A conexão debug_kit armazena meta-dados do DebugKit. - */ - 'debug_kit' => [ - 'className' => 'Cake\Database\Connection', - 'driver' => 'Cake\Database\Driver\Mysql', - 'persistent' => false, - 'host' => 'localhost', - //'port' => 'nonstandard_port_number', - 'username' => 'dbusername', // Your DB username here - 'password' => 'dbpassword', // Your DB password here - 'database' => 'debug_kit', - 'encoding' => 'utf8', - 'timezone' => 'UTC', - 'cacheMetadata' => true, - 'quoteIdentifiers' => false, - //'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'], - ], - -Uso da barra de ferramentas -=========================== - -A barra de ferramentas do DebugKit é composta por vários painéis, que são -exibidos ao clicar no ícone do CakePHP no canto inferior direito da janela do -seu navegador. Uma vez que a barra de ferramentas é aberta, você deverá ver uma -série de botões. Cada um desses botões se expande em um painel de informações -relacionadas. - -Cada painel permite a você observar aspectos diferentes da sua aplicação: - -* **Cache** Exibe o uso de cache durante uma solicitação e limpa caches. -* **Environment** Exibe variáveis de ambiente relacionadas com PHP + CakePHP. -* **History** Exibe uma lista de requisições anteriores, e permite que você - carregue e veja dados da barra de ferramentas a partir de solicitações - anteriores. -* **Include** Exibe os arquivos inclusos divididos por grupo. -* **Log** Exibe todas as entradas feitas nos arquivos de log este pedido. -* **Request** Exibe informações sobre a requisição atual, GET, POST, informações - sobre a rota atual do Cake e Cookies. -* **Session** Exibe a informação atual da sessão. -* **Sql Logs** Exibe logs SQL para cada conexão com o banco de dados. -* **Timer** Exibe qualquer temporizador que fora definido durante a requisição - com ``DebugKit\DebugTimer``, e memória utilizada coletada com - ``DebugKit\DebugMemory``. -* **Variables** Exibe variáveis de View definidas em um Controller. - -Tipicamente, um painel manipula a recolha e apresentação de um único tipo -de informações como logs ou informações de requisições. Você pode optar por -visualizar os painéis padrões da barra de ferramentas ou adicionar seus próprios -painéis personalizados. - -Usando o painel History -======================= - -O painel History é uma das características mais frequentemente confundidas do -DebugKit. Ele oferece uma forma de visualizar os dados de requisições -anteriores na barra de ferramentas, incluindo erros e redirecionamentos. - -.. figure:: ../_static/history-panel.png - :alt: Screenshot do painel History no DebugKit. - -Como você pode ver, o painel contém uma lista de requisições. Na esquerda você -pode ver um ponto marcando a requisição ativa. Clicar em qualquer requisição vai -carregar os dados referentes a mesma no painel. Quando os dados são carregados, -os títulos do painel vão sofrer uma transição para indicar que informações -alternativos foram carregados. - -.. only:: html or epub - - .. video:: ../_static/history-panel-use.mp4 - :alt: Video do painel History em ação. - -Desenvolvendo seus próprios painéis -=================================== - -Você pode criar seus próprios painéis customizados do DebugKit para ajudar -na depuração de suas aplicações. - -Criando uma Panel Class ------------------------ - -Panel Classes precisam ser colocadas no diretório **src/Panel**. O -nome do arquivo deve combinar com o nome da classe, então a classe -``MyCustomPanel`` deveria remeter ao nome de arquivo -**src/Panel/MyCustomPanel.php**:: - - namespace App\Panel; - - use DebugKit\DebugPanel; - - /** - * My Custom Panel - */ - class MyCustomPanel extends DebugPanel - { - ... - } - -Perceba que painéis customizados são necessários para extender a classe -``DebugPanel``. - -Callbacks ---------- - -Por padrão objetos do painel possuem dois callbacks, permitindo-lhes acoplar-se -na requisição atual. Painéis inscrevem-se aos eventos ``Controller.initialize`` -e ``Controller.shutdown``. Se o seu painel precisa inscrever-se a eventos -adicionais, você pode usar o método ``implementedEvents`` para definir todos os -eventos aos quais o seu painel possa precisar estar inscrito. - -Você deveria estudar os painéis nativos para absorver alguns exemplos de como -construir painéis. - -Elementos do painel -------------------- - -Cada painel deve ter um elemento view que renderiza o conteúdo do mesmo. -O nome do elemento deve ser sublinhado e flexionado a partir do nome da classe. -Por exemplo ``SessionPanel`` deve possuir um elemento nomeado -**session_panel.ctp**, e SqllogPanel deve possuir um elemento nomeado -**sqllog_panel.ctp**. Estes elementos devem estar localizados na raiz do seu -diretório **src/Template/Element**. - -Títulos personalizados e Elementos ----------------------------------- - -Os painéis devem relacionar o seu título e o nome do elemento por convenção. No -entanto, se você precisa escolher um nome de elemento personalizado ou título, -você pode definir métodos para customizar o comportamento do seu painel: - -- ``title()`` - Configure o título que é exibido na barra de ferramentas. -- ``elementName()`` - Configure qual elemento deve ser utilizada para um - determinado painel. - -Métodos de captura ------------------- - -Você também pode implementar os seguintes métodos para customizar como o seu -painel se comporta e se aparenta: - -* ``shutdown(Event $event)`` Esse método coleta e prepara os dados para o - painel. Os dados são geralmente armazenados em ``$this->_data``. -* ``summary()`` Este método retorna uma *string* de dados resumidos para serem - exibidos na *toolbar*, mesmo quando um painel está minimizado. Frequentemente, - é um contador ou um pequeno resumo de informações. -* ``data()`` Este método retorna os dados do painel que serão usados como - contexto para o elemento. Você pode manipular os dados coletados no método - ``shutdown()``. Esse método **deve** retornar dados que podem ser - serializados. - -Painéis em outros plugins -------------------------- - -Painéis disponibilizados por `plugins -`_ funcionam quase que totalmente -como outros plugins, com uma pequena diferença: Você deve definir ``public -$plugin`` como o nome do diretório do plugin, com isso os elementos do painel -poderão ser encontrados no momento de renderização:: - - namespace MyPlugin\Panel; - - use DebugKit\DebugPanel; - - class MyCustomPanel extends DebugPanel - { - public $plugin = 'MyPlugin'; - ... - } - -Para usar um plugin ou painel da aplicação, atualize a configuração do DebugKit -de sua aplicação para incluir o painel:: - - Configure::write( - 'DebugKit.panels', - array_merge(Configure::read('DebugKit.panels'), ['MyCustomPanel']) - ); - -O código acima deve carregar todos os painéis padrão tanto como os outros -painéis customizados do ``MyPlugin``. diff --git a/docs/public/favicon/apple-touch-icon.png b/docs/public/favicon/apple-touch-icon.png new file mode 100644 index 000000000..c6d073d7b Binary files /dev/null and b/docs/public/favicon/apple-touch-icon.png differ diff --git a/docs/public/favicon/favicon-96x96.png b/docs/public/favicon/favicon-96x96.png new file mode 100644 index 000000000..6642e0cda Binary files /dev/null and b/docs/public/favicon/favicon-96x96.png differ diff --git a/docs/public/favicon/favicon.ico b/docs/public/favicon/favicon.ico new file mode 100644 index 000000000..405aa94ce Binary files /dev/null and b/docs/public/favicon/favicon.ico differ diff --git a/docs/public/favicon/favicon.svg b/docs/public/favicon/favicon.svg new file mode 100644 index 000000000..805ef4b8f --- /dev/null +++ b/docs/public/favicon/favicon.svg @@ -0,0 +1,3 @@ + \ No newline at end of file diff --git a/docs/public/favicon/site.webmanifest b/docs/public/favicon/site.webmanifest new file mode 100644 index 000000000..4f23fb31d --- /dev/null +++ b/docs/public/favicon/site.webmanifest @@ -0,0 +1,21 @@ +{ + "name": "CakePHP", + "short_name": "CakePHP", + "icons": [ + { + "src": "/favicon/web-app-manifest-192x192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "/favicon/web-app-manifest-512x512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ], + "theme_color": "#ffffff", + "background_color": "#ffffff", + "display": "standalone" +} \ No newline at end of file diff --git a/docs/public/favicon/web-app-manifest-192x192.png b/docs/public/favicon/web-app-manifest-192x192.png new file mode 100644 index 000000000..b5df2990b Binary files /dev/null and b/docs/public/favicon/web-app-manifest-192x192.png differ diff --git a/docs/public/favicon/web-app-manifest-512x512.png b/docs/public/favicon/web-app-manifest-512x512.png new file mode 100644 index 000000000..6a522de35 Binary files /dev/null and b/docs/public/favicon/web-app-manifest-512x512.png differ diff --git a/docs/public/fonts/cakedingbats-webfont.eot b/docs/public/fonts/cakedingbats-webfont.eot new file mode 100644 index 000000000..0800d1e7d Binary files /dev/null and b/docs/public/fonts/cakedingbats-webfont.eot differ diff --git a/docs/public/fonts/cakedingbats-webfont.svg b/docs/public/fonts/cakedingbats-webfont.svg new file mode 100644 index 000000000..d2afda5e2 --- /dev/null +++ b/docs/public/fonts/cakedingbats-webfont.svg @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/public/fonts/cakedingbats-webfont.ttf b/docs/public/fonts/cakedingbats-webfont.ttf new file mode 100644 index 000000000..78ad6c884 Binary files /dev/null and b/docs/public/fonts/cakedingbats-webfont.ttf differ diff --git a/docs/public/fonts/cakedingbats-webfont.woff b/docs/public/fonts/cakedingbats-webfont.woff new file mode 100644 index 000000000..a95e1b38b Binary files /dev/null and b/docs/public/fonts/cakedingbats-webfont.woff differ diff --git a/docs/public/fonts/cakedingbats-webfont.woff2 b/docs/public/fonts/cakedingbats-webfont.woff2 new file mode 100644 index 000000000..2cd9fdd0e Binary files /dev/null and b/docs/public/fonts/cakedingbats-webfont.woff2 differ diff --git a/docs/_static/history-panel-use.mp4 b/docs/public/history-panel-use.mp4 similarity index 100% rename from docs/_static/history-panel-use.mp4 rename to docs/public/history-panel-use.mp4 diff --git a/docs/_static/history-panel.png b/docs/public/history-panel.png similarity index 100% rename from docs/_static/history-panel.png rename to docs/public/history-panel.png diff --git a/docs/public/icons/batteries_included_chiffon.svg b/docs/public/icons/batteries_included_chiffon.svg new file mode 100644 index 000000000..1972a9673 --- /dev/null +++ b/docs/public/icons/batteries_included_chiffon.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/docs/public/icons/build_quickly_chiffon.svg b/docs/public/icons/build_quickly_chiffon.svg new file mode 100644 index 000000000..d834c9c43 --- /dev/null +++ b/docs/public/icons/build_quickly_chiffon.svg @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/public/icons/license_chiffon.svg b/docs/public/icons/license_chiffon.svg new file mode 100644 index 000000000..4f4d2f362 --- /dev/null +++ b/docs/public/icons/license_chiffon.svg @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/public/icons/mvc_chiffon.svg b/docs/public/icons/mvc_chiffon.svg new file mode 100644 index 000000000..78b621f04 --- /dev/null +++ b/docs/public/icons/mvc_chiffon.svg @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/public/icons/no_config_chiffon.svg b/docs/public/icons/no_config_chiffon.svg new file mode 100644 index 000000000..80b5c29ab --- /dev/null +++ b/docs/public/icons/no_config_chiffon.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/public/icons/secure_chiffon.svg b/docs/public/icons/secure_chiffon.svg new file mode 100644 index 000000000..b85f60407 --- /dev/null +++ b/docs/public/icons/secure_chiffon.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/docs/public/logo.svg b/docs/public/logo.svg new file mode 100644 index 000000000..829c8e98d --- /dev/null +++ b/docs/public/logo.svg @@ -0,0 +1,27 @@ + + + + diff --git a/docs/_static/mail-panel.mp4 b/docs/public/mail-panel.mp4 similarity index 100% rename from docs/_static/mail-panel.mp4 rename to docs/public/mail-panel.mp4 diff --git a/docs/_static/mail-previewer.mp4 b/docs/public/mail-previewer.mp4 similarity index 100% rename from docs/_static/mail-previewer.mp4 rename to docs/public/mail-previewer.mp4