PHP code example of playwright-php / performance

1. Go to this page and download the library: Download playwright-php/performance library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

playwright-php / performance example snippets




laywright\Performance\Monitor\PerformanceMonitor;
use Playwright\Performance\Reporter\JsonReporter;
use Playwright\Playwright;

$context = Playwright::chromium();
$page = $context->newPage();
$monitor = new PerformanceMonitor($page);

$monitor->navigate('https://example.com');

$vitals = $monitor->collectCoreWebVitals();
$resources = $monitor->collectResourceMetrics();
$report = (new JsonReporter())->generate($vitals, $resources);

file_put_contents('performance.json', $report);

$context->close();

use Playwright\Performance\Monitor\PerformanceMonitor;
use Playwright\Performance\Test\PerformanceAssertions;
use Playwright\Testing\PlaywrightTestCase;

final class HomepagePerformanceTest extends PlaywrightTestCase
{
    use PerformanceAssertions;

    public function testHomepageBudgets(): void
    {
        $monitor = new PerformanceMonitor($this->page);
        $monitor->navigate('https://example.com');

        $vitals = $monitor->collectCoreWebVitals();
        $resources = $monitor->collectResourceMetrics();

        $this->assertLcpBelowThreshold($vitals, 2500);
        $this->assertClsBelowThreshold($vitals, 0.1);
        $this->assertResourceCountBelowThreshold($resources, 50);
    }
}

use Playwright\Performance\Reporter\MarkdownReporter;

$markdown = (new MarkdownReporter())->generate($vitals, $resources);
file_put_contents('performance.md', $markdown);

use Playwright\Performance\Metrics\CoreWebVitals;
use Playwright\Performance\Monitor\MockPerformanceMonitor;

$monitor = new MockPerformanceMonitor();
$monitor->setCoreWebVitals(new CoreWebVitals(
    lcp: 1000.0,
    fcp: 500.0,
    cls: 0.05,
    inp: 0.0,
    fid: 0.0,
    ttfb: 100.0,
    tbt: 0.0,
));
bash
composer laywright-install --browsers