Skip to content

Commit

Permalink
Switch internal annotation to php8 attribute/apply contributte coding…
Browse files Browse the repository at this point in the history
… styles
  • Loading branch information
dakorpar committed May 7, 2021
1 parent 1eb00ef commit b72b576
Show file tree
Hide file tree
Showing 18 changed files with 94 additions and 132 deletions.
12 changes: 5 additions & 7 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ jobs:

strategy:
matrix:
php-version: ["7.4"]
php-version: ["8.0"]
operating-system: ["ubuntu-latest"]
fail-fast: false

Expand Down Expand Up @@ -80,20 +80,18 @@ jobs:
runs-on: "${{ matrix.operating-system }}"
strategy:
matrix:
php-version: ["7.4"]
php-version: ["8.0"]
operating-system: ["ubuntu-latest"]
composer-args: [ "" ]
include:
- php-version: "7.4"
- php-version: "8.0"
operating-system: "ubuntu-latest"
composer-args: "--prefer-lowest"
- php-version: "8.0"
operating-system: "ubuntu-latest"
composer-args: "--ignore-platform-reqs"
fail-fast: false

continue-on-error: "${{ matrix.php-version == '8.0' }}"

steps:
- name: "Checkout"
uses: "actions/checkout@v2"
Expand Down Expand Up @@ -149,7 +147,7 @@ jobs:

strategy:
matrix:
php-version: ["7.4"]
php-version: ["8.0"]
operating-system: ["ubuntu-latest"]
fail-fast: false

Expand Down Expand Up @@ -205,7 +203,7 @@ jobs:

strategy:
matrix:
php-version: ["7.4"]
php-version: ["8.0"]
operating-system: ["ubuntu-latest"]
fail-fast: false

Expand Down
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"description": "rest api",
"license": ["MIT"],
"require": {
"php": "^7.4 || ^8.0",
"php": "^8.0",
"psr/log": "^1.1",
"nette/di": "^3.0",
"nette/application": "^3.0",
Expand All @@ -18,7 +18,7 @@
"phpstan/phpstan-dibi": "^0.12",
"phpstan/phpstan-nette": "^0.12",
"phpstan/phpstan-strict-rules": "^0.12",
"ninjify/qa": "^0.12"
"contributte/qa": "^0.1"
},
"autoload": {
"psr-4": {
Expand Down
4 changes: 2 additions & 2 deletions ruleset.xml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<?xml version="1.0"?>
<ruleset>
<!-- Contributte Coding Standard -->
<rule ref="./vendor/ninjify/coding-standard/contributte.xml">
<exclude name="SlevomatCodingStandard.Classes.SuperfluousInterfaceNaming.SuperfluousSuffix"></exclude>
<rule ref="./vendor/contributte/qa/ruleset.xml">
<exclude name="SlevomatCodingStandard.Classes.SuperfluousErrorNaming.SuperfluousSuffix"></exclude>
</rule>
<rule ref="SlevomatCodingStandard.TypeHints.ParameterTypeHint" />
<rule ref="SlevomatCodingStandard.TypeHints.ReturnTypeHint" />
Expand Down
3 changes: 3 additions & 0 deletions src/Attributes/HttpMethod.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Wedo\Api\Attributes;

use Attribute;

#[Attribute]
class HttpMethod
{
Expand All @@ -12,4 +14,5 @@ public function __construct(string $value)
{
$this->value = $value;
}

}
11 changes: 11 additions & 0 deletions src/Attributes/Internal.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php declare (strict_types = 1);

namespace Wedo\Api\Attributes;

use Attribute;

#[Attribute]
class Internal
{

}
43 changes: 15 additions & 28 deletions src/Controllers/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,12 @@
class Controller extends Presenter
{

/** @var mixed */
public $payload = [];

protected LoggerInterface $logger;
public mixed $payload = [];

public Request $request;

protected LoggerInterface $logger;

protected Translator $translator;

/**
Expand All @@ -67,13 +66,18 @@ public function run(Request $request): Response
//all ok, abort exception shouldn't be thrown to user
}

$result = $result ?? $this->payload;
$result ??= $this->payload;

$this->setTranslatorOnJsonTranslatable($result);

return new JsonResponse($result ?? $this->payload);
}

public function injectTranslator(Translator $translator): void
{
$translator = clone $translator;
$this->translator = $translator;
}

/**
* @param mixed[] $params
Expand All @@ -89,18 +93,13 @@ protected function tryCall(string $method, array $params): bool
$this->validateRequest($rm);
$methodParams = $rm->getParameters();

if (count($methodParams) > 0) {
$params = $this->createParams($params, $methodParams);
} else {
$params = [];
}
$params = count($methodParams) > 0 ? $this->createParams($params, $methodParams) : [];

$this->payload = $rm->invokeArgs($this, $params);

return true;
}


/**
* @throws BadRequestException
*/
Expand All @@ -117,7 +116,6 @@ protected function validateRequest(ReflectionMethod $rm): void
}
}


/**
* @param mixed[] $params
* @param ReflectionParameter[] $methodParams
Expand Down Expand Up @@ -158,7 +156,6 @@ protected function createParams(array $params, array $methodParams): array
return $params;
}


protected function process(): ?BaseResponse
{
try {
Expand All @@ -184,12 +181,11 @@ protected function process(): ?BaseResponse
return $result;
}


protected function beforeProcess(): void
{
//override if needed
}


protected function setOptionsRequestHeaders(): void
{
$this->getHttpResponse()->addHeader('Access-Control-Allow-Headers', 'api-key, accept, Content-Type, session-id');
Expand All @@ -198,11 +194,10 @@ protected function setOptionsRequestHeaders(): void
$this->getHttpResponse()->setCode(200);
}


/**
* @param BaseResponse|JsonObject|mixed[] $data
*/
private function setTranslatorOnJsonTranslatable(&$data): void
private function setTranslatorOnJsonTranslatable(mixed $data): void
{
if (is_array($data)) {
foreach ($data as $key => $value) {
Expand Down Expand Up @@ -231,23 +226,15 @@ private function setTranslatorOnJsonTranslatable(&$data): void
}
}

public function injectTranslator(Translator $translator): void
{
$translator = clone $translator;
$this->translator = $translator;
}


private function getExpectedHttpMethod(ReflectionMethod $rm): string
{
$attributes = $rm->getAttributes('HttpMethod');
$attributes = $rm->getAttributes(HttpMethod::class);

if (count($attributes) > 0) {
/** @var HttpMethod $httpMethod */
$httpMethod = $attributes[0]->newInstance();
return Strings::upper($httpMethod->value);


return Strings::upper($httpMethod->value);
}

$params = $rm->getParameters();
Expand All @@ -259,7 +246,7 @@ private function getExpectedHttpMethod(ReflectionMethod $rm): string
/** @var ReflectionNamedType|null $paramClass */
$paramClass = $params[0]->getType();

if ($paramClass === NULL) {
if ($paramClass === null) {
return 'GET';
}

Expand Down
4 changes: 2 additions & 2 deletions src/DI/ApiExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
use Nette\Application\Routers\Route;
use Nette\DI\CompilerExtension;
use Nette\DI\Definitions\ServiceDefinition;
use Nette\Reflection\AnnotationsParser;
use Nette\Utils\Strings;
use ReflectionClass;
use ReflectionMethod;
use Wedo\Api\Attributes\Internal;
use Wedo\Api\Routing\RouterFactory;

/**
Expand Down Expand Up @@ -58,7 +58,7 @@ public function beforeCompile(): void

foreach ($publicMethods as $oneMethod) {
if ($oneMethod->isConstructor() ||
isset(AnnotationsParser::getAll($oneMethod)['internal']) ||
count($oneMethod->getAttributes(Internal::class)) > 0 ||
$oneMethod->getDeclaringClass()->getName() !== $obj->getName()) {
continue;
}
Expand Down
3 changes: 1 addition & 2 deletions src/Exceptions/BadRequestException.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@ class BadRequestException extends ResponseException
{

/**
* @param mixed|string ...$parameters
* @codeCoverageIgnore
*/
public function __construct(string $message = '', int $code = 400, ?Throwable $previous = null, ...$parameters)
public function __construct(string $message = '', int $code = 400, ?Throwable $previous = null, mixed ...$parameters)
{
parent::__construct($message, $code, $previous, $parameters);
}
Expand Down
8 changes: 2 additions & 6 deletions src/Exceptions/ResponseException.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,13 @@ class ResponseException extends Exception
/** @var ResponseException[] */
protected array $additionalExceptions = [];

/**
* @param mixed|string ...$parameters
*/
public function __construct(string $message = '', int $code = 500, ?Throwable $previous = null, ...$parameters)
public function __construct(string $message = '', int $code = 500, ?Throwable $previous = null, mixed ...$parameters)
{
$this->parameters = $parameters;

parent::__construct($message, $code, $previous);
}


public function getTranslatedMessage(ITranslator $translator): string
{
return $translator->translate($this->getMessage(), $this->parameters);
Expand Down Expand Up @@ -52,7 +49,6 @@ public function getAll(): array
return [...[$this], ...$this->getAdditionalExceptions()];
}


/**
* @return string[]
*/
Expand Down
3 changes: 1 addition & 2 deletions src/Exceptions/ValidationException.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ class ValidationException extends ResponseException
public function __construct(array $validationErrors)
{
parent::__construct('Data is not Valid!', 422);

$this->validationErrors = $validationErrors;
}


/**
* @return ValidationError[]
* @codeCoverageIgnore
Expand All @@ -29,7 +29,6 @@ public function getValidationErrors(): array
return $this->validationErrors;
}


/**
* @param ValidationError[] $validationErrors
* @codeCoverageIgnore
Expand Down
5 changes: 2 additions & 3 deletions src/Helpers/AnnotationHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,11 @@ class AnnotationHelper

/**
* Returns an annotation value.
*
* @return string|IAnnotation
*/
public static function getAnnotation(Reflector $reflector, string $name)
public static function getAnnotation(Reflector $reflector, string $name): string|IAnnotation|null
{
$res = AnnotationsParser::getAll($reflector);

return isset($res[$name]) ? end($res[$name]) : null;
}

Expand Down
10 changes: 5 additions & 5 deletions src/Helpers/FormBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,11 @@ public function createForm(array $properties, BaseRequest $request, Container $f
}
}

public function createEmptyForm(): Form
{
return new Form();
}

/**
* @param string[][] $annotations
* @throws ArgumentOutOfRangeException
Expand All @@ -79,9 +84,4 @@ protected function getControlType(array $annotations): string
return $annotations['control'][0];
}

public function createEmptyForm(): Form
{
return new Form();
}

}
12 changes: 2 additions & 10 deletions src/Helpers/RequestHydrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,7 @@
class RequestHydrator
{

/**
* @param mixed|string $value
* @return string|int|float|bool|DateTimeImmutable|null
*/
public static function hydrateValue(ReflectionNamedType $type, $value)
public static function hydrateValue(ReflectionNamedType $type, mixed $value): string|int|float|bool|DateTimeImmutable|null
{
if (!$type->isBuiltin() && $type->getName() !== 'DateTimeInterface') {
throw new InvalidArgumentException('Only built in types are supported! ' . $type->getName() . ' is not supported');
Expand All @@ -22,11 +18,7 @@ public static function hydrateValue(ReflectionNamedType $type, $value)
return self::castValueToBuiltInType($value, $type->getName(), $type->allowsNull());
}

/**
* @param mixed $value
* @return int|float|string|bool|DateTimeImmutable|null
*/
public static function castValueToBuiltInType($value, string $type, bool $allowsNull)
public static function castValueToBuiltInType(mixed $value, string $type, bool $allowsNull): int|float|string|bool|DateTimeImmutable|null
{
switch ($type) {
case 'int':
Expand Down

0 comments on commit b72b576

Please sign in to comment.