Skip to content
This repository was archived by the owner on May 28, 2026. It is now read-only.

Commit 088b636

Browse files
committed
Fix PHPCS style violations for T375919
1 parent e1bc175 commit 088b636

2 files changed

Lines changed: 145 additions & 160 deletions

File tree

src/Controller/OcrController.php

Lines changed: 94 additions & 106 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,34 @@
11
<?php
22
// phpcs:disable MediaWiki.Commenting.FunctionAnnotations.UnrecognizedAnnotation
33

4-
declare(strict_types=1);
4+
declare( strict_types=1 );
55

66
namespace App\Controller;
77

88
use App\Engine\EngineBase;
99
use App\Engine\EngineFactory;
1010
use App\Engine\EngineResult;
1111
use App\Engine\GoogleCloudVisionEngine;
12-
use App\Engine\TesseractEngine;
1312
use App\Engine\ReferencePostProcessor;
13+
use App\Engine\TesseractEngine;
1414
use App\Engine\TranskribusEngine;
1515
use App\Exception\EngineNotFoundException;
1616
use Exception;
1717
use Krinkle\Intuition\Intuition;
18-
// phpcs:ignore MediaWiki.Classes.UnusedUseStatement.UnusedUse
19-
use OpenApi\Annotations as OA;
2018
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
2119
use Symfony\Component\HttpFoundation\JsonResponse;
2220
use Symfony\Component\HttpFoundation\Request;
2321
use Symfony\Component\HttpFoundation\RequestStack;
2422
use Symfony\Component\HttpFoundation\Response;
2523
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
2624
use Symfony\Component\HttpFoundation\Session\SessionInterface;
27-
// phpcs:ignore MediaWiki.Classes.UnusedUseStatement.UnusedUse
28-
use Symfony\Component\Routing\Annotation\Route;
2925
use Symfony\Contracts\Cache\CacheInterface;
3026
use Symfony\Contracts\Cache\ItemInterface;
3127

32-
class OcrController extends AbstractController
33-
{
28+
// phpcs:ignore MediaWiki.Classes.UnusedUseStatement.UnusedUse
29+
// phpcs:ignore MediaWiki.Classes.UnusedUseStatement.UnusedUse
30+
31+
class OcrController extends AbstractController {
3432
/** @var Intuition */
3533
protected $intuition;
3634

@@ -92,65 +90,63 @@ public function __construct(
9290
* Setup the engine and parameters needed for the view. This must be called before every action.
9391
* @suppress PhanSuspiciousValueComparison
9492
*/
95-
private function setup(): void
96-
{
97-
$requestedEngine = $this->request->query->get('engine', static::$params['engine']);
93+
private function setup(): void {
94+
$requestedEngine = $this->request->query->get( 'engine', static::$params['engine'] );
9895
try {
99-
$this->engine = $this->engineFactory->get($requestedEngine);
100-
} catch (EngineNotFoundException $e) {
101-
$this->addFlash('error', $this->intuition->msg(
96+
$this->engine = $this->engineFactory->get( $requestedEngine );
97+
} catch ( EngineNotFoundException $e ) {
98+
$this->addFlash( 'error', $this->intuition->msg(
10299
'engine-not-found-warning',
103-
['variables' => [$requestedEngine, static::DEFAULT_ENGINE]]
104-
));
105-
$this->engine = $this->engineFactory->get(static::DEFAULT_ENGINE);
100+
[ 'variables' => [ $requestedEngine, static::DEFAULT_ENGINE ] ]
101+
) );
102+
$this->engine = $this->engineFactory->get( static::DEFAULT_ENGINE );
106103
}
107104

108105
static::$params['engine'] = $this->engine::getId();
109106
$this->setEngineOptions();
110107

111108
// Parameters.
112-
static::$params['image'] = (string) $this->request->query->get('image');
109+
static::$params['image'] = (string)$this->request->query->get( 'image' );
113110
// Change protocol-relative URLs to https to avoid issues with Curl.
114-
if (substr(static::$params['image'], 0, 2) === '//') {
111+
if ( substr( static::$params['image'], 0, 2 ) === '//' ) {
115112
static::$params['image'] = "https:" . static::$params['image'];
116113
}
117-
static::$params['langs'] = $this->getLangs($this->request);
114+
static::$params['langs'] = $this->getLangs( $this->request );
118115
static::$params['image_hosts'] = $this->engine->getImageHosts();
119-
$crop = $this->request->query->get('crop');
116+
$crop = $this->request->query->get( 'crop' );
120117
if (
121-
!is_array($crop)
122-
|| isset($crop['width']) && !$crop['width']
123-
|| isset($crop['height']) && !$crop['height']
118+
!is_array( $crop )
119+
|| isset( $crop['width'] ) && !$crop['width']
120+
|| isset( $crop['height'] ) && !$crop['height']
124121
) {
125122
$crop = [];
126123
}
127-
static::$params['crop'] = array_map('intval', $crop);
124+
static::$params['crop'] = array_map( 'intval', $crop );
128125

129-
static::$params['handle_refs'] = (bool) $this->request->query->get('handle_refs', false);
126+
static::$params['handle_refs'] = (bool)$this->request->query->get( 'handle_refs', false );
130127
}
131128

132129
/**
133130
* Set Engine-specific options based on user-provided input or the defaults.
134131
*/
135-
private function setEngineOptions(): void
136-
{
132+
private function setEngineOptions(): void {
137133
// This is always set, even if Tesseract isn't initially chosen as the engine
138134
// because we want the default set if the user changes the engine to Tesseract.
139-
static::$params['psm'] = (int) $this->request->query->get('psm', (string) static::$params['psm']);
135+
static::$params['psm'] = (int)$this->request->query->get( 'psm', (string)static::$params['psm'] );
140136

141137
// This is always set, even if Transkribus isn't initially chosen as the engine
142138
// because we want the default set if the user changes the engine to Transkribus.
143-
static::$params['line_id'] = (int) $this->request->query->get('line_id', (string) static::$params['line_id']);
139+
static::$params['line_id'] = (int)$this->request->query->get( 'line_id', (string)static::$params['line_id'] );
144140

145141
// Apply the tesseract-specific settings
146142
// NOTE: Intentionally excluding `oem`, see T285262
147-
if (TesseractEngine::getId() === static::$params['engine']) {
148-
$this->engine->setPsm(static::$params['psm']);
143+
if ( TesseractEngine::getId() === static::$params['engine'] ) {
144+
$this->engine->setPsm( static::$params['psm'] );
149145
}
150146

151147
// Apply Transkribus specific settings
152-
if (TranskribusEngine::getId() === static::$params['engine']) {
153-
$this->engine->setLineId(static::$params['line_id']);
148+
if ( TranskribusEngine::getId() === static::$params['engine'] ) {
149+
$this->engine->setLineId( static::$params['line_id'] );
154150
}
155151
}
156152

@@ -160,15 +156,14 @@ private function setEngineOptions(): void
160156
* @param Request $request
161157
* @return string[]
162158
*/
163-
public function getLangs(Request $request): array
164-
{
165-
$lang = $request->query->get('lang');
166-
$langs = $request->query->all('langs');
167-
$langArray = array_merge([$lang], $langs);
159+
public function getLangs( Request $request ): array {
160+
$lang = $request->query->get( 'lang' );
161+
$langs = $request->query->all( 'langs' );
162+
$langArray = array_merge( [ $lang ], $langs );
168163
// Remove invalid chars.
169-
$langsSanitized = preg_replace('/[^a-zA-Z0-9\-_]/', '', $langArray);
164+
$langsSanitized = preg_replace( '/[^a-zA-Z0-9\-_]/', '', $langArray );
170165
// Remove empty and duplicated values, and then reorder keys (just for easier testing).
171-
$langsFiltered = array_values(array_unique(array_filter($langsSanitized)));
166+
$langsFiltered = array_values( array_unique( array_filter( $langsSanitized ) ) );
172167
// If no languages specified, default to the user's.
173168
// @TODO The default language code needs to vary based on the engine. T280617.
174169
//return 0 === count($langsFiltered) ? [$this->intuition->getLang()] : $langsFiltered;
@@ -180,43 +175,42 @@ public function getLangs(Request $request): array
180175
* @Route("/", name="home")
181176
* @return Response
182177
*/
183-
public function homeAction(): Response
184-
{
178+
public function homeAction(): Response {
185179
$this->setup();
186180

187181
// Pre-supply available langs for autocompletion in the form.
188-
static::$params['available_langs'] = $this->engine->getValidModels(true);
189-
ksort(static::$params['available_langs']);
182+
static::$params['available_langs'] = $this->engine->getValidModels( true );
183+
ksort( static::$params['available_langs'] );
190184

191185
// set empty array to avoid errors while rendering template on non-transkribus engines
192186
static::$params['available_line_ids'] = [];
193187

194-
if (static::$params['engine'] === 'transkribus') {
188+
if ( static::$params['engine'] === 'transkribus' ) {
195189
// Pre-supply the available line ids for autocompletion in the form.
196-
static::$params['available_line_ids'] = $this->engine->getValidLineIds(true, false);
197-
sort(static::$params['available_line_ids']);
190+
static::$params['available_line_ids'] = $this->engine->getValidLineIds( true, false );
191+
sort( static::$params['available_line_ids'] );
198192

199-
static::$params['available_line_id_langs'] = $this->engine->getValidLineIds(false, true);
200-
sort(static::$params['available_line_id_langs']);
193+
static::$params['available_line_id_langs'] = $this->engine->getValidLineIds( false, true );
194+
sort( static::$params['available_line_id_langs'] );
201195
}
202196

203197
// Get Tesseract's full list of PSMs.
204198
/** @var TesseractEngine */
205-
$tesseract = $this->engineFactory->get('tesseract');
199+
$tesseract = $this->engineFactory->get( 'tesseract' );
206200
static::$params['available_psms'] = $tesseract->getAvailablePsms();
207201

208202
// Intution::listToText() isn't available via Twig, and we only want to do this for the view and not the API.
209-
static::$params['image_hosts'] = $this->intuition->listToText(static::$params['image_hosts']);
203+
static::$params['image_hosts'] = $this->intuition->listToText( static::$params['image_hosts'] );
210204

211-
if (static::$params['image']) {
212-
$result = $this->getResult(EngineBase::ERROR_ON_INVALID_LANGS);
205+
if ( static::$params['image'] ) {
206+
$result = $this->getResult( EngineBase::ERROR_ON_INVALID_LANGS );
213207
static::$params['text'] = $result->getText();
214-
foreach ($result->getWarnings() as $warning) {
215-
$this->addFlash('warning', $warning);
208+
foreach ( $result->getWarnings() as $warning ) {
209+
$this->addFlash( 'warning', $warning );
216210
}
217211
}
218212

219-
return $this->render('output.html.twig', static::$params);
213+
return $this->render( 'output.html.twig', static::$params );
220214
}
221215

222216
/**
@@ -290,25 +284,24 @@ public function homeAction(): Response
290284
* @OA\Response(response=200, description="The OCR text, and other data.")
291285
* @return JsonResponse
292286
*/
293-
public function apiAction(): JsonResponse
294-
{
287+
public function apiAction(): JsonResponse {
295288
try {
296289
$this->setup();
297-
} catch (Exception $exception) {
298-
return $this->getApiResponse([
290+
} catch ( Exception $exception ) {
291+
return $this->getApiResponse( [
299292
"error" => $exception->getMessage(),
300-
]);
293+
] );
301294
}
302295

303-
$result = $this->getResult(EngineBase::WARN_ON_INVALID_LANGS);
304-
$responseParams = array_merge(static::$params, [
296+
$result = $this->getResult( EngineBase::WARN_ON_INVALID_LANGS );
297+
$responseParams = array_merge( static::$params, [
305298
'text' => $result->getText(),
306-
]);
299+
] );
307300
$warnings = $result->getWarnings();
308-
if ($warnings) {
301+
if ( $warnings ) {
309302
$responseParams['warnings'] = $warnings;
310303
}
311-
return $this->getApiResponse($responseParams);
304+
return $this->getApiResponse( $responseParams );
312305
}
313306

314307
/**
@@ -325,13 +318,12 @@ public function apiAction(): JsonResponse
325318
* @OA\Response(response=200, description="List of available model codes and names, in JSON format.")
326319
* @return JsonResponse
327320
*/
328-
public function apiAvailableLangsAction(): JsonResponse
329-
{
321+
public function apiAvailableLangsAction(): JsonResponse {
330322
$this->setup();
331-
return $this->getApiResponse([
323+
return $this->getApiResponse( [
332324
'engine' => static::$params['engine'],
333-
'available_langs' => $this->engine->getValidModels(true),
334-
]);
325+
'available_langs' => $this->engine->getValidModels( true ),
326+
] );
335327
}
336328

337329
/**
@@ -341,14 +333,13 @@ public function apiAvailableLangsAction(): JsonResponse
341333
* @OA\Response(response=200, description="List of available Tesseract PSM values and labels, in JSON format.")
342334
* @return JsonResponse
343335
*/
344-
public function apiAvailablePsms(): JsonResponse
345-
{
336+
public function apiAvailablePsms(): JsonResponse {
346337
$this->setup();
347338
/** @var TesseractEngine */
348-
$tesseract = $this->engineFactory->get('tesseract');
349-
return $this->getApiResponse([
339+
$tesseract = $this->engineFactory->get( 'tesseract' );
340+
return $this->getApiResponse( [
350341
'available_psms' => $tesseract->getAvailablePsms(),
351-
]);
342+
] );
352343
}
353344

354345
/**
@@ -359,39 +350,37 @@ public function apiAvailablePsms(): JsonResponse
359350
* phpcs:enable
360351
* @return JsonResponse
361352
*/
362-
public function apiAvailableLineDetectionModelIds(): JsonResponse
363-
{
364-
$this->request->query->set('engine', 'transkribus');
353+
public function apiAvailableLineDetectionModelIds(): JsonResponse {
354+
$this->request->query->set( 'engine', 'transkribus' );
365355
static::$params['engine'] = 'transkribus';
366356
$this->setup();
367-
return $this->getApiResponse([
368-
'available_line_ids' => $this->engine->getValidLineIds(false, false),
369-
]);
357+
return $this->getApiResponse( [
358+
'available_line_ids' => $this->engine->getValidLineIds( false, false ),
359+
] );
370360
}
371361

372362
/**
373363
* Return a new JsonResponse with the given $params merged into static::$params.
374364
* @param mixed[] $params
375365
* @return JsonResponse
376366
*/
377-
private function getApiResponse(array $params): JsonResponse
378-
{
367+
private function getApiResponse( array $params ): JsonResponse {
379368
$response = new JsonResponse();
380-
$response->setEncodingOptions(JSON_NUMERIC_CHECK);
381-
$response->setStatusCode(Response::HTTP_OK);
369+
$response->setEncodingOptions( JSON_NUMERIC_CHECK );
370+
$response->setStatusCode( Response::HTTP_OK );
382371

383372
// Expose flash messages.
384373
/** @var FlashBag $flashBag */
385-
$flashBag = $this->session->getBag('flashes');
374+
$flashBag = $this->session->getBag( 'flashes' );
386375
'@phan-var FlashBag $flashBag';
387-
if ($flashBag->has('error')) {
388-
$params['error'] = $flashBag->get('error');
376+
if ( $flashBag->has( 'error' ) ) {
377+
$params['error'] = $flashBag->get( 'error' );
389378
}
390379

391380
// Allow API requests from the Wikisource extension wherever it's installed.
392-
$response->headers->set('Access-Control-Allow-Origin', '*');
381+
$response->headers->set( 'Access-Control-Allow-Origin', '*' );
393382

394-
$response->setData($params);
383+
$response->setData( $params );
395384
return $response;
396385
}
397386

@@ -400,40 +389,39 @@ private function getApiResponse(array $params): JsonResponse
400389
* @param string $invalidLangsMode EngineBase::WARN_ON_INVALID_LANGS or EngineBase::ERROR_ON_INVALID_LANGS
401390
* @return EngineResult
402391
*/
403-
private function getResult(string $invalidLangsMode): EngineResult
404-
{
405-
ksort(static::$params['crop']);
406-
$cacheKey = md5(implode(
392+
private function getResult( string $invalidLangsMode ): EngineResult {
393+
ksort( static::$params['crop'] );
394+
$cacheKey = md5( implode(
407395
'|',
408396
[
409397
static::$params['image'],
410398
static::$params['engine'],
411-
implode('|', static::$params['langs']),
412-
implode('|', array_map('strval', static::$params['crop'])),
399+
implode( '|', static::$params['langs'] ),
400+
implode( '|', array_map( 'strval', static::$params['crop'] ) ),
413401
static::$params['psm'],
414402
static::$params['line_id'],
415403
static::$params['handle_refs'] ? 'refs=1' : 'refs=0',
416404
// Warning messages are localized
417405
$this->intuition->getLang(),
418406
]
419-
));
407+
) );
420408

421-
$result = $this->cache->get($cacheKey, function (ItemInterface $item) use ($invalidLangsMode) {
422-
$item->expiresAfter((int) $this->getParameter('cache_ttl'));
409+
$result = $this->cache->get( $cacheKey, function ( ItemInterface $item ) use ( $invalidLangsMode ) {
410+
$item->expiresAfter( (int)$this->getParameter( 'cache_ttl' ) );
423411
return $this->engine->getResult(
424412
static::$params['image'],
425413
$invalidLangsMode,
426414
static::$params['crop'],
427415
static::$params['langs']
428416
);
429-
});
430-
if (!$result instanceof EngineResult) {
431-
throw new Exception('Incorrect (possibly cached) result: ' . var_export($result, true));
417+
} );
418+
if ( !$result instanceof EngineResult ) {
419+
throw new Exception( 'Incorrect (possibly cached) result: ' . var_export( $result, true ) );
432420
}
433421

434-
if (static::$params['handle_refs']) {
422+
if ( static::$params['handle_refs'] ) {
435423
$result = new EngineResult(
436-
ReferencePostProcessor::process($result->getText()),
424+
ReferencePostProcessor::process( $result->getText() ),
437425
$result->getWarnings()
438426
);
439427
}

0 commit comments

Comments
 (0)