Skip to content

Commit 6b87720

Browse files
add monolog services and clean some vars names
1 parent 0b75f00 commit 6b87720

29 files changed

+230
-83
lines changed

.env.example

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,5 @@ SECRET_KEY='YourSuperSecret-KeY'
99

1010
REDIS_ENABLED=false
1111
REDIS_URL=''
12+
13+
LOGS_ENABLED=false

.scrutinizer.yml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,12 @@ build:
2020
DB_DATABASE: 'rest_api_slim_php'
2121
DB_USERNAME: 'root'
2222
DB_PASSWORD: ''
23-
DISPLAY_ERROR_DETAILS: true
23+
DISPLAY_ERROR_DETAILS: true
2424
APP_DOMAIN: 'https://rest-api-slim-php-sql.herokuapp.com'
2525
SECRET_KEY: 'YourSuperSecret-KeY'
2626
REDIS_ENABLED: true
2727
REDIS_URL: 'localhost'
28+
LOGS_ENABLED: true
2829
php:
2930
version: 7.4
3031
project_setup:

.travis.yml

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
language: php
22

33
php:
4-
- '7.3'
5-
- '7.4'
4+
- "7.3"
5+
- "7.4"
66

77
services:
88
- mysql
@@ -20,15 +20,16 @@ env:
2020
- SECRET_KEY=YourSuperSecret-KeY
2121
- REDIS_ENABLED=true
2222
- REDIS_URL=localhost
23+
- LOGS_ENABLED=true
2324

2425
before_install:
2526
- mysql -e 'CREATE DATABASE rest_api_slim_php;'
2627

2728
before_script:
2829
- mysql rest_api_slim_php < database/database.sql
2930
- composer install
30-
- curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
31-
- chmod +x ./cc-test-reporter
31+
- curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
32+
- chmod +x ./cc-test-reporter
3233
- ./cc-test-reporter before-build
3334

3435
script:

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
[![Quality gate](https://sonarcloud.io/api/project_badges/quality_gate?project=FernandoCalmet_rest-api-slim-php)](https://sonarcloud.io/dashboard?id=FernandoCalmet_rest-api-slim-php)
1111

12-
Principales tecnologías utilizadas: `PHP 7, Slim 3, MySQL, Redis, dotenv, PHPUnit y JSON Web Tokens.`
12+
Principales tecnologías utilizadas: `PHP 7, Slim 3, MySQL, Monolog, Redis, dotenv, PHPUnit y JSON Web Tokens.`
1313

1414
Además, se utilizo otras herramientas adicionales como: `Docker & Docker Compose, Travis CI, Swagger, Scrutinizer, Sonar Cloud, PHPStan, PHP Insights, Heroku and CORS.`
1515

@@ -107,6 +107,7 @@ composer restart-db
107107
- [vlucas/phpdotenv](https://github.com/vlucas/phpdotenv): Carga variables de entorno desde `.env` a `getenv()`,`$ _ENV` y `$ _SERVER` automágicamente.
108108
- [predis/predis](https://github.com/nrk/predis/): Cliente Redis flexible y con todas las funciones para PHP y HHVM.
109109
- [firebase/php-jwt](https://github.com/firebase/php-jwt): Una biblioteca simple para codificar y decodificar JSON Web Tokens (JWT) en PHP.
110+
- [monolog/monolog](https://github.com/Seldaek/monolog): Monolog envía sus registros a archivos, sockets, bandejas de entrada, bases de datos y varios servicios web. Consulte la lista completa de controladores a continuación. Los controladores especiales le permiten crear estrategias de registro avanzadas.
110111

111112
### LISTA DE DEPENDENCIAS DE DESARROLLO
112113

extras/bin/restart-db.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
$username = $db['username'];
1212
$password = $db['password'];
1313

14-
$pdo = new PDO("mysql:host=${hostname}", $username, $password);
14+
$pdo = new PDO("mysql:host=${hostname};charset=utf8", $username, $password);
1515
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
1616

1717
$pdo->exec("DROP DATABASE IF EXISTS ${database}");

src/App/Dependencies.php

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@
33
declare(strict_types=1);
44

55
use App\Handler\ApiError;
6+
use App\Service\LoggerService;
67
use App\Service\RedisService;
78
use Psr\Container\ContainerInterface;
89

910
$container['db'] = static function (ContainerInterface $container): PDO {
1011
$db = $container->get('settings')['db'];
11-
$dsn = sprintf('mysql:host=%s;dbname=%s', $db['hostname'], $db['database']);
12+
$dsn = sprintf('mysql:host=%s;dbname=%s;charset=utf8', $db['hostname'], $db['database']);
1213
$pdo = new PDO($dsn, $db['username'], $db['password']);
1314
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
1415
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
@@ -27,11 +28,12 @@
2728
return new RedisService(new \Predis\Client($redis['url']));
2829
};
2930

30-
$container['logger'] = static function ($container) {
31-
$channel = $container->get('settings')['log']['channel'];
32-
$path = $container->get('settings')['log']['path'];
31+
$container['logger_service'] = static function ($container): LoggerService {
32+
$channel = $container->get('settings')['logger']['channel'];
33+
$path = $container->get('settings')['logger']['path'];
3334
$logger = new \Monolog\Logger($channel);
3435
$file_handler = new \Monolog\Handler\StreamHandler($path . date('Ymd') . '.log');
3536
$logger->pushHandler($file_handler);
36-
return $logger;
37+
38+
return new LoggerService($logger);
3739
};

src/App/Routes.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
use App\Controller\User;
88
use App\Middleware\Auth;
99

10+
/** @var \Slim\App $app */
11+
1012
$app->get('/', 'App\Controller\DefaultController:getHelp');
1113
$app->get('/status', 'App\Controller\DefaultController:getStatus');
1214
$app->post('/login', \App\Controller\User\Login::class);

src/App/Services.php

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
): User\Find {
1313
return new User\Find(
1414
$container->get('user_repository'),
15-
$container->get('redis_service')
15+
$container->get('redis_service'),
16+
$container->get('logger_service')
1617
);
1718
};
1819

@@ -21,7 +22,8 @@
2122
): User\Create {
2223
return new User\Create(
2324
$container->get('user_repository'),
24-
$container->get('redis_service')
25+
$container->get('redis_service'),
26+
$container->get('logger_service')
2527
);
2628
};
2729

@@ -30,7 +32,8 @@
3032
): User\Update {
3133
return new User\Update(
3234
$container->get('user_repository'),
33-
$container->get('redis_service')
35+
$container->get('redis_service'),
36+
$container->get('logger_service')
3437
);
3538
};
3639

@@ -39,7 +42,8 @@
3942
): User\Delete {
4043
return new User\Delete(
4144
$container->get('user_repository'),
42-
$container->get('redis_service')
45+
$container->get('redis_service'),
46+
$container->get('logger_service')
4347
);
4448
};
4549

@@ -48,7 +52,8 @@
4852
): User\Login {
4953
return new User\Login(
5054
$container->get('user_repository'),
51-
$container->get('redis_service')
55+
$container->get('redis_service'),
56+
$container->get('logger_service')
5257
);
5358
};
5459

@@ -57,7 +62,8 @@
5762
): Task\Find {
5863
return new Task\Find(
5964
$container->get('task_repository'),
60-
$container->get('redis_service')
65+
$container->get('redis_service'),
66+
$container->get('logger_service')
6167
);
6268
};
6369

@@ -66,7 +72,8 @@
6672
): Task\Create {
6773
return new Task\Create(
6874
$container->get('task_repository'),
69-
$container->get('redis_service')
75+
$container->get('redis_service'),
76+
$container->get('logger_service')
7077
);
7178
};
7279

@@ -75,7 +82,8 @@
7582
): Task\Update {
7683
return new Task\Update(
7784
$container->get('task_repository'),
78-
$container->get('redis_service')
85+
$container->get('redis_service'),
86+
$container->get('logger_service')
7987
);
8088
};
8189

@@ -84,7 +92,8 @@
8492
): Task\Delete {
8593
return new Task\Delete(
8694
$container->get('task_repository'),
87-
$container->get('redis_service')
95+
$container->get('redis_service'),
96+
$container->get('logger_service')
8897
);
8998
};
9099

@@ -93,7 +102,8 @@
93102
): Note\Find {
94103
return new Note\Find(
95104
$container->get('note_repository'),
96-
$container->get('redis_service')
105+
$container->get('redis_service'),
106+
$container->get('logger_service')
97107
);
98108
};
99109

@@ -102,7 +112,8 @@
102112
): Note\Create {
103113
return new Note\Create(
104114
$container->get('note_repository'),
105-
$container->get('redis_service')
115+
$container->get('redis_service'),
116+
$container->get('logger_service')
106117
);
107118
};
108119

@@ -111,7 +122,8 @@
111122
): Note\Update {
112123
return new Note\Update(
113124
$container->get('note_repository'),
114-
$container->get('redis_service')
125+
$container->get('redis_service'),
126+
$container->get('logger_service')
115127
);
116128
};
117129

@@ -120,6 +132,7 @@
120132
): Note\Delete {
121133
return new Note\Delete(
122134
$container->get('note_repository'),
123-
$container->get('redis_service')
135+
$container->get('redis_service'),
136+
$container->get('logger_service')
124137
);
125138
};

src/App/Settings.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
'enabled' => $_SERVER['REDIS_ENABLED'],
1616
'url' => $_SERVER['REDIS_URL'],
1717
],
18-
'log' => [
18+
'logger' => [
19+
'enabled' => $_SERVER['LOGS_ENABLED'],
1920
'path' => 'logs/',
2021
'channel' => 'channel_api'
2122
],

src/Controller/BaseController.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,9 @@ protected static function isRedisEnabled(): bool
3939
{
4040
return filter_var($_SERVER['REDIS_ENABLED'], FILTER_VALIDATE_BOOLEAN);
4141
}
42+
43+
protected static function isLoggerEnabled(): bool
44+
{
45+
return filter_var($_SERVER['LOGS_ENABLED'], FILTER_VALIDATE_BOOLEAN);
46+
}
4247
}

src/Controller/DefaultController.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
final class DefaultController extends BaseController
1111
{
12-
public const API_VERSION = '1.5.0';
12+
public const API_VERSION = '1.6.0';
1313

1414
public function getHelp(Request $request, Response $response): Response
1515
{
@@ -38,6 +38,7 @@ public function getStatus(Request $request, Response $response): Response
3838
'stats' => $this->getDbStats(),
3939
'MySQL' => 'OK',
4040
'Redis' => $this->checkRedisConnection(),
41+
'Logger' => $this->checkLoggerConnection(),
4142
'version' => self::API_VERSION,
4243
'timestamp' => time(),
4344
];
@@ -70,4 +71,14 @@ private function checkRedisConnection(): string
7071

7172
return $redis;
7273
}
74+
75+
private function checkLoggerConnection(): string
76+
{
77+
$logger = 'Disabled';
78+
if (self::isLoggerEnabled() === true){
79+
$logger = 'Enabled';
80+
}
81+
82+
return $logger;
83+
}
7384
}

src/Repository/NoteRepository.php

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,17 @@
55
namespace App\Repository;
66

77
use App\Exception\NoteException;
8+
use App\Entity\Note;
89

910
final class NoteRepository extends BaseRepository
1011
{
11-
public function checkAndGetNote(int $noteId): \App\Entity\Note
12+
public function checkAndGetNote(int $noteId): Note
1213
{
1314
$query = 'SELECT * FROM `notes` WHERE `id` = :id';
1415
$statement = $this->getDb()->prepare($query);
1516
$statement->bindParam('id', $noteId);
1617
$statement->execute();
17-
$note = $statement->fetchObject(\App\Entity\Note::class);
18+
$note = $statement->fetchObject(Note::class);
1819
if (!$note) {
1920
throw new NoteException('Note not found.', 404);
2021
}
@@ -91,7 +92,7 @@ public function searchNotes(string $strNotes): array
9192
return $notes;
9293
}
9394

94-
public function createNote(\App\Entity\Note $note): \App\Entity\Note
95+
public function createNote(Note $note): Note
9596
{
9697
$query = '
9798
INSERT INTO `notes`
@@ -111,7 +112,7 @@ public function createNote(\App\Entity\Note $note): \App\Entity\Note
111112
return $this->checkAndGetNote((int) $this->getDb()->lastInsertId());
112113
}
113114

114-
public function updateNote(\App\Entity\Note $note): \App\Entity\Note
115+
public function updateNote(Note $note): Note
115116
{
116117
$query = '
117118
UPDATE `notes`

src/Repository/TaskRepository.php

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@
55
namespace App\Repository;
66

77
use App\Exception\TaskException;
8+
use App\Entity\Task;
89

910
final class TaskRepository extends BaseRepository
1011
{
11-
public function checkAndGetTask(int $taskId, int $userId): \App\Entity\Task
12+
public function checkAndGetTask(int $taskId, int $userId): Task
1213
{
1314
$query = '
1415
SELECT * FROM `tasks`
@@ -18,7 +19,7 @@ public function checkAndGetTask(int $taskId, int $userId): \App\Entity\Task
1819
$statement->bindParam('id', $taskId);
1920
$statement->bindParam('userId', $userId);
2021
$statement->execute();
21-
$task = $statement->fetchObject(\App\Entity\Task::class);
22+
$task = $statement->fetchObject(Task::class);
2223
if (!$task) {
2324
throw new TaskException('Task not found.', 404);
2425
}
@@ -124,7 +125,7 @@ public function searchTasks(string $tasksName, int $userId, ?int $status): array
124125
return $tasks;
125126
}
126127

127-
public function createTask(\App\Entity\Task $task): \App\Entity\Task
128+
public function createTask(Task $task): Task
128129
{
129130
$query = '
130131
INSERT INTO `tasks`
@@ -150,7 +151,7 @@ public function createTask(\App\Entity\Task $task): \App\Entity\Task
150151
return $this->checkAndGetTask((int) $taskId, (int) $userId);
151152
}
152153

153-
public function updateTask(\App\Entity\Task $task): \App\Entity\Task
154+
public function updateTask(Task $task): Task
154155
{
155156
$query = '
156157
UPDATE `tasks`

0 commit comments

Comments
 (0)