Skip to content

Commit

Permalink
More compatibility adjustments
Browse files Browse the repository at this point in the history
  • Loading branch information
byjg committed Sep 19, 2024
1 parent a348f89 commit 7ba0095
Show file tree
Hide file tree
Showing 17 changed files with 77 additions and 83 deletions.
8 changes: 4 additions & 4 deletions builder/Scripts.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public static function codeGenerator(Event $event)
* @throws ConfigException
* @throws InvalidDateException
*/
public function runMigrate($arguments)
public function runMigrate($arguments): void
{
$argumentList = $this->extractArguments($arguments);
if (isset($argumentList["command"])) {
Expand Down Expand Up @@ -160,7 +160,7 @@ protected function extractArguments(array $arguments, bool $hasCmd = true): arra
* @param array $arguments
* @return void
*/
public function runGenOpenApiDocs(array $arguments)
public function runGenOpenApiDocs(array $arguments): void
{
$docPath = $this->workdir . '/public/docs/';

Expand All @@ -187,7 +187,7 @@ public function runGenOpenApiDocs(array $arguments)
* @throws \ByJG\Serializer\Exception\InvalidArgumentException
* @throws Exception
*/
public function runCodeGenerator(array $arguments)
public function runCodeGenerator(array $arguments): void
{
// Get Table Name
$table = null;
Expand Down Expand Up @@ -379,7 +379,7 @@ public function runCodeGenerator(array $arguments)
echo "Processing Test for table $table...\n";
$template = $loader->getTemplate('test.php');
if ($save) {
$file = __DIR__ . '/../tests/Functional/Rest/' . $data['className'] . 'Test.php';
$file = __DIR__ . '/../tests/Rest/' . $data['className'] . 'Test.php';
file_put_contents($file, $template->render($data));
echo "File saved in $file\n";
} else {
Expand Down
3 changes: 2 additions & 1 deletion docker/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,5 @@ COPY templates /srv/templates
COPY composer.* /srv
COPY phpunit.xml.dist /srv
COPY db /srv/db
RUN composer install --no-dev --no-interaction --no-progress --no-scripts --optimize-autoloader
RUN composer install --no-dev --no-interaction --no-progress --no-scripts --optimize-autoloader && \
composer dump-autoload --optimize --classmap-authoritative -q
41 changes: 22 additions & 19 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -6,33 +6,36 @@ and open the template in the editor.
-->

<!-- see http://www.phpunit.de/wiki/Documentation -->
<phpunit bootstrap="./vendor/autoload.php"
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
bootstrap="./vendor/autoload.php"
colors="true"
testdox="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
convertDeprecationsToExceptions="true"
stopOnFailure="false">
stopOnFailure="false"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">

<filter>
<whitelist>
<directory>./src</directory>
</whitelist>
</filter>
<coverage>
<include>
<directory>./src</directory>
</include>
</coverage>

<testsuites>
<testsuite name="Test Suite">
<directory>./tests/</directory>
</testsuite>
</testsuites>
<testsuites>
<testsuite name="Backend Tests">
<directory>./tests/Rest</directory>
<directory>./tests/</directory>
</testsuite>
</testsuites>

<php>
<ini name="display_errors" value="On" />
<ini name="display_startup_errors" value="On" />
<ini name="error_reporting" value="E_ALL" />
<php>
<ini name="display_errors" value="On"/>
<ini name="display_startup_errors" value="On"/>
<ini name="error_reporting" value="E_ALL"/>

<!-- important, do not remove -->
<env name="APP_ENV" value="test" force="true" />
</php>
<!-- important, do not remove -->
<env name="APP_ENV" value="test" force="true"/>
</php>
</phpunit>
20 changes: 9 additions & 11 deletions src/Model/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

namespace RestReferenceArchitecture\Model;

use ByJG\Authenticate\Definition\PasswordDefinition;
use ByJG\Authenticate\Model\UserModel;
use ByJG\Authenticate\Model\UserPropertiesModel;
use ByJG\MicroOrm\Literal\HexUuidLiteral;
use InvalidArgumentException;
use OpenApi\Attributes as OA;
use RestReferenceArchitecture\Psr11;

#[OA\Schema(required: ["email"], type: "object", xml: new OA\Xml(name: "User"))]
class User extends UserModel
Expand All @@ -26,10 +26,10 @@ class User extends UserModel
const ROLE_USER = 'user';

/**
* @var ?string
* @var ?string|int|HexUuidLiteral
*/
#[OA\Property(type: "string", format: "string")]
protected ?string $userid = null;
protected string|int|HexUuidLiteral|null $userid = null;

/**
* @var ?string
Expand Down Expand Up @@ -90,26 +90,24 @@ class User extends UserModel
* @param string $password
* @param string $admin
*/
public function __construct(string $name = "", string $email = "", string $username = "", string $password = "", string $admin = "")
public function __construct(string $name = "", string $email = "", string $username = "", string $password = "", string $admin = "no")
{
parent::__construct($name, $email, $username, $password, $admin);

$this->withPasswordDefinition(Psr11::container()->get(PasswordDefinition::class));
}


/**
* @return string|null
* @return string|HexUuidLiteral|int|null
*/
public function getUserid(): ?string
public function getUserid(): string|HexUuidLiteral|int|null
{
return $this->userid;
}

/**
* @param string|null $userid
* @param string|HexUuidLiteral|int|null $userid
*/
public function setUserid(?string $userid): void
public function setUserid(string|HexUuidLiteral|int|null $userid): void
{
$this->userid = $userid;
}
Expand Down
19 changes: 7 additions & 12 deletions src/OpenApiSpec.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

namespace RestReferenceArchitecture;

use OpenApi\Attributes as OA;

#[OA\Info(
Expand All @@ -23,19 +24,13 @@
)]
#[OA\Schema(
schema: 'error',
required: ['error'],
properties: [
new OA\Property(
property: 'error',
required: ['type', 'message', 'file', 'line'],
properties: [
new OA\Property(property: 'type', description: 'A class de Exceção', type: 'string'),
new OA\Property(property: 'message', description: 'A mensagem de erro', type: 'string'),
new OA\Property(property: 'file', description: 'O arquivo que gerou o erro', type: 'string'),
new OA\Property(property: 'line', description: 'A linha do erro', type: 'integer')
],
type: 'object'
)
new OA\Property('error', properties: [
new OA\Property(property: 'type', description: 'A class de Exceção', type: 'string'),
new OA\Property(property: 'message', description: 'A mensagem de erro', type: 'string'),
new OA\Property(property: 'file', description: 'O arquivo que gerou o erro', type: 'string'),
new OA\Property(property: 'line', description: 'A linha do erro', type: 'integer'),
])
],
type: 'object'
)]
Expand Down
7 changes: 5 additions & 2 deletions src/Psr11.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,19 @@ class Psr11
private static ?Container $container = null;

/**
* @param null $env
* @param string|null $env
* @return Container
* @throws ConfigException
* @throws ConfigNotFoundException
* @throws InvalidArgumentException
* @throws InvalidDateException
*/
public static function container($env = null): ?Container
public static function container(?string $env = null): ?Container
{
if (is_null(self::$container)) {
if (PHP_INT_SIZE < 8) {
throw new \Exception("This application requires 64-bit PHP");
}
self::$container = self::environment()->build($env);
}

Expand Down
30 changes: 12 additions & 18 deletions src/Rest/Login.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,10 @@ class Login
)]
public function post(HttpResponse $response, HttpRequest $request)
{
OpenApiContext::validateRequest($request);

$json = json_decode($request->payload());
$json = OpenApiContext::validateRequest($request);

$users = Psr11::container()->get(UsersDBDataset::class);
$user = $users->isValidUser($json->username, $json->password);
$user = $users->isValidUser($json["username"], $json["password"]);
$metadata = JwtContext::createUserMetadata($user);

$response->getResponseBag()->setSerializationRule(SerializationRuleEnum::SingleObject);
Expand Down Expand Up @@ -149,12 +147,10 @@ public function refreshToken(HttpResponse $response, HttpRequest $request)
)]
public function postResetRequest(HttpResponse $response, HttpRequest $request)
{
OpenApiContext::validateRequest($request);

$json = json_decode($request->payload());
$json = OpenApiContext::validateRequest($request);

$users = Psr11::container()->get(UsersDBDataset::class);
$user = $users->getByEmail($json->email);
$user = $users->getByEmail($json["email"]);

$token = BaseRepository::getUuid();
$code = rand(10000, 99999);
Expand All @@ -168,7 +164,7 @@ public function postResetRequest(HttpResponse $response, HttpRequest $request)

// Send email using MailWrapper
$mailWrapper = Psr11::container()->get(MailWrapperInterface::class);
$envelope = Psr11::container()->get('MAIL_ENVELOPE', [$json->email, "RestReferenceArchitecture - Password Reset", "email_code.html", [
$envelope = Psr11::container()->get('MAIL_ENVELOPE', [$json["email"], "RestReferenceArchitecture - Password Reset", "email_code.html", [
"code" => trim(chunk_split($code, 1, ' ')),
"expire" => 10
]]);
Expand All @@ -181,18 +177,16 @@ public function postResetRequest(HttpResponse $response, HttpRequest $request)

protected function validateResetToken($response, $request): array
{
OpenApiContext::validateRequest($request);

$json = json_decode($request->payload());
$json = OpenApiContext::validateRequest($request);

$users = Psr11::container()->get(UsersDBDataset::class);
$user = $users->getByEmail($json->email);
$user = $users->getByEmail($json["email"]);

if (is_null($user)) {
throw new Error422Exception("Invalid data");
}

if ($user->get("resettoken") != $json->token) {
if ($user->get("resettoken") != $json["token"]) {
throw new Error422Exception("Invalid data");
}

Expand Down Expand Up @@ -241,14 +235,14 @@ public function postConfirmCode(HttpResponse $response, HttpRequest $request)
{
list($users, $user, $json) = $this->validateResetToken($response, $request);

if ($user->get("resetcode") != $json->code) {
if ($user->get("resetcode") != $json["code"]) {
throw new Error422Exception("Invalid data");
}

$user->set("resetallowed", "yes");
$users->save($user);

$response->write(['token' => $json->token]);
$response->write(['token' => $json["token"]]);
}

/**
Expand Down Expand Up @@ -293,13 +287,13 @@ public function postResetPassword(HttpResponse $response, HttpRequest $request)
throw new Error422Exception("Invalid data");
}

$user->setPassword($json->password);
$user->setPassword($json["password"]);
$user->set("resettoken", null);
$user->set("resettokenexpire", null);
$user->set("resetcode", null);
$user->set("resetallowed", null);
$users->save($user);

$response->write(['token' => $json->token]);
$response->write(['token' => $json["token"]]);
}
}
7 changes: 3 additions & 4 deletions src/Util/JwtContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace RestReferenceArchitecture\Util;

use ByJG\Authenticate\Model\UserModel;
use ByJG\Config\Exception\ConfigException;
use ByJG\Config\Exception\ConfigNotFoundException;
use ByJG\Config\Exception\DependencyInjectionException;
Expand All @@ -24,11 +23,11 @@ class JwtContext
protected static ?HttpRequest $request;

/**
* @param ?UserModel $user
* @param ?User $user
* @return array
* @throws Error401Exception
*/
public static function createUserMetadata(?UserModel $user): array
public static function createUserMetadata(?User $user): array
{
if (is_null($user)) {
throw new Error401Exception('Username or password is invalid');
Expand All @@ -52,7 +51,7 @@ public static function createUserMetadata(?UserModel $user): array
* @throws KeyNotFoundException
* @throws ReflectionException
*/
public static function createToken($properties = [])
public static function createToken(array $properties = [])
{
$jwt = Psr11::container()->get(JwtWrapper::class);
$jwtData = $jwt->createJwtData($properties, 60 * 60 * 24 * 7); // 7 Dias
Expand Down
7 changes: 4 additions & 3 deletions src/Util/OpenApiContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use ByJG\ApiTools\Base\Schema;
use ByJG\RestServer\Exception\Error400Exception;
use ByJG\RestServer\HttpRequest;
use ByJG\Serializer\Serialize;
use Exception;
use RestReferenceArchitecture\Psr11;

Expand All @@ -21,7 +22,7 @@ public static function validateRequest(HttpRequest $request)
$bodyRequestDef = $schema->getRequestParameters($path, $method);

// Validate the request body (payload)
if (str_contains($request->getHeader('Content-Type'), 'multipart/')) {
if (str_contains($request->getHeader('Content-Type') ?? "", 'multipart/')) {
$requestBody = $request->post();
$files = $request->uploadedFiles()->getKeys();
$requestBody = array_merge($requestBody, array_combine($files, $files));
Expand All @@ -35,6 +36,6 @@ public static function validateRequest(HttpRequest $request)
throw new Error400Exception(explode("\n", $ex->getMessage())[0]);
}

return $requestBody;
return Serialize::from($requestBody)->withDoNotParseNullValues()->toArray();
}
}
}
2 changes: 1 addition & 1 deletion templates/codegen/test.php.jinja
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

namespace Test\Functional\Rest;
namespace Test\Rest;

use ByJG\RestServer\Exception\Error401Exception;
use ByJG\RestServer\Exception\Error403Exception;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?php


namespace Test\Functional\Rest;
namespace Test\Rest;

use ByJG\ApiTools\ApiTestCase;
use ByJG\ApiTools\Base\Schema;
Expand All @@ -16,7 +16,7 @@ class BaseApiTestCase extends ApiTestCase
{
protected static bool $databaseReset = false;

protected string $filePath = __DIR__ . '/../../../public/docs/openapi.json';
protected string $filePath = __DIR__ . '/../../public/docs/openapi.json';

protected function setUp(): void
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

namespace Test\Functional\Rest;
namespace Test\Rest;

use ByJG\Util\Uri;
use ByJG\WebRequest\Psr7\Request;
Expand Down
Loading

0 comments on commit 7ba0095

Please sign in to comment.