Skip to content

Commit

Permalink
Remove phpcs exclusions for linting
Browse files Browse the repository at this point in the history
Remove phpcs exclusions and fix
linting errors according to
Mediawiki Coding Rules

Bug: T328730
  • Loading branch information
Parthiv-M authored May 9, 2023
1 parent 33bafe3 commit 9af00f8
Show file tree
Hide file tree
Showing 13 changed files with 80 additions and 35 deletions.
3 changes: 2 additions & 1 deletion .phan/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
],

'suppress_issue_types' => [
'PhanUnreferencedUseNormal', // PHPCS does this already and without false positives.
// PHPCS does this already and without false positives.
'PhanUnreferencedUseNormal',
'SecurityCheck-LikelyFalsePositive',
],

Expand Down
11 changes: 0 additions & 11 deletions .phpcs.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,6 @@
<element key="tests" value="App\Tests" />
</property>
</properties>
<!-- remove the below exclude rules after making the linting changes manually in a separate PR -->
<exclude name="Generic.Files.LineLength.TooLong" />
<exclude name="MediaWiki.Classes.UnusedUseStatement.UnusedUse" />
<exclude name="MediaWiki.Commenting.MissingCovers.MissingCovers" />
<exclude name="MediaWiki.Commenting.FunctionComment.MissingReturn" />
<exclude name="MediaWiki.Commenting.FunctionComment.MissingParamTag" />
<exclude name="MediaWiki.Commenting.FunctionComment.ParamNameNoMatch" />
<exclude name="Generic.ControlStructures.DisallowYodaConditions.Found" />
<exclude name="MediaWiki.Commenting.FunctionComment.MissingDocumentationPublic" />
<exclude name="MediaWiki.WhiteSpace.SpaceBeforeSingleLineComment.NewLineComment" />
<exclude name="MediaWiki.Commenting.FunctionAnnotations.UnrecognizedAnnotation" />
</rule>
<file>.</file>
<arg name="bootstrap" value="./vendor/mediawiki/mediawiki-codesniffer/utils/bootstrap-ci.php"/>
Expand Down
5 changes: 3 additions & 2 deletions src/Command/TranskribusAuthCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ protected function configure(): void {
* Method that runs the CLI command.
* @param InputInterface $input
* @param OutputInterface $output
* @return int
*/
protected function execute( InputInterface $input, OutputInterface $output ): int {
$helper = $this->getHelper( 'question' );
Expand All @@ -52,7 +53,7 @@ protected function execute( InputInterface $input, OutputInterface $output ): in
$tokenResponse = $this->transkribusClient->getAccessTokenResponse( $userName, $password );

$statusCode = $tokenResponse->getStatusCode();
if ( 200 === $statusCode ) {
if ( $statusCode === 200 ) {
$content = json_decode( $tokenResponse->getContent() );
if ( $content === null ) {
$io->error( 'Response from Transkribus API could not be parsed' );
Expand All @@ -68,7 +69,7 @@ protected function execute( InputInterface $input, OutputInterface $output ): in
$io->writeln( 'APP_TRANSKRIBUS_REFRESH_TOKEN=' . $refreshToken );
return Command::SUCCESS;
}
} elseif ( 401 === $statusCode ) {
} elseif ( $statusCode === 401 ) {
$io->error( 'Error Code ' . $statusCode . ' :: Credentials are incorrect!' );
return Command::FAILURE;
} else {
Expand Down
10 changes: 9 additions & 1 deletion src/Controller/OcrController.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use App\Exception\EngineNotFoundException;
use Exception;
use Krinkle\Intuition\Intuition;
// phpcs:ignore MediaWiki.Classes.UnusedUseStatement.UnusedUse
use OpenApi\Annotations as OA;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
Expand All @@ -20,6 +21,7 @@
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
// phpcs:ignore MediaWiki.Classes.UnusedUseStatement.UnusedUse
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
Expand Down Expand Up @@ -102,7 +104,7 @@ private function setup(): void {
// Parameters.
static::$params['image'] = (string)$this->request->query->get( 'image' );
// Change protocol-relative URLs to https to avoid issues with Curl.
if ( '//' === substr( static::$params['image'], 0, 2 ) ) {
if ( substr( static::$params['image'], 0, 2 ) === '//' ) {
static::$params['image'] = "https:" . static::$params['image'];
}
static::$params['langs'] = $this->getLangs( $this->request );
Expand Down Expand Up @@ -151,7 +153,9 @@ public function getLangs( Request $request ): array {

/**
* The main form and result page.
* phpcs:disable MediaWiki.Commenting.FunctionAnnotations.UnrecognizedAnnotation
* @Route("/", name="home")
* phpcs:enable
* @return Response
*/
public function homeAction(): Response {
Expand All @@ -176,6 +180,7 @@ public function homeAction(): Response {
}

/**
* phpcs:disable MediaWiki.Commenting.FunctionAnnotations.UnrecognizedAnnotation
* @Route("/api", name="api", methods={"GET"})
* @Route("/api.php", name="apiPhp", methods={"GET"})
* @OA\Parameter(
Expand Down Expand Up @@ -212,6 +217,7 @@ public function homeAction(): Response {
* @OA\Schema(type="array", @OA\Items(type="int"))
* )
* @OA\Response(response=200, description="The OCR text, and other data.")
* phpcs:enable
* @return JsonResponse
*/
public function apiAction(): JsonResponse {
Expand All @@ -235,6 +241,7 @@ public function apiAction(): JsonResponse {
}

/**
* phpcs:disable MediaWiki.Commenting.FunctionAnnotations.UnrecognizedAnnotation
* @Route("/api/available_langs", name="apiLangs", methods={"GET"})
* @OA\Parameter(
* name="engine",
Expand All @@ -244,6 +251,7 @@ public function apiAction(): JsonResponse {
* @OA\Schema(type="string")
* )
* @OA\Response(response=200, description="List of available language codes and names, in JSON format.")
* phpcs:enable
* @return JsonResponse
*/
public function apiAvailableLangsAction(): JsonResponse {
Expand Down
5 changes: 3 additions & 2 deletions src/Engine/EngineBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ abstract class EngineBase {
* EngineBase constructor.
* @param Intuition $intuition
* @param string $projectDir
* @param HttpClientInterface $httpClient
*/
public function __construct( Intuition $intuition, string $projectDir, HttpClientInterface $httpClient ) {
$this->intuition = $intuition;
Expand Down Expand Up @@ -148,7 +149,7 @@ public function getValidLangs( bool $withNames = false ): array {
* @return string
*/
public function getLangName( ?string $lang = null ): string {
return '' === $this->intuition->getLangName( $lang )
return $this->intuition->getLangName( $lang ) === ''
? ( self::LANG_NAMES[$lang] ?? '' )
: $this->intuition->getLangName( $lang );
}
Expand Down Expand Up @@ -190,7 +191,7 @@ public function checkImageUrl( string $imageUrl ): void {
$formatRegex = implode( '|', self::ALLOWED_FORMATS );
$regex = "/^https?:\/\/($hostRegex)\/.+($formatRegex)$/";
$matches = preg_match( $regex, strtolower( $imageUrl ) );
if ( 1 !== $matches ) {
if ( $matches !== 1 ) {
$params = [ count( $this->getImageHosts() ), $this->intuition->listToText( $this->getImageHosts() ) ];
throw new OcrException( 'image-url-error', $params );
}
Expand Down
9 changes: 9 additions & 0 deletions src/Engine/EngineFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ class EngineFactory {
/** @var array<string, EngineBase> */
private $engines;

/**
* @param GoogleCloudVisionEngine $cloudVisionEngine
* @param TesseractEngine $tesseractEngine
* @param TranskribusEngine $transkribusEngine
*/
public function __construct(
GoogleCloudVisionEngine $cloudVisionEngine,
TesseractEngine $tesseractEngine,
Expand All @@ -22,6 +27,10 @@ public function __construct(
];
}

/**
* @param string $name
* @return EngineBase
*/
public function get( string $name ): EngineBase {
if ( !isset( $this->engines[$name] ) ) {
throw new EngineNotFoundException();
Expand Down
1 change: 1 addition & 0 deletions src/Engine/GoogleCloudVisionEngine.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class GoogleCloudVisionEngine extends EngineBase {
* @param string $keyFile Filesystem path to the credentials JSON file.
* @param Intuition $intuition
* @param string $projectDir
* @param HttpClientInterface $httpClient
*/
public function __construct(
string $keyFile,
Expand Down
22 changes: 19 additions & 3 deletions src/Engine/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,17 @@ class Image {
private $size;

/**
* @param string $imageUrl
* @param int[] $crop
*/
public function __construct( string $imageUrl, array $crop = [] ) {
$this->imageUrl = $imageUrl;
$this->crop = $crop;
}

/**
* @return string
*/
public function getUrl(): string {
return $this->imageUrl;
}
Expand All @@ -39,6 +43,9 @@ public function needsCropping(): bool {
&& isset( $this->crop['height'] ) && $this->crop['height'] > 0;
}

/**
* @return Crop
*/
public function getCrop(): Crop {
return new Crop(
new Point( $this->crop['x'], $this->crop['y'] ),
Expand All @@ -47,16 +54,22 @@ public function getCrop(): Crop {
}

public function hasData(): bool {
return null !== $this->data;
return $this->data !== null;
}

/**
* @return string
*/
public function getData(): string {
if ( null === $this->data ) {
if ( $this->data === null ) {
throw new LogicException( 'Image::setData() must be called before getData()' );
}
return $this->data;
}

/**
* @param string $data
*/
public function setData( string $data ): void {
$this->data = $data;
}
Expand All @@ -66,12 +79,15 @@ public function setData( string $data ): void {
* @return int
*/
public function getSize(): int {
if ( null === $this->data ) {
if ( $this->data === null ) {
throw new LogicException( 'Image::setData() must be called before getSize()' );
}
return $this->size ?? strlen( $this->data );
}

/**
* @param int $size
*/
public function setSize( int $size ): void {
$this->size = $size;
}
Expand Down
28 changes: 17 additions & 11 deletions src/Engine/TranskribusClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
namespace App\Engine;

use App\Exception\OcrException;
use stdclass;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

class TranskribusClient {

Expand Down Expand Up @@ -73,7 +75,7 @@ public function initProcess( string $imageURL, int $htrId, string $points ): int

$content = $this->request( 'POST', self::PROCESSES_URL, $jsonBody );

if ( 'FAILED' !== $content->status ) {
if ( $content->status !== 'FAILED' ) {
$processId = $content->processId;
return $processId;
}
Expand All @@ -91,11 +93,11 @@ public function retrieveProcessResult( int $processId ): string {
$content = $this->request( 'GET', $url );
$textResult = '';

if ( 'FAILED' === $content->status ) {
if ( $content->status === 'FAILED' ) {
throw new OcrException( 'transkribus-failed-process-error' );
}

if ( 'FINISHED' === $content->status ) {
if ( $content->status === 'FINISHED' ) {
$this->processStatus = $content->status;
$textResult = $content->content->text ?? '';
}
Expand Down Expand Up @@ -129,6 +131,7 @@ private function throwException( int $statusCode ): void {
* @param string $method
* @param string $url
* @param mixed[] $jsonBody
* @return stdClass
*/
private function request(
string $method,
Expand All @@ -141,13 +144,13 @@ private function request(
'Authorization' => 'Bearer ' . $this->accessToken,
],
];
if ( [] != $jsonBody ) {
if ( $jsonBody != [] ) {
$body['json'] = $jsonBody;
}

$response = $this->httpClient->request( $method, $url, $body );
$statusCode = $response->getStatusCode();
if ( 200 === $statusCode ) {
if ( $statusCode === 200 ) {
$content = json_decode( $response->getContent() );

if ( !empty( $content ) ) {
Expand All @@ -156,14 +159,14 @@ private function request(
$this->throwException( self::ERROR_NO_CONTENT );
}

if ( 401 === $statusCode ) {
if ( $statusCode === 401 ) {
$this->setAccessToken();

$body['headers']['Authorization'] = 'Bearer ' . $this->accessToken;
$response = $this->httpClient->request( $method, $url, $body );
$statusCode = $response->getStatusCode();

if ( 200 === $statusCode ) {
if ( $statusCode === 200 ) {
$content = json_decode( $response->getContent() );

if ( !empty( $content ) ) {
Expand All @@ -178,7 +181,7 @@ private function request(
private function setAccessToken(): void {
$response = $this->getRefreshTokenResponse( $this->refreshToken );
$statusCode = $response->getStatusCode();
if ( 200 !== $statusCode ) {
if ( $statusCode !== 200 ) {
$this->throwException( $statusCode );
}
$content = json_decode( $response->getContent() );
Expand All @@ -190,8 +193,9 @@ private function setAccessToken(): void {

/**
* @param string $token
* @return ResponseInterface
*/
public function getRefreshTokenResponse( string $token ): object {
public function getRefreshTokenResponse( string $token ): ResponseInterface {
$body = [
'grant_type' => 'refresh_token',
'client_id' => 'processing-api-client',
Expand All @@ -205,8 +209,9 @@ public function getRefreshTokenResponse( string $token ): object {
/**
* @param string $userName
* @param string $password
* @return ResponseInterface
*/
public function getAccessTokenResponse( string $userName, string $password ): object {
public function getAccessTokenResponse( string $userName, string $password ): ResponseInterface {
$body = [
'grant_type' => 'password',
'username' => $userName,
Expand All @@ -221,8 +226,9 @@ public function getAccessTokenResponse( string $userName, string $password ): ob

/**
* @param mixed[] $body
* @return ResponseInterface
*/
private function authRequest( array $body ): object {
private function authRequest( array $body ): ResponseInterface {
$response = $this->httpClient->request(
'POST',
self::AUTH_URL,
Expand Down
7 changes: 4 additions & 3 deletions src/Engine/TranskribusEngine.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ public function getResult(
$y = $crop['y'];
$yPlusH = $crop['y'] + $crop['height'];
$xPlusW = $crop['x'] + $crop['width'];
$points = $x . ',' . $y . ' ' . $xPlusW . ',' . $y . ' ' . $xPlusW . ',' . $yPlusH . ' ' . $x . ',' . $yPlusH;
$points = $x . ',' . $y . ' ' . $xPlusW . ',' .
$y . ' ' . $xPlusW . ',' . $yPlusH . ' ' . $x . ',' . $yPlusH;
}

$modelId = 0;
Expand All @@ -67,15 +68,15 @@ public function getResult(
throw new OcrException( 'transkribus-no-lang-error' );
}
$langCodes = $this->getLangCodes( $validLangs );
if ( 1 < count( $langCodes ) ) {
if ( count( $langCodes ) > 1 ) {
throw new OcrException( 'transkribus-multiple-lang-error' );
}
$modelId = (int)$langCodes[0];

$processId = $this->transkribusClient->initProcess( $imageUrl, $modelId, $points );

$resText = '';
while ( 'FINISHED' !== $this->transkribusClient->processStatus ) {
while ( $this->transkribusClient->processStatus !== 'FINISHED' ) {
$resText = $this->transkribusClient->retrieveProcessResult( $processId );
sleep( 2 );
}
Expand Down
Loading

0 comments on commit 9af00f8

Please sign in to comment.