Skip to content

Commit

Permalink
dev: Refactor the NewsPicker API
Browse files Browse the repository at this point in the history
  • Loading branch information
marienfressinaud committed Oct 2, 2024
1 parent 6870e57 commit 418cdff
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 29 deletions.
13 changes: 4 additions & 9 deletions src/controllers/News.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,8 @@ public function create(Request $request): Response
]);
}

$news_picker = new services\NewsPicker($user, [
'number_links' => 50,
]);
$links = $news_picker->pick();
$news_picker = new services\NewsPicker($user);
$links = $news_picker->pick(max: 50);

$news = $user->news();

Expand Down Expand Up @@ -125,11 +123,8 @@ public function showAvailable(Request $request): Response
]);
}

$news_picker = new services\NewsPicker($user, [
'number_links' => 1,
'from' => 'followed',
]);
$links = $news_picker->pick();
$news_picker = new services\NewsPicker($user);
$links = $news_picker->pick(max: 1);

return Response::json(200, [
'available' => count($links) > 0,
Expand Down
23 changes: 3 additions & 20 deletions src/services/NewsPicker.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,41 +8,24 @@
* The NewsPicker service is a sort of basic artificial intelligence. Its
* purpose is to select a bunch of links relevant for a given user.
*
* @phpstan-type Options array{
* 'number_links': int,
* }
*
* @author Marien Fressinaud <dev@marienfressinaud.fr>
* @license http://www.gnu.org/licenses/agpl-3.0.en.html AGPL
*/
class NewsPicker
{
private const DEFAULT_OPTIONS = [
'number_links' => 9,
];

private models\User $user;

/** @var Options */
private array $options;

/**
* @param array{
* 'number_links'?: int,
* } $options
*/
public function __construct(models\User $user, array $options = [])
public function __construct(models\User $user)
{
$this->user = $user;
$this->options = array_merge(self::DEFAULT_OPTIONS, $options);
}

/**
* Pick and return a set of links relevant for news.
*
* @return models\Link[]
*/
public function pick(): array
public function pick(int $max = 25): array
{
$excluded_hashes = models\Link::listHashesExcludedFromNews($this->user->id);
$links_from_followed = models\Link::listFromFollowedCollections($this->user->id);
Expand All @@ -58,7 +41,7 @@ public function pick(): array

$links[$hash] = $link;

if (count($links) >= $this->options['number_links']) {
if (count($links) >= $max) {
break;
}
}
Expand Down

0 comments on commit 418cdff

Please sign in to comment.