Skip to content

Commit e706ed7

Browse files
committed
Add Quick Start Guide
1 parent dea55f7 commit e706ed7

File tree

7 files changed

+611
-0
lines changed

7 files changed

+611
-0
lines changed

docs/guide.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Playwright PHP - Quick Start Guide
2+
3+
- [Getting Started](./guide/getting-started.md)
4+
- [Core Concepts](./guide/core-concepts.md)
5+
- [Handling Authentication](./guide/handling-authentication.md)
6+
- [Testing with PHPUnit](./guide/testing-with-phpunit.md)
7+
- [Assertions Reference](./guide/assertions-reference.md)
8+
- [Advanced Recipes](./guide/advanced-recipes.md)

docs/guide/advanced-recipes.md

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
# Advanced Recipes
2+
3+
This page contains recipes for common but more advanced automation scenarios. Use these examples to leverage the full
4+
power of Playwright for PHP.
5+
6+
## File Uploads
7+
8+
You can upload one or more files to an `<input type="file">` element using the `setInputFiles()` method on a `Locator`.
9+
10+
```php
11+
// Find the file input element
12+
$fileChooser = $this->page->locator('#upload-input');
13+
14+
// Upload a single file
15+
$fileChooser->setInputFiles(__DIR__.'/fixtures/avatar.jpg');
16+
17+
// Upload multiple files
18+
$fileChooser->setInputFiles([
19+
__DIR__.'/fixtures/document1.pdf',
20+
__DIR__.'/fixtures/document2.docx',
21+
]);
22+
```
23+
24+
## Network Interception
25+
26+
Playwright allows you to intercept, inspect, and modify network requests made by the page. This is incredibly useful for
27+
testing edge cases, mocking API responses, or blocking unwanted resources.
28+
29+
You can use `$page->route()` to intercept requests that match a specific URL pattern.
30+
31+
```php
32+
// Mock an API response
33+
$this->page->route('**/api/v1/users/me', function ($route) {
34+
$route->fulfill([
35+
'status' => 200,
36+
'contentType' => 'application/json',
37+
'body' => json_encode([
38+
'id' => 123,
39+
'name' => 'Mock User',
40+
'email' => '[email protected]',
41+
]),
42+
]);
43+
});
44+
45+
// Navigate to the page that makes the API call
46+
$this->page->goto('/profile');
47+
48+
// Assert that the mocked data is displayed
49+
expect($this->page->locator('.username'))->toHaveText('Mock User');
50+
```
51+
52+
You can also use `$route->abort()` to block requests, for example, to test how your site behaves without analytics
53+
scripts or third-party fonts.
54+
55+
## Handling Dialogs
56+
57+
Your application might trigger JavaScript dialogs like `alert`, `confirm`, or `prompt`. Playwright can listen for these
58+
and handle them automatically.
59+
60+
```php
61+
// Listen for the next dialog that appears
62+
$this->page->events()->onDialog(function ($dialog) {
63+
// Assert the dialog message is correct
64+
$this->assertSame('Are you sure you want to delete this item?', $dialog->message());
65+
66+
// Accept the dialog
67+
$dialog->accept();
68+
});
69+
70+
// Perform the action that triggers the dialog
71+
$this->page->locator('#delete-item-button')->click();
72+
```
73+
74+
## Working with Frames
75+
76+
If your page uses `<iframe>` elements, you can interact with their content using `$page->frameLocator()`. This returns a
77+
`FrameLocator`, which has a `.locator()` method to find elements specifically within that frame.
78+
79+
```php
80+
// Create a locator for the iframe
81+
$frame = $this->page->frameLocator('#my-iframe');
82+
83+
// Now find elements within that frame
84+
$frameInput = $frame->locator('#name-input');
85+
$frameInput->fill('This is inside a frame');
86+
87+
$frameButton = $frame->locator('button:has-text("Submit")');
88+
$frameButton->click();
89+
```
90+
91+
## Browser Configuration with `PlaywrightConfigBuilder`
92+
93+
For advanced browser setups, such as using a proxy server or setting custom launch arguments, you can use the
94+
`PlaywrightConfigBuilder`.
95+
96+
This is typically done outside of the test case itself, when you are creating your `PlaywrightClient` instance.
97+
98+
```php
99+
use PlaywrightPHP\PlaywrightFactory;
100+
use PlaywrightPHP\Configuration\PlaywrightConfigBuilder;
101+
102+
// Create a custom configuration
103+
$config = PlaywrightConfigBuilder::create()
104+
->withHeadless(false)
105+
->withSlowMoMs(50)
106+
->addArg('--start-maximized')
107+
->withProxy('http://myproxy.com:8080')
108+
->build();
109+
110+
// Create a Playwright client with the custom config
111+
$playwright = PlaywrightFactory::create($config);
112+
113+
// Now launch the browser, which will use these settings
114+
$browser = $playwright->chromium()->launch();
115+
```

docs/guide/assertions-reference.md

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# Assertions Reference
2+
3+
Playwright for PHP includes a powerful assertion library accessible via the `expect()` function. This provides a fluent
4+
and expressive way to write checks in your tests.
5+
6+
A key feature of these assertions is **auto-waiting**. When you write an assertion, Playwright will automatically wait
7+
for a reasonable amount of time for the condition to be met. This eliminates a major source of flaky tests.
8+
9+
## Using `expect()`
10+
11+
The `expect()` function can be passed either a `Locator` or a `Page` object. It returns an assertion object that you can
12+
use to make claims about the state of your application.
13+
14+
```php
15+
use function PlaywrightPHP\Testing\expect;
16+
17+
// Make an assertion about a locator
18+
expect($this->page->locator('h1'))->toHaveText('Welcome!');
19+
20+
// Make an assertion about the page
21+
expect($this->page)->toHaveURL('https://my-app.com/dashboard');
22+
```
23+
24+
-----
25+
26+
## Modifiers
27+
28+
You can alter the behavior of any assertion using these chainable modifier methods.
29+
30+
### `.not()`
31+
32+
The `.not()` modifier negates any assertion that follows it.
33+
34+
```php
35+
// Assert that an element is not visible
36+
expect($this->page->locator('.loading-spinner'))->not()->toBeVisible();
37+
38+
// Assert that a checkbox is not checked
39+
expect($this->page->locator('#terms-and-conditions'))->not()->toBeChecked();
40+
```
41+
42+
### `.withTimeout()`
43+
44+
By default, assertions have a timeout of 5 seconds. You can override this for a specific assertion using
45+
`withTimeout()`.
46+
47+
```php
48+
// Wait up to 10 seconds for the success message to appear
49+
expect($this->page->locator('.success-message'))
50+
->withTimeout(10000)
51+
->toBeVisible();
52+
```
53+
54+
-----
55+
56+
## Locator Assertions
57+
58+
These assertions are available when you pass a `Locator` to `expect()`.
59+
60+
* **`toBeVisible()`**: Asserts the locator resolves to a visible element.
61+
* **`toBeHidden()`**: Asserts the locator resolves to a hidden element.
62+
* **`toBeEnabled()`**: Asserts the element is enabled.
63+
* **`toBeDisabled()`**: Asserts the element is disabled.
64+
* **`toBeChecked()`**: Asserts a checkbox or radio button is checked.
65+
* **`toBeFocused()`**: Asserts the element is focused.
66+
* **`toHaveText(string $text)`**: Asserts the element contains the given text.
67+
* **`toHaveExactText(string $text)`**: Asserts the element's text is an exact match.
68+
* **`toContainText(string $text)`**: An alias for `toHaveText()`.
69+
* **`toHaveValue(string $value)`**: Asserts an input element has a specific value.
70+
* **`toHaveAttribute(string $name, string $value)`**: Asserts the element has the given attribute and value.
71+
* **`toHaveCSS(string $name, string $value)`**: Asserts the element has the given computed CSS style.
72+
* **`toHaveCount(int $count)`**: Asserts the locator resolves to a specific number of elements.
73+
74+
-----
75+
76+
## Page Assertions
77+
78+
These assertions are available when you pass a `Page` object to `expect()`.
79+
80+
* **`toHaveURL(string $url)`**: Asserts the page's current URL is a match.
81+
* **`toHaveTitle(string $title)`**: Asserts the page's title is a match.

docs/guide/core-concepts.md

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# Core Concepts
2+
3+
Playwright's power and reliability come from its well-defined architecture. Understanding these core concepts is key to
4+
using the library effectively and writing robust browser automation scripts. The API is structured around four main
5+
objects: `Browser`, `BrowserContext`, `Page`, and `Locator`.
6+
7+
## Browser
8+
9+
A `Browser` instance represents a single browser process (e.g., Chromium, Firefox, or WebKit). You typically launch a
10+
browser once at the beginning of your script or test suite and close it at the end.
11+
12+
While you can interact with the `Browser` object directly, most of your work will be done within a `BrowserContext`.
13+
14+
```php
15+
<?php
16+
use PlaywrightPHP\Playwright;
17+
18+
// The Playwright static class is the easiest way to get started.
19+
// This launches a Chromium browser and returns a default BrowserContext.
20+
$context = Playwright::chromium(['headless' => false]);
21+
22+
// ... do stuff ...
23+
24+
// Closing the context will also close the associated browser.
25+
$context->close();
26+
```
27+
28+
## BrowserContext
29+
30+
A `BrowserContext` is an isolated, "incognito-like" session within a browser instance. Each context has its own cookies,
31+
local storage, and cache, and they do not share these with other contexts. This makes them perfect for running
32+
independent tests in parallel.
33+
34+
You can create multiple contexts from a single `Browser` instance.
35+
36+
```php
37+
// The Browser object is available on the context.
38+
$browser = $context->browser();
39+
40+
// Create a second, isolated context.
41+
$adminContext = $browser->newContext();
42+
43+
// Create a new page in each context.
44+
$userPage = $context->newPage();
45+
$adminPage = $adminContext->newPage();
46+
```
47+
48+
Contexts are also where you configure session-specific behavior, such as:
49+
50+
* Setting a custom viewport size.
51+
* Emulating mobile devices.
52+
* Granting permissions.
53+
* Loading a saved authentication state.
54+
55+
## Page
56+
57+
A `Page` represents a single tab within a `BrowserContext`. It is the primary object you will use to interact with a web
58+
page's content. Most of the essential actions, like navigating, clicking, and typing, are methods on the `Page` object.
59+
60+
```php
61+
// Navigate the page to a URL.
62+
$page->goto('https://github.com');
63+
64+
// Interact with elements on the page.
65+
$page->click('a.HeaderMenu-link--sign-in');
66+
$page->type('#login_field', 'my-username');
67+
```
68+
69+
A `BrowserContext` can have multiple `Page` objects (tabs).
70+
71+
## Locator
72+
73+
The `Locator` is the heart of Playwright's modern approach to browser automation. It is the recommended way to find and
74+
interact with elements on a `Page`.
75+
76+
A `Locator` is a "recipe" for finding an element on the page. Unlike traditional methods that find an element
77+
immediately, a `Locator` has **auto-waiting** built-in. When you perform an action on a locator, Playwright
78+
automatically waits for the element to exist and be in an "actionable" state (e.g., visible, enabled, not obscured)
79+
before performing the action. This eliminates a major source of flakiness in browser tests.
80+
81+
```php
82+
// Create a locator for the search input field.
83+
$searchInput = $page->locator('#search-input');
84+
85+
// Playwright will automatically wait for the element to be ready
86+
// before filling it with text.
87+
$searchInput->fill('Playwright for PHP');
88+
89+
// You can chain locators to find elements within other elements.
90+
$header = $page->locator('header');
91+
$signInButton = $header->locator('a:has-text("Sign In")');
92+
$signInButton->click();
93+
```
94+
95+
By understanding and using these four core concepts, you can build powerful, reliable, and maintainable browser
96+
automation scripts and tests.

docs/guide/getting-started.md

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
# Getting Started with Playwright for PHP
2+
3+
Welcome to Playwright for PHP\! This guide will walk you through setting up your first project and running a basic
4+
browser automation script. Our goal is to get you up and running in just a few minutes.
5+
6+
## Requirements
7+
8+
Before you begin, please ensure your development environment meets the following requirements:
9+
10+
* **PHP 8.3+**
11+
* **Node.js 20+** (This is used by the underlying Playwright server)
12+
* **Composer** for managing PHP dependencies.
13+
14+
## Installation
15+
16+
Getting started with Playwright for PHP is a two-step process. First, you add the library to your project using
17+
Composer. Second, you run a command to download the necessary browser binaries.
18+
19+
### Step 1: Install the Library
20+
21+
Navigate to your project's root directory and run the following Composer command:
22+
23+
```bash
24+
composer require playwright-php/playwright
25+
```
26+
27+
### Step 2: Install Browsers
28+
29+
Playwright needs to download browser binaries (for Chromium, Firefox, and WebKit) to work. The library provides a
30+
convenient script to handle this for you. Run the following command from your project's root:
31+
32+
```bash
33+
composer run install-browsers
34+
```
35+
36+
This will install the Node.js dependencies for the server and download the latest browser versions into a local cache.
37+
38+
## Your First Script
39+
40+
You're now ready to write your first script. Create a new file named `example.php` and add the following code:
41+
42+
```php
43+
<?php
44+
45+
require __DIR__.'/vendor/autoload.php';
46+
47+
use PlaywrightPHP\Playwright;
48+
49+
// Start a new Playwright client and launch a browser.
50+
// By default, it launches a headless Chromium instance.
51+
$context = Playwright::chromium();
52+
53+
// Create a new page within the browser context.
54+
$page = $context->newPage();
55+
56+
// Navigate to a website.
57+
$page->goto('https://example.com');
58+
59+
// Get the title of the page and print it to the console.
60+
echo $page->title() . PHP_EOL; // Outputs: "Example Domain"
61+
62+
// Take a screenshot and save it as 'screenshot.png'.
63+
$page->screenshot('screenshot.png');
64+
65+
// Close the browser context and all its pages.
66+
$context->close();
67+
```
68+
69+
To run the script, execute it from your terminal:
70+
71+
```bash
72+
php example.php
73+
```
74+
75+
You should see "Example Domain" printed to your console, and a `screenshot.png` file will be created in the same
76+
directory.
77+
78+
Congratulations, you've successfully run your first Playwright for PHP script\!
79+
80+
## What's Next?
81+
82+
Now that you have the library installed and running, you can explore its core concepts to understand how to build more
83+
complex and reliable automations.
84+
85+
* **[Core Concepts](./core-concepts.md)**: Learn about the fundamental building blocks
86+
of Playwright like Browsers, Contexts, Pages, and Locators.
87+
* **[Testing with PHPUnit](./testing-with-phpunit.md)**: See how to integrate Playwright
88+
into your PHPUnit test suite for seamless end-to-end testing.

0 commit comments

Comments
 (0)