Skip to content

Commit

Permalink
* replace all usages to laravel facade static proxy with dependency i…
Browse files Browse the repository at this point in the history
…njected constructor property

* replace modifiers on all prop from `protected` to `private readonly` @ `App\Http\PostsQuery\BaseQuery->__construct()`
* remove the alias `BilibiliVoteModel` for import `App\Eloquent\Model\BilibiliVote` since fe56ab4, partial revert cec8b48 @ `App\Http\BilibiliVoteQuery`
* globally suppress `Squiz.Functions.MultiLineFunctionDeclaration.BraceOnSameLine` & `Squiz.WhiteSpace.ScopeClosingBrace.ContentBefore` to fix squizlabs/PHP_CodeSniffer#3291 @ .phpcs.xml
@ be
  • Loading branch information
n0099 committed Sep 16, 2024
1 parent 364c05c commit 57363c5
Show file tree
Hide file tree
Showing 8 changed files with 51 additions and 39 deletions.
6 changes: 5 additions & 1 deletion be/.phpcs.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
<?xml version="1.0"?>
<ruleset>
<rule ref="PSR12" />
<rule ref="PSR12">
<!-- https://github.com/squizlabs/PHP_CodeSniffer/issues/3291 -->
<exclude name="Squiz.Functions.MultiLineFunctionDeclaration.BraceOnSameLine"/>
<exclude name="Squiz.WhiteSpace.ScopeClosingBrace.ContentBefore"/>
</rule>
<arg name="extensions" value="php" />
<exclude-pattern>*.blade.php</exclude-pattern>
<exclude-pattern>_ide_helper*.php</exclude-pattern>
Expand Down
5 changes: 3 additions & 2 deletions be/app/Console/Commands/BatchTableSQLGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@

use App\Eloquent\Model\Forum;
use Illuminate\Console\Command;
use Illuminate\Database\DatabaseManager;

class BatchTableSQLGenerator extends Command
{
protected $signature = 'tbm:batchSQL';

protected $description = '基于所有吧帖子表占位生成SQL';

public function __construct()
public function __construct(private readonly DatabaseManager $db)
{
parent::__construct();
}
Expand Down Expand Up @@ -41,7 +42,7 @@ public function handle(): void
if ($this->confirm('是否执行上述SQL?')) {
foreach ($outputSQLs as $outputSQL) {
try {
$affectedRows = \DB::statement($outputSQL);
$affectedRows = $this->db->statement($outputSQL);
$this->info($outputSQL . ' 影响行数:' . $affectedRows ?? 0);
} catch (\Exception $e) {
$this->error($e->getMessage());
Expand Down
37 changes: 20 additions & 17 deletions be/app/Http/BilibiliVoteQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,22 @@

namespace App\Http;

use App\Eloquent\Model\BilibiliVote as BilibiliVoteModel;
use App\Eloquent\Model\BilibiliVote;
use App\Helper;
use Illuminate\Database\DatabaseManager;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Validation\Rule;
use Spatie\Regex\Regex;

class BilibiliVoteQuery
{
public function __construct(private readonly DatabaseManager $db) {}

/**
* Generate a query builder, which returns top $candidateCount candidates based on valid votes
*/
private static function getCandidatesWithMostVotes(int $candidateCount): \Illuminate\Database\Query\Builder
private function getCandidatesWithMostVotes(int $candidateCount): \Illuminate\Database\Query\Builder
{
/*
* select `voteFor` from (
Expand All @@ -26,8 +29,8 @@ private static function getCandidatesWithMostVotes(int $candidateCount): \Illumi
* limit $candidateCount
* ) as `T`
*/
return \DB::query()->select('voteFor')->fromSub(
BilibiliVoteModel::select('voteFor')
return $this->db->query()->select('voteFor')->fromSub(
BilibiliVote::select('voteFor')
->selectRaw('COUNT(*) AS count')
->where('isValid', true)
->groupBy('voteFor')
Expand All @@ -48,7 +51,7 @@ public static function allCandidatesVoteCount(Request $request): string
* group by `isValid`, `voteFor`
* order by `voteFor` asc
*/
return self::normalizeVoteFor(BilibiliVoteModel::select(['isValid', 'voteFor'])
return self::normalizeVoteFor(BilibiliVote::select(['isValid', 'voteFor'])
->selectRaw('COUNT(*) AS count')
->groupBy('isValid', 'voteFor')
->orderBy('voteFor', 'ASC')
Expand All @@ -72,7 +75,7 @@ public static function allVoteCountsGroupByTime(Request $request): string
$request->validate([
'timeGranularity' => ['required', Rule::in(array_keys($groupByTimeGranularity))],
]);
return BilibiliVoteModel::selectRaw($groupByTimeGranularity[$request->query()['timeGranularity']])
return BilibiliVote::selectRaw($groupByTimeGranularity[$request->query()['timeGranularity']])
->selectRaw('isValid, COUNT(*) AS count')
->groupBy('time', 'isValid')
->orderBy('time', 'ASC')
Expand All @@ -82,7 +85,7 @@ public static function allVoteCountsGroupByTime(Request $request): string
/**
* Return votes count and average voters' exp grade of top 50 candidates
*/
public static function top50CandidatesVoteCount(Request $request): string
public function top50CandidatesVoteCount(Request $request): string
{
/*
* select `isValid`, `voteFor`, COUNT(*) AS count, AVG(authorExpGrade) AS voterAvgGrade
Expand All @@ -91,9 +94,9 @@ public static function top50CandidatesVoteCount(Request $request): string
* group by `isValid`, `voteFor`
* order by `voteFor` asc
*/
return self::normalizeVoteFor(BilibiliVoteModel::select(['isValid', 'voteFor'])
return self::normalizeVoteFor(BilibiliVote::select(['isValid', 'voteFor'])
->selectRaw('COUNT(*) AS count, AVG(authorExpGrade) AS voterAvgGrade')
->whereIn('voteFor', self::getCandidatesWithMostVotes(50))
->whereIn('voteFor', $this->getCandidatesWithMostVotes(50))
->groupBy('isValid', 'voteFor')
->orderBy('voteFor', 'ASC')
->get())
Expand All @@ -107,7 +110,7 @@ public static function top50CandidatesVoteCount(Request $request): string
/**
* Return votes count of top 5 candidates, group by given time range
*/
public static function top5CandidatesVoteCountGroupByTime(Request $request): string
public function top5CandidatesVoteCountGroupByTime(Request $request): string
{
/*
* select DATE_FORMAT(postTime, "%Y-%m-%d %H:%i|00") AS time, `isValid`, `voteFor`, COUNT(*) AS count
Expand All @@ -120,12 +123,12 @@ public static function top5CandidatesVoteCountGroupByTime(Request $request): str
$request->validate([
'timeGranularity' => ['required', Rule::in(array_keys($groupBytimeGranularity))],
]);
return self::normalizeVoteFor(BilibiliVoteModel::selectRaw(
return self::normalizeVoteFor(BilibiliVote::selectRaw(
$groupBytimeGranularity[$request->query()['timeGranularity']],
)
->addSelect(['isValid', 'voteFor'])
->selectRaw('COUNT(*) AS count')
->whereIn('voteFor', self::getCandidatesWithMostVotes(5))
->whereIn('voteFor', $this->getCandidatesWithMostVotes(5))
->groupBy('time', 'isValid', 'voteFor')
->orderBy('time', 'ASC')
->get())
Expand All @@ -135,7 +138,7 @@ public static function top5CandidatesVoteCountGroupByTime(Request $request): str
/**
* Return every 5-min sum of cumulative votes count, group by candidates and validate
*/
public static function top10CandidatesTimeline(Request $request): string
public function top10CandidatesTimeline(Request $request): string
{
/*
* select CAST(timeGranularityRawSQL.endTime AS UNSIGNED) AS endTime,
Expand Down Expand Up @@ -164,17 +167,17 @@ public static function top10CandidatesTimeline(Request $request): string
$timeGranularityRawSQL[] = "SELECT '$time' AS endTime";
}
$timeGranularityRawSQL = implode(' UNION ', $timeGranularityRawSQL);
return self::normalizeVoteFor(\DB::query()
return self::normalizeVoteFor($this->db->query()
->selectRaw('CAST(timeGranularityRawSQL.endTime AS UNSIGNED) AS endTime,
isValid, voteFor, CAST(SUM(timeGroups.count) AS UNSIGNED) AS count')
->fromSub(BilibiliVoteModel::selectRaw(
->fromSub(BilibiliVote::selectRaw(
"FLOOR(UNIX_TIMESTAMP(postTime)/$timeGranularity)*$timeGranularity as endTime,
isValid, voteFor, COUNT(*) as count",
)
->whereIn('voteFor', self::getCandidatesWithMostVotes(10))
->whereIn('voteFor', $this->getCandidatesWithMostVotes(10))
->groupBy('endTime', 'isValid', 'voteFor'), 'timeGroups')
->join(
\DB::raw("($timeGranularityRawSQL) AS timeGranularityRawSQL"),
$this->db->raw("($timeGranularityRawSQL) AS timeGranularityRawSQL"),
'timeGroups.endTime',
'<',
'timeGranularityRawSQL.endTime',
Expand Down
16 changes: 9 additions & 7 deletions be/app/Http/Controllers/PostsQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@
use App\Http\PostsQuery\SearchQuery;
use App\Eloquent\Model\Forum;
use App\Eloquent\Model\User;
use Barryvdh\Debugbar\Facades\Debugbar;
use Barryvdh\Debugbar\LaravelDebugbar;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;

class PostsQuery extends Controller
{
public function __construct(private readonly LaravelDebugbar $debugbar) {}

public function query(\Illuminate\Http\Request $request): array
{
$validator = new ParamsValidator(Helper::jsonDecode(
Expand Down Expand Up @@ -47,14 +49,14 @@ public function query(\Illuminate\Http\Request $request): array
$validator->addDefaultParamsThenValidate($isIndexQuery);

$queryClass = $isIndexQuery ? IndexQuery::class : SearchQuery::class;
Debugbar::startMeasure('$queryClass->query()');
$this->debugbar->startMeasure('$queryClass->query()');
$query = (new $queryClass())->query($params, $request->get('cursor'));
Debugbar::stopMeasure('$queryClass->query()');
Debugbar::startMeasure('fillWithParentPost');
$this->debugbar->stopMeasure('$queryClass->query()');
$this->debugbar->startMeasure('fillWithParentPost');
$result = $query->fillWithParentPost();
Debugbar::stopMeasure('fillWithParentPost');
$this->debugbar->stopMeasure('fillWithParentPost');

Debugbar::startMeasure('queryUsers');
$this->debugbar->startMeasure('queryUsers');
$latestRepliersId = $result['threads']->pluck('latestReplierId');
$latestRepliers = LatestReplier::query()->whereIn('id', $latestRepliersId)
->whereNotNull('uid')->selectPublicFields()->get()
Expand All @@ -71,7 +73,7 @@ public function query(\Illuminate\Http\Request $request): array
->filter()->unique(), // remove NULLs
)->with(['currentForumModerator' => $whereCurrentFid, 'currentAuthorExpGrade' => $whereCurrentFid])
->selectPublicFields()->get();
Debugbar::stopMeasure('queryUsers');
$this->debugbar->stopMeasure('queryUsers');

return [
'type' => $isIndexQuery ? 'index' : 'search',
Expand Down
6 changes: 4 additions & 2 deletions be/app/Http/Controllers/ThreadsSitemap.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@
use App\Eloquent\Model\Forum;
use App\Eloquent\Model\Post\PostFactory;
use App\Helper;
use Illuminate\Cache\Repository;
use Illuminate\Http;
use Illuminate\Support\Facades\Cache;

class ThreadsSitemap extends Controller
{
public static int $maxUrls = 50000;

public function __construct(private readonly Repository $cache) {}

public function query(Http\Request $request, int $fid): Http\Response
{
// https://stackoverflow.com/questions/59554777/laravel-how-to-set-default-value-in-validator-at-post-registeration/78707950#78707950
Expand All @@ -20,7 +22,7 @@ public function query(Http\Request $request, int $fid): Http\Response
]) + ['cursor' => 0];
Helper::abortAPIIfNot(40406, Forum::fid($fid)->exists());

return Cache::remember(
return $this->cache->remember(
"/sitemaps/forums/$fid/threads?cursor=$cursor",
86400,
static fn() => Helper::xmlResponse(view('sitemaps.threads', [
Expand Down
5 changes: 2 additions & 3 deletions be/app/Http/PostsQuery/BaseQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,8 @@ abstract class BaseQuery
abstract public function query(QueryParams $params, ?string $cursor): self;

public function __construct(
protected LaravelDebugbar $debugbar,
protected int $perPageItems = 50,
// @phpcs:ignore Squiz.Functions.MultiLineFunctionDeclaration.BraceOnSameLine, Squiz.WhiteSpace.ScopeClosingBrace.ContentBefore -- https://github.com/squizlabs/PHP_CodeSniffer/issues/3291
private readonly LaravelDebugbar $debugbar,
private readonly int $perPageItems = 50,
) {}

public function getResultPages(): array
Expand Down
13 changes: 7 additions & 6 deletions be/app/Http/PostsQuery/ParamsValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use App\Helper;
use Illuminate\Support\Arr;
use Illuminate\Validation\Factory;
use Illuminate\Validation\Rule;

class ParamsValidator
Expand All @@ -15,9 +16,9 @@ class ParamsValidator
protected array $currentPostTypes;

/** @param array[] $params */
public function __construct(array $params)
public function __construct(private readonly Factory $validator, array $params)
{
self::validateParamsValue($params);
$this->validateParamsValue($params);
$this->params = new QueryParams($params);
$this->validate40001();
$this->validate40005();
Expand All @@ -36,20 +37,20 @@ public function addDefaultParamsThenValidate(bool $shouldSkip40003): void
$this->validate40004();
}

private static function validateParamsValue(array $params): void
private function validateParamsValue(array $params): void
{
$paramsPossibleValue = [
'userGender' => [0, 1, 2],
'userManagerType' => ['NULL', 'manager', 'assist', 'voiceadmin'],
];
$dateRangeValidator = static function ($_, string $value): void {
\Validator::make(
$dateRangeValidator = function ($_, string $value): void {
$this->validator->make(
explode(',', $value),
['0' => 'date|before_or_equal:1', '1' => 'date|after_or_equal:0'],
)->validate();
};
// note here we haven't validated that is every sub param have a corresponding main param yet
\Validator::make($params, [
$this->validator->make($params, [
'*.fid' => 'integer',
'*.postTypes' => 'array|in:thread,reply,subReply',
'*.orderBy' => 'string|in:postedAt,tid,pid,spid',
Expand Down
2 changes: 1 addition & 1 deletion be/tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

// @phpcs:ignore PSR2.Classes.ClassDeclaration.OpenBraceNewLine, Squiz.WhiteSpace.ScopeClosingBrace.ContentBefore -- https://github.com/PHPCSStandards/PHP_CodeSniffer/issues/566
// @phpcs:ignore PSR2.Classes.ClassDeclaration.OpenBraceNewLine -- https://github.com/PHPCSStandards/PHP_CodeSniffer/issues/566
abstract class TestCase extends BaseTestCase {}

0 comments on commit 57363c5

Please sign in to comment.