Skip to content

Commit 4a3f341

Browse files
committed
feat(music): add timebox functionality to search method
- Introduced Timebox dependency to manage execution time. - Updated the search method to utilize Timebox for limiting execution duration. - Ensured that the method still processes sources and sorts results as before.
1 parent ddc6586 commit 4a3f341

File tree

1 file changed

+31
-21
lines changed

1 file changed

+31
-21
lines changed

app/Music.php

Lines changed: 31 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
use GuzzleHttp\Exception\GuzzleException;
1919
use Illuminate\Contracts\Concurrency\Driver;
2020
use Illuminate\Support\Collection;
21+
use Illuminate\Support\Timebox;
2122
use Illuminate\Support\Traits\Conditionable;
2223
use Illuminate\Support\Traits\Dumpable;
2324
use Illuminate\Support\Traits\Localizable;
@@ -35,35 +36,44 @@ class Music implements Contracts\HttpClientFactory, Contracts\Music
3536
use Tappable;
3637
use Localizable;
3738

38-
public function __construct(private Meting $meting, private Driver $driver)
39-
{
39+
public function __construct(
40+
private Meting $meting,
41+
private Driver $driver,
42+
private ?Timebox $timebox = null,
43+
) {
4044
$this->meting = $meting->format();
45+
$this->timebox = $timebox ?: new Timebox;
4146
}
4247

4348
/**
4449
* @psalm-suppress NamedArgumentNotAllowed
50+
*
51+
* @throws \Throwable
4552
*/
4653
public function search(string $keyword, array $sources = []): Collection
4754
{
48-
return collect($sources)
49-
->map(fn (string $source): array => json_decode(
50-
(string) $this->meting->site($source)->search($keyword),
51-
true,
52-
512,
53-
\JSON_THROW_ON_ERROR
54-
))
55-
->collapse()
56-
->pipe(fn (Collection $songs): Collection => $this->ensureWithUrls($songs))
57-
->sortBy([
58-
['name', 'asc'],
59-
['artist', 'asc'],
60-
['size', 'desc'],
61-
['br', 'desc'],
62-
['album', 'asc'],
63-
['source', 'asc'],
64-
])
65-
->values()
66-
->mapWithKeys(static fn (array $song, int $index): array => [$index + 1 => $song]);
55+
return $this->timebox->call(
56+
fn (): Collection => collect($sources)
57+
->map(fn (string $source): array => json_decode(
58+
(string) $this->meting->site($source)->search($keyword),
59+
true,
60+
512,
61+
\JSON_THROW_ON_ERROR
62+
))
63+
->collapse()
64+
->pipe(fn (Collection $songs): Collection => $this->ensureWithUrls($songs))
65+
->sortBy([
66+
['name', 'asc'],
67+
['artist', 'asc'],
68+
['size', 'desc'],
69+
['br', 'desc'],
70+
['album', 'asc'],
71+
['source', 'asc'],
72+
])
73+
->values()
74+
->mapWithKeys(static fn (array $song, int $index): array => [$index + 1 => $song]),
75+
6180 * 1000
76+
);
6777
}
6878

6979
/**

0 commit comments

Comments
 (0)