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

Commit a449e48

Browse files
committed
Fix MediaWiki style violations in OcrController.php
1 parent e86687b commit a449e48

1 file changed

Lines changed: 90 additions & 108 deletions

File tree

src/Controller/OcrController.php

Lines changed: 90 additions & 108 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
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

@@ -15,23 +15,20 @@
1515
use App\Exception\EngineNotFoundException;
1616
use Exception;
1717
use Krinkle\Intuition\Intuition;
18-
use OpenApi\Annotations as OA;
1918
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
2019
use Symfony\Component\HttpFoundation\JsonResponse;
2120
use Symfony\Component\HttpFoundation\Request;
2221
use Symfony\Component\HttpFoundation\RequestStack;
2322
use Symfony\Component\HttpFoundation\Response;
2423
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
2524
use Symfony\Component\HttpFoundation\Session\SessionInterface;
26-
use Symfony\Component\Routing\Annotation\Route;
2725
use Symfony\Contracts\Cache\CacheInterface;
2826
use Symfony\Contracts\Cache\ItemInterface;
2927

3028
// phpcs:ignore MediaWiki.Classes.UnusedUseStatement.UnusedUse
3129
// phpcs:ignore MediaWiki.Classes.UnusedUseStatement.UnusedUse
3230

33-
class OcrController extends AbstractController
34-
{
31+
class OcrController extends AbstractController {
3532
/** @var Intuition */
3633
protected $intuition;
3734

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

109105
static::$params['engine'] = $this->engine::getId();
110106
$this->setEngineOptions();
111107

112108
// Parameters.
113-
static::$params['image'] = (string) $this->request->query->get('image');
109+
static::$params['image'] = (string)$this->request->query->get( 'image' );
114110
// Change protocol-relative URLs to https to avoid issues with Curl.
115-
if (substr(static::$params['image'], 0, 2) === '//') {
111+
if ( substr( static::$params['image'], 0, 2 ) === '//' ) {
116112
static::$params['image'] = "https:" . static::$params['image'];
117113
}
118-
static::$params['langs'] = $this->getLangs($this->request);
114+
static::$params['langs'] = $this->getLangs( $this->request );
119115
static::$params['image_hosts'] = $this->engine->getImageHosts();
120-
$crop = $this->request->query->get('crop');
116+
$crop = $this->request->query->get( 'crop' );
121117
if (
122-
!is_array($crop)
123-
|| isset($crop['width']) && !$crop['width']
124-
|| isset($crop['height']) && !$crop['height']
118+
!is_array( $crop )
119+
|| ( isset( $crop['width'] ) && !$crop['width'] )
120+
|| ( isset( $crop['height'] ) && !$crop['height'] )
125121
) {
126122
$crop = [];
127123
}
128-
static::$params['crop'] = array_map('intval', $crop);
124+
static::$params['crop'] = array_map( 'intval', $crop );
129125

130-
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 );
131127
}
132128

133129
/**
134130
* Set Engine-specific options based on user-provided input or the defaults.
135131
*/
136-
private function setEngineOptions(): void
137-
{
132+
private function setEngineOptions(): void {
138133
// This is always set, even if Tesseract isn't initially chosen as the engine
139134
// because we want the default set if the user changes the engine to Tesseract.
140-
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'] );
141136

142137
// This is always set, even if Transkribus isn't initially chosen as the engine
143138
// because we want the default set if the user changes the engine to Transkribus.
144-
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'] );
145140

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

152147
// Apply Transkribus specific settings
153-
if (TranskribusEngine::getId() === static::$params['engine']) {
154-
$this->engine->setLineId(static::$params['line_id']);
148+
if ( TranskribusEngine::getId() === static::$params['engine'] ) {
149+
$this->engine->setLineId( static::$params['line_id'] );
155150
}
156151
}
157152

@@ -161,63 +156,56 @@ private function setEngineOptions(): void
161156
* @param Request $request
162157
* @return string[]
163158
*/
164-
public function getLangs(Request $request): array
165-
{
166-
$lang = $request->query->get('lang');
167-
$langs = $request->query->all('langs');
168-
$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 );
169163
// Remove invalid chars.
170-
$langsSanitized = preg_replace('/[^a-zA-Z0-9\-_]/', '', $langArray);
164+
$langsSanitized = preg_replace( '/[^a-zA-Z0-9\-_]/', '', $langArray );
171165
// Remove empty and duplicated values, and then reorder keys (just for easier testing).
172-
$langsFiltered = array_values(array_unique(array_filter($langsSanitized)));
166+
$langsFiltered = array_values( array_unique( array_filter( $langsSanitized ) ) );
173167
// If no languages specified, default to the user's.
174168
// @TODO The default language code needs to vary based on the engine. T280617.
175169
//return 0 === count($langsFiltered) ? [$this->intuition->getLang()] : $langsFiltered;
176170
return $langsFiltered;
177171
}
178172

179-
/**
180-
* The main form and result page.
181-
* @Route("/", name="home")
182-
* @return Response
183-
*/
184-
public function homeAction(): Response
185-
{
173+
public function homeAction(): Response {
186174
$this->setup();
187175

188176
// Pre-supply available langs for autocompletion in the form.
189-
static::$params['available_langs'] = $this->engine->getValidModels(true);
190-
ksort(static::$params['available_langs']);
177+
static::$params['available_langs'] = $this->engine->getValidModels( true );
178+
ksort( static::$params['available_langs'] );
191179

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

195-
if (static::$params['engine'] === 'transkribus') {
183+
if ( static::$params['engine'] === 'transkribus' ) {
196184
// Pre-supply the available line ids for autocompletion in the form.
197-
static::$params['available_line_ids'] = $this->engine->getValidLineIds(true, false);
198-
sort(static::$params['available_line_ids']);
185+
static::$params['available_line_ids'] = $this->engine->getValidLineIds( true, false );
186+
sort( static::$params['available_line_ids'] );
199187

200-
static::$params['available_line_id_langs'] = $this->engine->getValidLineIds(false, true);
201-
sort(static::$params['available_line_id_langs']);
188+
static::$params['available_line_id_langs'] = $this->engine->getValidLineIds( false, true );
189+
sort( static::$params['available_line_id_langs'] );
202190
}
203191

204192
// Get Tesseract's full list of PSMs.
205193
/** @var TesseractEngine */
206-
$tesseract = $this->engineFactory->get('tesseract');
194+
$tesseract = $this->engineFactory->get( 'tesseract' );
207195
static::$params['available_psms'] = $tesseract->getAvailablePsms();
208196

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

212-
if (static::$params['image']) {
213-
$result = $this->getResult(EngineBase::ERROR_ON_INVALID_LANGS);
200+
if ( static::$params['image'] ) {
201+
$result = $this->getResult( EngineBase::ERROR_ON_INVALID_LANGS );
214202
static::$params['text'] = $result->getText();
215-
foreach ($result->getWarnings() as $warning) {
216-
$this->addFlash('warning', $warning);
203+
foreach ( $result->getWarnings() as $warning ) {
204+
$this->addFlash( 'warning', $warning );
217205
}
218206
}
219207

220-
return $this->render('output.html.twig', static::$params);
208+
return $this->render( 'output.html.twig', static::$params );
221209
}
222210

223211
/**
@@ -291,25 +279,24 @@ public function homeAction(): Response
291279
* @OA\Response(response=200, description="The OCR text, and other data.")
292280
* @return JsonResponse
293281
*/
294-
public function apiAction(): JsonResponse
295-
{
282+
public function apiAction(): JsonResponse {
296283
try {
297284
$this->setup();
298-
} catch (Exception $exception) {
299-
return $this->getApiResponse([
285+
} catch ( Exception $exception ) {
286+
return $this->getApiResponse( [
300287
"error" => $exception->getMessage(),
301-
]);
288+
] );
302289
}
303290

304-
$result = $this->getResult(EngineBase::WARN_ON_INVALID_LANGS);
305-
$responseParams = array_merge(static::$params, [
291+
$result = $this->getResult( EngineBase::WARN_ON_INVALID_LANGS );
292+
$responseParams = array_merge( static::$params, [
306293
'text' => $result->getText(),
307-
]);
294+
] );
308295
$warnings = $result->getWarnings();
309-
if ($warnings) {
296+
if ( $warnings ) {
310297
$responseParams['warnings'] = $warnings;
311298
}
312-
return $this->getApiResponse($responseParams);
299+
return $this->getApiResponse( $responseParams );
313300
}
314301

315302
/**
@@ -326,13 +313,12 @@ public function apiAction(): JsonResponse
326313
* @OA\Response(response=200, description="List of available model codes and names, in JSON format.")
327314
* @return JsonResponse
328315
*/
329-
public function apiAvailableLangsAction(): JsonResponse
330-
{
316+
public function apiAvailableLangsAction(): JsonResponse {
331317
$this->setup();
332-
return $this->getApiResponse([
318+
return $this->getApiResponse( [
333319
'engine' => static::$params['engine'],
334-
'available_langs' => $this->engine->getValidModels(true),
335-
]);
320+
'available_langs' => $this->engine->getValidModels( true ),
321+
] );
336322
}
337323

338324
/**
@@ -342,14 +328,13 @@ public function apiAvailableLangsAction(): JsonResponse
342328
* @OA\Response(response=200, description="List of available Tesseract PSM values and labels, in JSON format.")
343329
* @return JsonResponse
344330
*/
345-
public function apiAvailablePsms(): JsonResponse
346-
{
331+
public function apiAvailablePsms(): JsonResponse {
347332
$this->setup();
348333
/** @var TesseractEngine */
349-
$tesseract = $this->engineFactory->get('tesseract');
350-
return $this->getApiResponse([
334+
$tesseract = $this->engineFactory->get( 'tesseract' );
335+
return $this->getApiResponse( [
351336
'available_psms' => $tesseract->getAvailablePsms(),
352-
]);
337+
] );
353338
}
354339

355340
/**
@@ -360,39 +345,37 @@ public function apiAvailablePsms(): JsonResponse
360345
* phpcs:enable
361346
* @return JsonResponse
362347
*/
363-
public function apiAvailableLineDetectionModelIds(): JsonResponse
364-
{
365-
$this->request->query->set('engine', 'transkribus');
348+
public function apiAvailableLineDetectionModelIds(): JsonResponse {
349+
$this->request->query->set( 'engine', 'transkribus' );
366350
static::$params['engine'] = 'transkribus';
367351
$this->setup();
368-
return $this->getApiResponse([
369-
'available_line_ids' => $this->engine->getValidLineIds(false, false),
370-
]);
352+
return $this->getApiResponse( [
353+
'available_line_ids' => $this->engine->getValidLineIds( false, false ),
354+
] );
371355
}
372356

373357
/**
374358
* Return a new JsonResponse with the given $params merged into static::$params.
375359
* @param mixed[] $params
376360
* @return JsonResponse
377361
*/
378-
private function getApiResponse(array $params): JsonResponse
379-
{
362+
private function getApiResponse( array $params ): JsonResponse {
380363
$response = new JsonResponse();
381-
$response->setEncodingOptions(JSON_NUMERIC_CHECK);
382-
$response->setStatusCode(Response::HTTP_OK);
364+
$response->setEncodingOptions( JSON_NUMERIC_CHECK );
365+
$response->setStatusCode( Response::HTTP_OK );
383366

384367
// Expose flash messages.
385368
/** @var FlashBag $flashBag */
386-
$flashBag = $this->session->getBag('flashes');
369+
$flashBag = $this->session->getBag( 'flashes' );
387370
'@phan-var FlashBag $flashBag';
388-
if ($flashBag->has('error')) {
389-
$params['error'] = $flashBag->get('error');
371+
if ( $flashBag->has( 'error' ) ) {
372+
$params['error'] = $flashBag->get( 'error' );
390373
}
391374

392375
// Allow API requests from the Wikisource extension wherever it's installed.
393-
$response->headers->set('Access-Control-Allow-Origin', '*');
376+
$response->headers->set( 'Access-Control-Allow-Origin', '*' );
394377

395-
$response->setData($params);
378+
$response->setData( $params );
396379
return $response;
397380
}
398381

@@ -401,40 +384,39 @@ private function getApiResponse(array $params): JsonResponse
401384
* @param string $invalidLangsMode EngineBase::WARN_ON_INVALID_LANGS or EngineBase::ERROR_ON_INVALID_LANGS
402385
* @return EngineResult
403386
*/
404-
private function getResult(string $invalidLangsMode): EngineResult
405-
{
406-
ksort(static::$params['crop']);
407-
$cacheKey = md5(implode(
387+
private function getResult( string $invalidLangsMode ): EngineResult {
388+
ksort( static::$params['crop'] );
389+
$cacheKey = md5( implode(
408390
'|',
409391
[
410392
static::$params['image'],
411393
static::$params['engine'],
412-
implode('|', static::$params['langs']),
413-
implode('|', array_map('strval', static::$params['crop'])),
394+
implode( '|', static::$params['langs'] ),
395+
implode( '|', array_map( 'strval', static::$params['crop'] ) ),
414396
static::$params['psm'],
415397
static::$params['line_id'],
416398
static::$params['handle_refs'] ? 'refs=1' : 'refs=0',
417399
// Warning messages are localized
418400
$this->intuition->getLang(),
419401
]
420-
));
402+
) );
421403

422-
$result = $this->cache->get($cacheKey, function (ItemInterface $item) use ($invalidLangsMode) {
423-
$item->expiresAfter((int) $this->getParameter('cache_ttl'));
404+
$result = $this->cache->get( $cacheKey, function ( ItemInterface $item ) use ( $invalidLangsMode ) {
405+
$item->expiresAfter( (int)$this->getParameter( 'cache_ttl' ) );
424406
return $this->engine->getResult(
425407
static::$params['image'],
426408
$invalidLangsMode,
427409
static::$params['crop'],
428410
static::$params['langs']
429411
);
430-
});
431-
if (!$result instanceof EngineResult) {
432-
throw new Exception('Incorrect (possibly cached) result: ' . var_export($result, true));
412+
} );
413+
if ( !$result instanceof EngineResult ) {
414+
throw new Exception( 'Incorrect (possibly cached) result: ' . var_export( $result, true ) );
433415
}
434416

435-
if (static::$params['handle_refs']) {
417+
if ( static::$params['handle_refs'] ) {
436418
$result = new EngineResult(
437-
ReferencePostProcessor::process($result->getText()),
419+
ReferencePostProcessor::process( $result->getText() ),
438420
$result->getWarnings()
439421
);
440422
}

0 commit comments

Comments
 (0)