Skip to content

Commit

Permalink
Merge b72b576 into 3884557
Browse files Browse the repository at this point in the history
  • Loading branch information
dakorpar committed May 7, 2021
2 parents 3884557 + b72b576 commit baa9a16
Show file tree
Hide file tree
Showing 18 changed files with 138 additions and 146 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
6 changes: 3 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
"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",
"nette/forms": "^3.1.2",
"nette/reflection": "^2.4",
"wedo/utilities": "^1.0 || ^2.0"
"wedo/utilities": "^2.0"
},
"require-dev": {
"phpunit/phpunit": "^9.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
18 changes: 18 additions & 0 deletions src/Attributes/HttpMethod.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php declare (strict_types = 1);

namespace Wedo\Api\Attributes;

use Attribute;

#[Attribute]
class HttpMethod
{

public string $value;

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
{

}
84 changes: 43 additions & 41 deletions src/Controllers/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
use Nette\Application\Responses\JsonResponse;
use Nette\Application\UI\Presenter;
use Nette\Localization\Translator;
use Nette\Reflection\Annotation;
use Nette\Utils\Json;
use Nette\Utils\Strings;
use Psr\Log\LoggerInterface;
Expand All @@ -17,11 +16,11 @@
use ReflectionNamedType;
use ReflectionParameter;
use Throwable;
use Wedo\Api\Attributes\HttpMethod;
use Wedo\Api\Exceptions\BadRequestException;
use Wedo\Api\Exceptions\NotFoundException;
use Wedo\Api\Exceptions\ResponseException;
use Wedo\Api\Exceptions\ValidationException;
use Wedo\Api\Helpers\AnnotationHelper;
use Wedo\Api\Requests\BaseRequest;
use Wedo\Api\Responses\BaseResponse;
use Wedo\Api\Responses\ErrorResponse;
Expand All @@ -36,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 @@ -68,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 @@ -90,42 +93,19 @@ 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
*/
protected function validateRequest(ReflectionMethod $rm): void
{
/** @var Annotation $expectedMethod */
$expectedMethod = AnnotationHelper::getAnnotation($rm, 'httpMethod');
$expectedMethod = strtoupper((string) $expectedMethod);

if ($expectedMethod === '') {
$expectedMethod = 'get';
$params = $rm->getParameters();
/** @phpstan-ignore-next-line */
if (!empty($params)) {
/** @var ReflectionNamedType|null $paramClass */
$paramClass = $params[0]->getType();

if ($paramClass !== null) {
$paramClassName = $paramClass->getName();
if (class_exists($paramClassName) && (new ReflectionClass($paramClassName))->isSubclassOf(BaseRequest::class))
$expectedMethod = 'post';
}
}
}
$expectedMethod = $this->getExpectedHttpMethod($rm);

$request = $this->getHttpRequest();

Expand All @@ -136,7 +116,6 @@ protected function validateRequest(ReflectionMethod $rm): void
}
}


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


protected function process(): ?BaseResponse
{
try {
Expand All @@ -203,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 @@ -217,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 @@ -250,10 +226,36 @@ private function setTranslatorOnJsonTranslatable(&$data): void
}
}

public function injectTranslator(Translator $translator): void
private function getExpectedHttpMethod(ReflectionMethod $rm): string
{
$translator = clone $translator;
$this->translator = $translator;
$attributes = $rm->getAttributes(HttpMethod::class);

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

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

$params = $rm->getParameters();

if (count($params) === 0) {
return 'GET';
}

/** @var ReflectionNamedType|null $paramClass */
$paramClass = $params[0]->getType();

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

$paramClassName = $paramClass->getName();
if (class_exists($paramClassName) && (new ReflectionClass($paramClassName))->isSubclassOf(BaseRequest::class)) {
return 'POST';
}

return 'GET';
}

}
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
Loading

0 comments on commit baa9a16

Please sign in to comment.