-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathDownloadCollector.php
More file actions
84 lines (73 loc) · 2.14 KB
/
DownloadCollector.php
File metadata and controls
84 lines (73 loc) · 2.14 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
<?php
declare(strict_types=1);
namespace Pest\Browser\Api;
use Pest\Browser\Exceptions\BrowserExpectationFailedException;
use Pest\Browser\Execution;
use Pest\Browser\Playwright\Client;
use Pest\Browser\Playwright\Page;
use PHPUnit\Framework\ExpectationFailedException;
/**
* @internal
*/
final class DownloadCollector
{
/**
* The collected downloads.
*
* @var array<int, Download>
*/
private array $downloads = [];
public function __construct(
private readonly Page $page,
private readonly string $pageGuid,
) {
Client::instance()->startCollectingDownloads($this->pageGuid, $this);
}
/**
* Adds a download to the collection.
*
* @internal This method is called by the Client when a download event is received.
*/
public function add(string $url, string $suggestedFilename, string $artifactGuid): void
{
$download = new Download($this->page);
$download->resolve($url, $suggestedFilename, $artifactGuid);
$this->downloads[] = $download;
}
/**
* Returns the collected downloads, optionally waiting for an expected count.
*
* @return array<int, Download>
*/
public function all(?int $count = null): array
{
if ($count !== null) {
$this->waitForCount($count);
}
return $this->downloads;
}
/**
* Stops collecting and cleans up.
*/
public function stop(): void
{
Client::instance()->stopCollectingDownloads($this->pageGuid);
}
/**
* Waits until the expected number of downloads have been collected.
*/
private function waitForCount(int $count): void
{
Execution::instance()->waitForExpectation(function () use ($count): void {
$actual = count($this->downloads);
if ($actual !== $count) {
throw BrowserExpectationFailedException::from(
$this->page,
new ExpectationFailedException(
sprintf('Expected %d downloads, but %d received', $count, $actual)
),
);
}
});
}
}