Skip to content

Commit 68e6846

Browse files
committed
Jobs: add helper service to wait for a job to finish
1 parent 10295aa commit 68e6846

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -557,6 +557,14 @@ $job = $client->jobs()->show($jobId);
557557
```
558558
Returns the job.
559559

560+
##### Wait for a job to finish
561+
```php
562+
$numberOfMinutesToWait = 3;
563+
$jobHelper = new \PrivatePackagist\ApiClient\JobHelper($client);
564+
$job = $jobHelper->waitForJob($jobId, $numberOfMinutesToWait);
565+
```
566+
Returns the job.
567+
560568
#### Magento legacy keys
561569

562570
##### List all legacy keys for a customer
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
3+
namespace PrivatePackagist\ApiClient\Exception;
4+
5+
class JobErrorException extends RuntimeException
6+
{
7+
/** @var array */
8+
private $job;
9+
10+
public function __construct(array $job)
11+
{
12+
$this->job = $job;
13+
14+
parent::__construct($job['message']);
15+
}
16+
17+
/**
18+
* @return array
19+
*/
20+
public function getJob()
21+
{
22+
return $this->job;
23+
}
24+
}

src/JobHelper.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
namespace PrivatePackagist\ApiClient;
4+
5+
use PrivatePackagist\ApiClient\Exception\JobErrorException;
6+
7+
class JobHelper
8+
{
9+
/** @var Client */
10+
private $packagistClient;
11+
12+
public function __construct(Client $packagistClient)
13+
{
14+
$this->packagistClient = $packagistClient;
15+
}
16+
17+
public function waitForJob($jobId, $maxWaitMinutes = 3)
18+
{
19+
$maxWaitTime = new \DateTimeImmutable(sprintf('+%s minutes', $maxWaitMinutes));
20+
while ($maxWaitTime> new \DateTimeImmutable()) {
21+
$job = $this->packagistClient->jobs()->show($jobId);
22+
23+
if ($job['status'] === 'success') {
24+
return $job;
25+
}
26+
27+
if ($job['status'] === 'error') {
28+
throw new JobErrorException($job);
29+
}
30+
31+
sleep(1);
32+
}
33+
34+
throw new \Exception(sprintf('Job has not finish after %s minutes', $maxWaitMinutes));
35+
}
36+
}

0 commit comments

Comments
 (0)