-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathScreenshot.php
More file actions
86 lines (69 loc) · 2.63 KB
/
Screenshot.php
File metadata and controls
86 lines (69 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
declare(strict_types=1);
/*
* This file is part of the community-maintained Playwright PHP project.
* It is not affiliated with or endorsed by Microsoft.
*
* (c) 2025-Present - Playwright PHP - https://github.com/playwright-php
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Playwright\Media\Screenshot;
use Playwright\Media\Filesystem\FilesystemInterface;
use Playwright\Page\Options\ScreenshotOptions;
use Playwright\Transport\TransportInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
final readonly class Screenshot
{
public function __construct(
private TransportInterface $transport,
private FilesystemInterface $filesystem,
private LoggerInterface $logger = new NullLogger(),
) {
}
/**
* @param array<string, mixed>|ScreenshotOptions $options
*/
public function take(string $pageId, ?string $path, string $url, array|ScreenshotOptions $options = []): string
{
$options = ScreenshotOptions::from($options)->toArray();
/** @var string $finalPath */
$finalPath = $path ?? $options['path'] ?? $this->generateFilename($url);
// Prevent saving the file by Playwright
if (isset($options['path'])) {
unset($options['path']);
}
$this->logger->debug('Taking screenshot', ['path' => $finalPath, 'options' => $options]);
try {
/** @var array{binary: ?string} $response */
$response = $this->transport->send(
[
'options' => $options,
'action' => 'page.screenshot',
'pageId' => $pageId,
],
);
$finalPath = $this->filesystem->write($finalPath, base64_decode($response['binary'] ?? ''));
} catch (\Throwable $e) {
$this->logger->error('Failed to take screenshot', [
'path' => $finalPath,
'error' => $e->getMessage(),
'exception' => $e,
]);
throw $e;
}
$this->logger->info('Screenshot saved successfully', ['path' => $finalPath]);
return $finalPath;
}
private function generateFilename(string $url): string
{
$now = microtime(true);
$datetime = date('Ymd_His', (int) $now);
$milliseconds = sprintf('%03d', ($now - floor($now)) * 1000);
$urlSlug = ScreenshotHelper::slugifyUrl($url);
$safeExtension = ltrim('png', '.');
return sprintf('%s_%s_%s.%s', $datetime, $milliseconds, $urlSlug, $safeExtension ?: 'png');
}
}