Skip to content

Commit d0376ce

Browse files
committed
Add RedBeanPHP for storing users into the DB
1 parent d75cdc1 commit d0376ce

File tree

7 files changed

+191
-20
lines changed

7 files changed

+191
-20
lines changed

src/Dal/UserDal.php

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,30 @@
22

33
namespace PH7\ApiSimpleMenu\Dal;
44

5-
use RedBeanPHP\SimpleModel;
5+
use PH7\ApiSimpleMenu\Entity\User as UserEntity;
6+
use RedBeanPHP\R;
67

7-
class UserDal extends SimpleModel
8+
final class UserDal
89
{
10+
public const TABLE_NAME = 'users';
911

12+
/**
13+
* @throws \RedBeanPHP\RedException\SQL
14+
*/
15+
public static function create(UserEntity $userEntity): int|string
16+
{
17+
$userBean = R::dispense(self::TABLE_NAME);
18+
$userBean->user_uuid = $userEntity->getUserUuid();
19+
$userBean->first_name = $userEntity->getFirstName();
20+
$userBean->last_name = $userEntity->getLastName();
21+
$userBean->email = $userEntity->getEmail();
22+
$userBean->phone = $userEntity->getPhone();
23+
$userBean->created_date = $userEntity->getCreationDate();
24+
25+
$id = R::store($userBean);
26+
27+
R::close();
28+
29+
return $id;
30+
}
1031
}

src/Entity/User.php

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
<?php
2+
namespace PH7\ApiSimpleMenu\Entity;
3+
4+
class User
5+
{
6+
private string $userUuid;
7+
8+
private string $firstName;
9+
10+
private string $lastName;
11+
12+
private string $email;
13+
14+
private string $phone;
15+
16+
private string $password;
17+
18+
private string $creationDate;
19+
20+
public function setUserUuid(string $userUuid) :self
21+
{
22+
$this->userUuid = $userUuid;
23+
24+
return $this;
25+
}
26+
27+
public function getUserUuid(): string
28+
{
29+
return $this->userUuid;
30+
}
31+
32+
public function setFirstName(string $firstName): self
33+
{
34+
$this->firstName = $firstName;
35+
36+
return $this;
37+
}
38+
39+
public function getFirstName(): string
40+
{
41+
return $this->firstName;
42+
}
43+
44+
public function setLastName(string $lastName): self
45+
{
46+
$this->lastName = $lastName;
47+
48+
return $this;
49+
}
50+
51+
public function getLastName(): string
52+
{
53+
return $this->lastName;
54+
}
55+
56+
public function setEmail(string $email): self
57+
{
58+
$this->email = $email;
59+
60+
return $this;
61+
}
62+
63+
public function getEmail(): string
64+
{
65+
return $this->email;
66+
}
67+
68+
public function setPhone(string $phone): self
69+
{
70+
$this->phone = $phone;
71+
72+
return $this;
73+
}
74+
75+
public function getPhone(): string
76+
{
77+
return $this->phone;
78+
}
79+
80+
public function setPassword(string $password): self
81+
{
82+
$this->password = $password;
83+
84+
return $this;
85+
}
86+
87+
public function getPassword(): string
88+
{
89+
return $this->password;
90+
}
91+
92+
public function setCreationDate(string $creationDate): self
93+
{
94+
$this->creationDate = $creationDate;
95+
96+
return $this;
97+
}
98+
99+
public function getCreationDate(): string
100+
{
101+
return $this->creationDate;
102+
}
103+
}
Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,19 @@
11
<?php
2-
namespace PH7\ApiSimpleMenu;
2+
namespace PH7\ApiSimpleMenu\Service;
33

4+
use PH7\ApiSimpleMenu\Dal\UserDal;
45
use PH7\ApiSimpleMenu\Validation\Exception\InvalidValidationException;
56
use PH7\ApiSimpleMenu\Validation\UserValidation;
7+
use PH7\JustHttp\StatusCode;
8+
use PH7\PhpHttpResponseHeader\Http;
69
use Ramsey\Uuid\Uuid;
10+
use RedBeanPHP\RedException\SQL;
711
use Respect\Validation\Validator as v;
12+
use PH7\ApiSimpleMenu\Entity\User as UserEntity;
813

914
class User
1015
{
11-
public readonly ?string $userId;
16+
public const DATE_TIME_FORMAT = 'Y-m-d H:i:s';
1217

1318
public function __construct(
1419
public readonly string $name,
@@ -22,7 +27,26 @@ public function create(mixed $data): object
2227
// validate data
2328
$userValidation = new UserValidation($data);
2429
if ($userValidation->isCreationSchemaValid()) {
25-
$data->userId = Uuid::uuid4(); // assigning a UUID to the user
30+
$userUuid = Uuid::uuid4(); // assigning a UUID to the user
31+
32+
$userEntity = new UserEntity();
33+
$userEntity
34+
->setUserUuid($userUuid)
35+
->setFirstName($data->first)
36+
->setLastName($data->last)
37+
->setEmail($data->email)
38+
->setPhone($data->phone)
39+
->setCreationDate(date(self::DATE_TIME_FORMAT));
40+
41+
try {
42+
UserDal::create($userEntity);
43+
} catch (SQL $exception) {
44+
// Set an internal error when we cannot add an entry to the database
45+
Http::setHeadersByCode(StatusCode::INTERNAL_SERVER_ERROR);
46+
47+
// Set to empty result, because an issue happened. The client has to handle this properly
48+
$data = [];
49+
}
2650

2751
return $data; // return statement exists the function and doesn't go beyond this scope
2852
}
@@ -38,7 +62,7 @@ public function retrieveAll(): array
3862
public function retrieve(string $userId): self
3963
{
4064
if (v::uuid()->validate($userId)) {
41-
$this->userId = $userId;
65+
// TODO To be implemented
4266

4367
return $this;
4468
}
@@ -60,7 +84,7 @@ public function update(mixed $postBody): object
6084
public function remove(string $userId): bool
6185
{
6286
if (v::uuid()->validate($userId)) {
63-
$this->userId = $userId;
87+
// TODO To be implemented
6488
} else {
6589
throw new InvalidValidationException("Invalid user UUID");
6690
}

src/Validation/UserValidation.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ public function __construct(private mixed $data) {}
1515
public function isCreationSchemaValid(): bool
1616
{
1717
// validation schema
18-
$schemaValidation = v::attribute('first', v::stringType()->length(self::MINIMUM_NAME_LENGTH, self::MAXIMUM_NAME_LENGTH))
18+
$schemaValidation =
19+
v::attribute('first', v::stringType()->length(self::MINIMUM_NAME_LENGTH, self::MAXIMUM_NAME_LENGTH))
1920
->attribute('last', v::stringType()->length(self::MINIMUM_NAME_LENGTH, self::MAXIMUM_NAME_LENGTH))
2021
->attribute('email', v::email(), mandatory: false)
2122
->attribute('phone', v::phone(), mandatory: false);

src/config/config.inc.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,20 @@
33

44
use Dotenv\Dotenv;
55

6+
enum Environment : string
7+
{
8+
case DEVELOPMENT = 'development';
9+
case PRODUCTION = 'production';
10+
11+
public function environmentName(): string
12+
{
13+
return match($this) {
14+
self::DEVELOPMENT => 'development',
15+
self::PRODUCTION => 'production'
16+
};
17+
}
18+
}
19+
620
$path = dirname(__DIR__, 2);
721
$dotenv = Dotenv::createImmutable($path);
822
$dotenv->load();

src/config/database.inc.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,10 @@
66
// setup RedBean
77
$dsn = sprintf('mysql:host=%s;dbname=%s', $_ENV['DB_HOST'], $_ENV['DB_NAME']);
88
R::setup($dsn, $_ENV['DB_USER'], $_ENV['DB_PASS']);
9+
10+
// Freeze RedBean on production
11+
$currentEnvironment = Environment::tryFrom($_ENV['ENVIRONMENT']);
12+
if ($currentEnvironment?->environmentName() !== Environment::DEVELOPMENT->value) {
13+
echo 'RedBean Frozen';
14+
R::freeze();
15+
}

src/routes/user.routes.php

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
<?php
22
namespace PH7\ApiSimpleMenu;
33

4+
use PH7\ApiSimpleMenu\Service\User;
45
use PH7\ApiSimpleMenu\Validation\Exception\InvalidValidationException;
56

67
use PH7\JustHttp\StatusCode;
78
use PH7\PhpHttpResponseHeader\Http;
89

9-
require_once dirname(__DIR__) . '/endpoints/User.php';
10+
require_once dirname(__DIR__) . '/Service/User.php';
1011

1112
// PHP 8.1 enums
1213
enum UserAction: string
@@ -31,18 +32,18 @@ public function getResponse(): string
3132
try {
3233
$response = match ($this) {
3334
self::CREATE => $user->create($postBody),
34-
self::RETRIEVE_ALL => $user->retrieveAll(),
35-
self::RETRIEVE => $user->retrieve($userId),
36-
self::REMOVE => $user->remove($userId),
37-
self::UPDATE => $user->update($postBody),
38-
};
39-
} catch (InvalidValidationException $e) {
40-
// Send 400 http status code
41-
Http::setHeadersByCode(StatusCode::BAD_REQUEST);
35+
self::RETRIEVE_ALL => $user->retrieveAll(),
36+
self::RETRIEVE => $user->retrieve($userId),
37+
self::REMOVE => $user->remove($userId),
38+
self::UPDATE => $user->update($postBody),
39+
};
40+
} catch (InvalidValidationException $e) {
41+
// Send 400 http status code
42+
Http::setHeadersByCode(StatusCode::BAD_REQUEST);
4243

43-
$response = [
44-
'errors' => [
45-
'message' => $e->getMessage(),
44+
$response = [
45+
'errors' => [
46+
'message' => $e->getMessage(),
4647
'code' => $e->getCode()
4748
]
4849
];

0 commit comments

Comments
 (0)