Skip to content

Commit

Permalink
More updates on code
Browse files Browse the repository at this point in the history
  • Loading branch information
byjg committed Sep 15, 2023
1 parent 420a0f8 commit 864c2dc
Show file tree
Hide file tree
Showing 17 changed files with 204 additions and 112 deletions.
4 changes: 3 additions & 1 deletion builder/PostCreateScript.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,13 +121,15 @@ public static function run(Event $event)
$workdir = realpath(__DIR__ . '/..');
$stdIo = $event->getIO();

$currentPhpVersion = PHP_MAJOR_VERSION . "." .PHP_MINOR_VERSION;

$stdIo->write("========================================================");
$stdIo->write(" Setup Project");
$stdIo->write(" Answer the questions below");
$stdIo->write("========================================================");
$stdIo->write("");
$stdIo->write("Project Directory: " . $workdir);
$phpVersion = $stdIo->ask('PHP Version [7.4]: ', '7.4');
$phpVersion = $stdIo->ask("PHP Version [$currentPhpVersion]: ", $currentPhpVersion);
$namespace = $stdIo->ask('Project namespace [MyRest]: ', 'MyRest');
$composerName = $stdIo->ask('Composer name [me/myrest]: ', 'me/myrest');
$mysqlConnection = $stdIo->ask('MySQL connection DEV [mysql://root:mysqlp455w0rd@mysql-container/mydb]: ', 'mysql://root:mysqlp455w0rd@mysql-container/mydb');
Expand Down
15 changes: 11 additions & 4 deletions builder/Scripts.php
Original file line number Diff line number Diff line change
Expand Up @@ -280,26 +280,33 @@ public function runCodeGenerator(array $arguments)
$nullableFields = [];
foreach ($tableDefinition as $field) {
if ($field['null'] == 'YES') {
$nullableFields[] = $field["field"];
$nullableFields[] = $field["property"];
}
}

// Create an array only with primary keys
$primaryKeys = [];
foreach ($tableDefinition as $field) {
if ($field['key'] == 'PRI') {
$primaryKeys[] = $field["field"];
$primaryKeys[] = $field["property"];
}
}

// Create an array with non-nullable fields but primary keys
// Create an array with non nullable fields but primary keys
$nonNullableFields = [];
foreach ($tableDefinition as $field) {
if ($field['null'] == 'NO' && $field['key'] != 'PRI') {
$nonNullableFields[] = $field["field"];
$nonNullableFields[] = $field["property"];
}
}

// Create an array with non nullable fields but primary keys
foreach ($tableIndexes as $key => $field) {
$tableIndexes[$key]['camelColumnName'] = preg_replace_callback('/_(.?)/', function($match) {
return strtoupper($match[1]);
}, $field['column_name']);
}

$data = [
'namespace' => 'RestTemplate',
'restTag' => ucwords(explode('_', strtolower($table))[0]),
Expand Down
2 changes: 2 additions & 0 deletions db/base.sql
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ create table dummy (
field varchar(10) not null
);

create index ix_field on dummy(field);

insert into dummy (field) values ('fld value');
insert into dummy (field) values ('Test 1');
insert into dummy (field) values ('Test 2');
Expand Down
2 changes: 1 addition & 1 deletion docker/fpm/php/custom.ini
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ upload_max_filesize = 40M

; Must be greater than or equal to upload_max_filesize
post_max_size = 40M
memory_limit = 128M
memory_limit = 192M
59 changes: 57 additions & 2 deletions src/Model/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,72 @@
#[OA\Schema(required: ["email"], type: "object", xml: new \OpenApi\Attributes\Xml(name: "User"))]
class User extends UserModel
{
// Property Fields
const PROP_RESETTOKENEXPIRE = 'resettokenexpire';
const PROP_RESETTOKEN = 'resettoken';
const PROP_RESETCODE = 'resetcode';
const PROP_RESETALLOWED = 'resetallowed';

// Property Values
const VALUE_YES = 'yes';
const VALUE_NO = 'no';

// Roles
const ROLE_ADMIN = 'admin';
const ROLE_USER = 'user';

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

/**
* @var ?string
*/
#[OA\Property(type: "string", format: "string")]
protected $name;

/**
* @var ?string
*/
#[OA\Property(type: "string", format: "string")]
protected $email;

/**
* @var ?string
*/
#[OA\Property(type: "string", format: "string")]
protected ?string $updated = null;
protected $username;
/**
* @var ?string
*/
#[OA\Property(type: "string", format: "string")]
protected $password;

/**
* @var ?string
*/
#[OA\Property(type: "string", format: "string")]
protected $created;

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

/**
* @var ?string
*/
#[OA\Property(type: "string", format: "string")]
protected $admin = "no";

/**
* @OA\Property()
* @var ?string
*/
protected $uuid;

/**
* User constructor.
Expand Down
31 changes: 22 additions & 9 deletions src/Repository/BaseRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -142,13 +142,13 @@ public static function getUuid()

/**
* @param Mapper $mapper
* @param string $pkFieldName
* @param string $modelField
* @return void
* @param string $binPropertyName
* @param string $uuidStrPropertyName
* @return FieldMapping
*/
protected function setClosureFixBinaryUUID(Mapper $mapper, string $pkFieldName = 'id', string $modelField = 'uuid')
protected function setClosureFixBinaryUUID(?Mapper $mapper, $binPropertyName = 'id', $uuidStrPropertyName = 'uuid')
{
$mapper->addFieldMapping(FieldMapping::create($pkFieldName)
$fieldMapping = FieldMapping::create($binPropertyName)
->withUpdateFunction(function ($value, $instance) {
if (empty($value)) {
return null;
Expand All @@ -158,10 +158,23 @@ protected function setClosureFixBinaryUUID(Mapper $mapper, string $pkFieldName =
}
return $value;
})
->withSelectFunction(function ($value, $instance) use ($modelField) {
return str_replace('-', '', $instance->{'get' . $modelField}());
})
);
->withSelectFunction(function ($value, $instance) use ($binPropertyName, $uuidStrPropertyName) {
if (!empty($uuidStrPropertyName)) {
$fieldValue = $instance->{'get' . $uuidStrPropertyName}();
} else {
$fieldValue = HexUuidLiteral::getFormattedUuid($instance->{'get' . $binPropertyName}(), false);
}
if (is_null($fieldValue)) {
return null;
}
return $fieldValue;
});

if (!empty($mapper)) {
$mapper->addFieldMapping($fieldMapping);
}

return $fieldMapping;
}

/**
Expand Down
16 changes: 6 additions & 10 deletions src/Repository/DummyRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@

namespace RestTemplate\Repository;

use RestTemplate\Psr11;
use ByJG\AnyDataset\Db\DbDriverInterface;
use ByJG\MicroOrm\FieldMapping;
use ByJG\MicroOrm\Mapper;
use ByJG\MicroOrm\Query;
use ByJG\MicroOrm\Repository;
use ByJG\Serializer\Exception\InvalidArgumentException;
use RestTemplate\Model\Dummy;

class DummyRepository extends BaseRepository
Expand Down Expand Up @@ -36,22 +37,17 @@ public function __construct(DbDriverInterface $dbDriver)
$this->repository = new Repository($dbDriver, $mapper);
}


/**
* @param $field string
* @param mixed $field
* @return null|Dummy[]
* @throws \ByJG\MicroOrm\Exception\InvalidArgumentException
* @throws InvalidArgumentException
*/
public function getByField(string $field): ?array
public function getByField($field)
{
$query = Query::getInstance()
->table('dummy')
->where('dummy.field like :field', ['field' => "%$field%"]);

->where('dummy.field = :value', ['value' => $field]);
$result = $this->repository->getByQuery($query);
if (is_null($result)) {
return null;
}
return $result;
}

Expand Down
13 changes: 7 additions & 6 deletions src/Rest/DummyHexRest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use RestTemplate\Model\DummyHex;
use RestTemplate\Psr11;
use RestTemplate\Repository\DummyHexRepository;
use RestTemplate\Model\User;

class DummyHexRest extends ServiceAbstractBase
{
Expand Down Expand Up @@ -63,7 +64,7 @@ class DummyHexRest extends ServiceAbstractBase
description: "The object DummyHex",
content: new OA\JsonContent(ref: "#/components/schemas/DummyHex")
)]
public function getDummyHex(HttpResponse $response, HttpRequest $request)
public function getDummyHex(HttpResponse $response, HttpRequest $request): void
{
$data = $this->requireAuthenticated();

Expand Down Expand Up @@ -149,7 +150,7 @@ public function getDummyHex(HttpResponse $response, HttpRequest $request)
description: "Not Authorized",
content: new OA\JsonContent(ref: "#/components/schemas/error")
)]
public function listDummyHex(HttpResponse $response, HttpRequest $request)
public function listDummyHex(HttpResponse $response, HttpRequest $request): void
{
$data = $this->requireAuthenticated();

Expand Down Expand Up @@ -222,9 +223,9 @@ public function listDummyHex(HttpResponse $response, HttpRequest $request)
description: "Not Authorized",
content: new OA\JsonContent(ref: "#/components/schemas/error")
)]
public function postDummyHex(HttpResponse $response, HttpRequest $request)
public function postDummyHex(HttpResponse $response, HttpRequest $request): void
{
$data = $this->requireRole("admin");
$data = $this->requireRole(User::ROLE_ADMIN);

$payload = $this->validateRequest($request);

Expand Down Expand Up @@ -281,9 +282,9 @@ public function postDummyHex(HttpResponse $response, HttpRequest $request)
description: "Not Authorized",
content: new OA\JsonContent(ref: "#/components/schemas/error")
)]
public function putDummyHex(HttpResponse $response, HttpRequest $request)
public function putDummyHex(HttpResponse $response, HttpRequest $request): void
{
$data = $this->requireRole("admin");
$data = $this->requireRole(User::ROLE_ADMIN);

$payload = $this->validateRequest($request);

Expand Down
15 changes: 8 additions & 7 deletions src/Rest/DummyRest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use RestTemplate\Model\Dummy;
use RestTemplate\Psr11;
use RestTemplate\Repository\DummyRepository;
use RestTemplate\Model\User;

class DummyRest extends ServiceAbstractBase
{
Expand Down Expand Up @@ -63,7 +64,7 @@ class DummyRest extends ServiceAbstractBase
description: "The object Dummy",
content: new OA\JsonContent(ref: "#/components/schemas/Dummy")
)]
public function getDummy(HttpResponse $response, HttpRequest $request)
public function getDummy(HttpResponse $response, HttpRequest $request): void
{
$data = $this->requireAuthenticated();

Expand Down Expand Up @@ -149,7 +150,7 @@ public function getDummy(HttpResponse $response, HttpRequest $request)
description: "Not Authorized",
content: new OA\JsonContent(ref: "#/components/schemas/error")
)]
public function listDummy(HttpResponse $response, HttpRequest $request)
public function listDummy(HttpResponse $response, HttpRequest $request): void
{
$data = $this->requireAuthenticated();

Expand Down Expand Up @@ -196,7 +197,7 @@ public function listDummy(HttpResponse $response, HttpRequest $request)
tags: ["Dummy"]
)]
#[OA\RequestBody(
description: "The object DummyHex to be created",
description: "The object Dummy to be created",
required: true,
content: new OA\JsonContent(
required: [ "field" ],
Expand All @@ -222,9 +223,9 @@ public function listDummy(HttpResponse $response, HttpRequest $request)
description: "Not Authorized",
content: new OA\JsonContent(ref: "#/components/schemas/error")
)]
public function postDummy(HttpResponse $response, HttpRequest $request)
public function postDummy(HttpResponse $response, HttpRequest $request): void
{
$data = $this->requireRole("admin");
$data = $this->requireRole(User::ROLE_ADMIN);

$payload = $this->validateRequest($request);

Expand Down Expand Up @@ -281,9 +282,9 @@ public function postDummy(HttpResponse $response, HttpRequest $request)
description: "Not Authorized",
content: new OA\JsonContent(ref: "#/components/schemas/error")
)]
public function putDummy(HttpResponse $response, HttpRequest $request)
public function putDummy(HttpResponse $response, HttpRequest $request): void
{
$data = $this->requireRole("admin");
$data = $this->requireRole(User::ROLE_ADMIN);

$payload = $this->validateRequest($request);

Expand Down
20 changes: 0 additions & 20 deletions src/Rest/Login.php
Original file line number Diff line number Diff line change
Expand Up @@ -354,24 +354,4 @@ public function postResetPassword(HttpResponse $response, HttpRequest $request)

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



/**
* @param User|null $user
* @return array
* @throws Error401Exception
*/
private function createUserMetadata(?User $user): array
{
if (is_null($user)) {
throw new Error401Exception('Username or password is invalid');
}

return [
'role' => ($user->getAdmin() === 'yes' ? 'admin' : 'user'),
'userid' => $user->getUserid(),
'name' => $user->getName()
];
}
}
Loading

0 comments on commit 864c2dc

Please sign in to comment.