fn_b/app/Services/ArticleLikeDefaults.php

62 lines
2.3 KiB
PHP

<?php
namespace App\Services;
use InvalidArgumentException;
final class ArticleLikeDefaults
{
public function editorialCategory(string $slug): string
{
if ($slug === 'advanced') {
return 'comprehensive';
}
return in_array($slug, ['client', 'windows', 'andorid', 'ios', 'linux', 'mac'], true)
? 'beginner' : 'editorial_other';
}
/** @return array{seven_day:int, yearly:int, one_year:int} */
public function resolve(string $type, array $overrides = []): array
{
$limits = ['seven_day' => 1000000, 'yearly' => 365, 'one_year' => 1000000];
$settings = config('article_likes.'.$type);
if (! is_array($settings)) {
throw new InvalidArgumentException('Missing article like defaults: '.$type);
}
$result = [];
foreach ($limits as $key => $max) {
// Site settings are authoritative, including zero. Incoming values
// remain accepted for API compatibility but cannot change the policy.
$value = $settings[$key] ?? null;
if (is_array($value)) {
if (count($value) !== 2 || ! array_is_list($value) || ! is_int($value[0]) || ! is_int($value[1])
|| $value[0] < 0 || $value[1] > $max || $value[0] > $value[1]) {
throw new InvalidArgumentException('Invalid article like range: '.$type.'.'.$key);
}
$value = random_int($value[0], $value[1]);
}
// Legacy callers historically submit numeric strings.
if (is_string($value) && ctype_digit($value)) {
$value = (int) $value;
}
if (! is_int($value) || $value < 0 || $value > $max) {
throw new InvalidArgumentException('Invalid article like value: '.$type.'.'.$key);
}
$result[$key] = $value;
}
return $result;
}
public function newArticleFields(string $type, array $overrides = []): array
{
$values = $this->resolve($type, $overrides);
return ['i7like' => $values['seven_day'], 'i365like' => $values['yearly'],
'iYearLikeTarget' => $values['one_year'], 'iYearLikeAdded' => 0,
'sYearLikeStartedAt' => $values['one_year'] > 0 ? now() : null];
}
}