Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions inline-documentation-standards/php.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@ HTML markup should never be used outside of code examples, though Markdown can b
* The description continues on ...
```

To let readers run a code sample on the Code Reference, write it as a [runnable code example](https://developer.wordpress.org/coding-standards/inline-documentation-standards/runnable-code-examples/) instead.

3. Links in the form of URLs, such as related Trac tickets or other documentation, should be added in the appropriate place in the DocBlock using the `@link` tag:

```php
Expand Down Expand Up @@ -187,6 +189,7 @@ Functions and class methods should be formatted as follows:

- **Summary**: A brief, one sentence explanation of the purpose of the function spanning a maximum of two lines. Use a period at the end.
- **Description**: A supplement to the summary, providing a more detailed description. Use a period at the end of sentences.
- **Runnable code example**: Optional. A code sample in the description that readers can run on the Code Reference. See [Runnable Code Examples](https://developer.wordpress.org/coding-standards/inline-documentation-standards/runnable-code-examples/).
- **`@ignore`**: Used when an element is meant only for internal use and should be skipped from parsing.
- **`@since x.x.x`**: Should always be 3-digit (e.g. `@since 3.9.0`). Exception is `@since MU (3.0.0)`.
- **`@access`**: Only used for core-only functions or classes implementing "private" core APIs. If the element is private it will be output with a message stating its intention for internal use.
Expand Down
205 changes: 205 additions & 0 deletions inline-documentation-standards/runnable-code-examples.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
# Runnable Code Examples

A code example in a PHP DocBlock can be made runnable by marking it `interactive`. On the [Code Reference](https://developer.wordpress.org/reference/), readers can edit a runnable example and run it with a **Run** button. [WordPress Playground](https://developer.wordpress.org/playground/handbook/guides/php-code-snippets/) runs the code in the browser.

Runnable examples are optional. Ordinary code samples, indented by four spaces as described in the [PHP Documentation Standards](https://developer.wordpress.org/coding-standards/inline-documentation-standards/php/#description), keep working. Convert a code sample only when running it teaches something that reading it cannot.

## Example

````php
/**
* Sanitizes a string into a slug, which can be used in URLs or HTML attributes.
*
* ```php interactive
* echo sanitize_title( 'Hello World!' );
* // Outputs: hello-world
* ```
*
* @since 1.0.0
*/
function sanitize_title() { /* …snip… */ }
````

A runnable example has three parts:

1. A fence with the info string `php interactive`.
2. PHP code that prints something.
3. An output comment, starting with `// Outputs`, that states what the code prints. It is recommended but optional.

## The fence

A fence is a Markdown code block that starts and ends with a line of three backticks. The text after the opening backticks is the fence's [info string](https://spec.commonmark.org/0.31.2/#info-string). Markdown uses its first word as the language. The second word, `interactive`, is a WordPress convention that the Code Reference recognizes. Markdown gives it no meaning.

- The info string must be `php interactive`, lowercase, in that order. Any other info string, such as `PHP interactive`, `php-interactive`, or `php interactive title="x"`, displays as ordinary code that readers cannot run.
- The only other word allowed is a reference to a shared setup Blueprint, described under [Setup Blueprints](#setup-blueprints).
- The fence may be indented, for example inside a Markdown list item. Code lines may be indented less than the fence.
- The runnable example appears where the fence is, between the surrounding paragraphs.

## The code

Start with the first line the example needs. Do **not** include:

- `<?php`. The Code Reference adds it. An example that starts with a PHP opening tag does not run.
- `require '/wordpress/wp-load.php';`. WordPress is already loaded.

Print the result with `echo`, `print_r()`, `var_export()`, or `var_dump()`. Keep the example short enough to read comfortably in the DocBlock. A runnable example is a reference example, not a tutorial.

## The output comment

An output comment states what the example prints. It is one or more PHP line comments at the end of the example, starting with `// Outputs`. The Code Reference shows the stated output before the reader selects **Run**, so readers see the result without running the code. After a run, the real output replaces it. The output comment is not part of the code that runs.

An output comment is recommended but optional. Update it whenever the example's output changes.

The output can be a single line or multiline.

### Single-line output

Write `// Outputs:`, one space, and the output on one line. Everything after that space is the output, exactly as written.

````php
/**
* …snip…
* ```php interactive
* echo esc_html( 'Fish & Chips' );
* // Outputs: Fish &amp; Chips
* ```
*/
````

### Multiline output

Write `// Outputs:` alone on a line, then one `//` line for each line of output. The first space after each `//` is removed. Any further spaces are part of the output. When the output ends with a newline, end the comment with an empty `//` line.

````php
/**
* …snip…
* ```php interactive
* print_r( array( 'fruit' => 'apple' ) );
* // Outputs:
* // Array
* // (
* // [fruit] => apple
* // )
* //
* ```
*/
````

### JSON-encoded output

When the output contains tabs, trailing spaces, or several trailing newlines, write it as one JSON string after `// Outputs (JSON-encoded):`.

````php
/**
* …snip…
* ```php interactive
* echo implode( "\t", array( 'ID', 'Title' ) );
* // Outputs (JSON-encoded): "ID\tTitle"
* ```
*/
````

### Placement

The output comment must be the last lines of the example, each comment on its own line. Otherwise the Code Reference treats it as code, and shows no output until the reader runs the example.

Incorrect, because the output comment shares a line with code:

````php
/**
* …snip…
* ```php interactive
* echo sanitize_title( 'Hello World!' ); // Outputs: hello-world
* ```
*/
````

Incorrect, because code follows the output comment:

````php
/**
* …snip…
* ```php interactive
* echo sanitize_title( 'Hello World!' );
* // Outputs: hello-world
* echo sanitize_title( 'Goodbye, World!' );
* ```
*/
````

Correct:

````php
/**
* …snip…
* ```php interactive
* echo sanitize_title( 'Hello World!' ), "\n";
* echo sanitize_title( 'Goodbye, World!' );
* // Outputs:
* // hello-world
* // goodbye-world
* ```
*/
````

## Setup Blueprints

Some examples need content or settings that a new WordPress site does not have, such as a user's first name. Code that creates them would distract from the function the example documents. Put that setup in a setup Blueprint instead: a [Playground Blueprint](https://developer.wordpress.org/playground/blueprints/) in a fence with the info string `setup-blueprint`. The Blueprint runs before the example, and the Code Reference does not show it.

Place the setup Blueprint directly before or after the example's fence, with nothing but blank lines between them. Each example can have one setup Blueprint.

````php
/**
* …snip…
* ```setup-blueprint
* { "steps": [ { "step": "updateUserMeta", "userId": 1, "meta": { "first_name": "Ada" } } ] }
* ```
* ```php interactive
* echo get_user_meta( 1, 'first_name', true );
* // Outputs: Ada
* ```
*/
````

### Shared setup Blueprints

To use one setup Blueprint in several examples, name it: add the name after `setup-blueprint` in its info string. Then add `setup-blueprint=` and the name after `php interactive` in each example that uses it. A name contains only lowercase letters, digits, and hyphens, and starts with a letter.

A named setup Blueprint can be used in the DocBlock that defines it. One defined in a file header DocBlock can also be used in every DocBlock in the file. One defined in a class DocBlock can also be used in the DocBlocks of the class's methods and properties. Do not define a name that the file header or class DocBlock already defines.

````php
/**
* …snip…
* ```setup-blueprint user-ada
* { "steps": [ { "step": "updateUserMeta", "userId": 1, "meta": { "first_name": "Ada", "last_name": "Lovelace" } } ] }
* ```
*/
class Example {
/**
* …snip…
* ```php interactive setup-blueprint=user-ada
* echo get_user_meta( 1, 'last_name', true );
* // Outputs: Lovelace
* ```
*/
public function example() { /* …snip… */ }
}
````

## Checklist

Before committing a runnable example, check that:

- The fence's info string is `php interactive`, followed by `setup-blueprint=<name>` only when the example uses a shared setup Blueprint.
- The code does not include `<?php` or `require '/wordpress/wp-load.php';`.
- The code prints something, and the output comment, if present, matches what it prints.
- The DocBlock still reads clearly as plain text in the source. If it does not, use an ordinary indented code sample.

The Code Reference parser stops with an error when a DocBlock contains:

- A setup Blueprint that is not a valid JSON object.
- A setup Blueprint not placed next to an example, or two setup Blueprints for one example.
- An invalid or undefined setup Blueprint name, or a name defined twice.
- A JSON-encoded output comment that is not one JSON string.

To try an example before committing, run it in a `<php-snippet>` element as described in the [Playground guide](https://developer.wordpress.org/playground/handbook/guides/php-code-snippets/). Add `<?php` and `require '/wordpress/wp-load.php';` at the top first, because the Code Reference adds them for you.
6 changes: 6 additions & 0 deletions manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@
"parent": "inline-documentation-standards",
"markdown_source": "https://github.com/WordPress/wpcs-docs/blob/master/inline-documentation-standards/php.md"
},
"inline-documentation-standards/runnable-code-examples": {
"title": "Runnable Code Examples",
"slug": "runnable-code-examples",
"parent": "inline-documentation-standards",
"markdown_source": "https://github.com/WordPress/wpcs-docs/blob/master/inline-documentation-standards/runnable-code-examples.md"
},
"changelog": {
"title": "Changelog",
"slug": "changelog",
Expand Down
Loading