-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathScreenshotHelper.php
More file actions
194 lines (161 loc) · 5.65 KB
/
ScreenshotHelper.php
File metadata and controls
194 lines (161 loc) · 5.65 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
<?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\Exception\RuntimeException;
/**
* Utility for generating screenshot filenames and managing screenshot directories.
*
* @author Simon André <smn.andre@gmail.com>
*/
final class ScreenshotHelper
{
/**
* Generate an auto screenshot filename based on current datetime and URL.
*
* Format: YYYYMMDD_HHMMSS_mmm_url-slug.<extension>
* Example: 20240811_143052_123_github-com-smnandre.png
*/
public static function generateFilename(string $url, string $directory, string $extension = 'png'): string
{
$now = microtime(true);
$datetime = date('Ymd_His', (int) $now);
$milliseconds = sprintf('%03d', ($now - floor($now)) * 1000);
$urlSlug = self::slugifyUrl($url, 40);
$safeExtension = ltrim($extension, '.');
$filename = sprintf('%s_%s_%s.%s', $datetime, $milliseconds, $urlSlug, $safeExtension ?: 'png');
return $directory.DIRECTORY_SEPARATOR.$filename;
}
/**
* Slugify a URL for use in filenames.
*
* @param string $url The URL to slugify
* @param int $maxLength Maximum length of the slug
*
* @return string The slugified URL
*/
public static function slugifyUrl(string $url, int $maxLength = 40): string
{
$slug = preg_replace('#^(https?://)?(www\.)?#i', '', $url);
if (null === $slug) {
$slug = 'invalid-url';
}
$slug = preg_replace('/[^a-zA-Z0-9]+/', '-', $slug);
if (null === $slug) {
$slug = 'invalid-url';
} else {
$slug = trim($slug, '-');
$slug = strtolower($slug);
}
$slug = substr($slug, 0, $maxLength);
$slug = rtrim($slug, '-');
return $slug ?: 'screenshot';
}
/**
* Ensure a directory exists, creating it if necessary.
*
* @param string $directory The directory path
*
* @throws \RuntimeException If directory cannot be created
*/
public static function ensureDirectoryExists(string $directory): void
{
if (is_dir($directory)) {
return;
}
if (!mkdir($directory, 0755, true) && !is_dir($directory)) {
throw new RuntimeException(sprintf('Failed to create screenshot directory: %s', $directory));
}
}
/**
* Clean up old screenshots in a directory.
*
* @param string $directory The directory to clean
* @param int $maxAge Maximum age in seconds (default: 7 days)
* @param int $maxFiles Maximum number of files to keep (default: 100)
*/
public static function cleanupOldScreenshots(string $directory, int $maxAge = 604800, int $maxFiles = 100): int
{
if (!is_dir($directory)) {
return 0;
}
$files = [];
$currentTime = time();
$cleanedCount = 0;
foreach (new \DirectoryIterator($directory) as $fileInfo) {
if ($fileInfo->isDot() || 'png' !== $fileInfo->getExtension()) {
continue;
}
$filePath = $fileInfo->getPathname();
$modTime = $fileInfo->getMTime();
if (($currentTime - $modTime) > $maxAge) {
if (unlink($filePath)) {
++$cleanedCount;
}
continue;
}
$files[] = [
'path' => $filePath,
'mtime' => $modTime,
];
}
if (count($files) > $maxFiles) {
usort($files, fn ($a, $b) => $a['mtime'] <=> $b['mtime']);
$filesToDelete = array_slice($files, 0, count($files) - $maxFiles);
foreach ($filesToDelete as $file) {
if (unlink($file['path'])) {
++$cleanedCount;
}
}
}
return $cleanedCount;
}
/**
* Get information about screenshots in a directory.
*
* @param string $directory The directory to analyze
*
* @return array{count: int, totalSize: int, oldestFile: string|null, newestFile: string|null}
*/
public static function getDirectoryInfo(string $directory): array
{
$info = [
'count' => 0,
'totalSize' => 0,
'oldestFile' => null,
'newestFile' => null,
'oldestTime' => null,
'newestTime' => null,
];
if (!is_dir($directory)) {
unset($info['oldestTime'], $info['newestTime']);
return $info;
}
foreach (new \DirectoryIterator($directory) as $fileInfo) {
if ($fileInfo->isDot() || 'png' !== $fileInfo->getExtension()) {
continue;
}
++$info['count'];
$info['totalSize'] += $fileInfo->getSize();
$mtime = $fileInfo->getMTime();
if (null === $info['oldestTime'] || $mtime < $info['oldestTime']) {
$info['oldestTime'] = $mtime;
$info['oldestFile'] = $fileInfo->getFilename();
}
if (null === $info['newestTime'] || $mtime > $info['newestTime']) {
$info['newestTime'] = $mtime;
$info['newestFile'] = $fileInfo->getFilename();
}
}
unset($info['oldestTime'], $info['newestTime']);
return $info;
}
}