Skip to content

Commit

Permalink
add monolog services and clean some vars names
Browse files Browse the repository at this point in the history
  • Loading branch information
FernandoCalmet committed Oct 1, 2020
1 parent 0b75f00 commit 6b87720
Show file tree
Hide file tree
Showing 29 changed files with 230 additions and 83 deletions.
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,5 @@ SECRET_KEY='YourSuperSecret-KeY'

REDIS_ENABLED=false
REDIS_URL=''

LOGS_ENABLED=false
3 changes: 2 additions & 1 deletion .scrutinizer.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@ build:
DB_DATABASE: 'rest_api_slim_php'
DB_USERNAME: 'root'
DB_PASSWORD: ''
DISPLAY_ERROR_DETAILS: true
DISPLAY_ERROR_DETAILS: true
APP_DOMAIN: 'https://rest-api-slim-php-sql.herokuapp.com'
SECRET_KEY: 'YourSuperSecret-KeY'
REDIS_ENABLED: true
REDIS_URL: 'localhost'
LOGS_ENABLED: true
php:
version: 7.4
project_setup:
Expand Down
9 changes: 5 additions & 4 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
language: php

php:
- '7.3'
- '7.4'
- "7.3"
- "7.4"

services:
- mysql
Expand All @@ -20,15 +20,16 @@ env:
- SECRET_KEY=YourSuperSecret-KeY
- REDIS_ENABLED=true
- REDIS_URL=localhost
- LOGS_ENABLED=true

before_install:
- mysql -e 'CREATE DATABASE rest_api_slim_php;'

before_script:
- mysql rest_api_slim_php < database/database.sql
- composer install
- curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
- chmod +x ./cc-test-reporter
- curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
- chmod +x ./cc-test-reporter
- ./cc-test-reporter before-build

script:
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

[![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)

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

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

Expand Down Expand Up @@ -107,6 +107,7 @@ composer restart-db
- [vlucas/phpdotenv](https://github.com/vlucas/phpdotenv): Carga variables de entorno desde `.env` a `getenv()`,`$ _ENV` y `$ _SERVER` automágicamente.
- [predis/predis](https://github.com/nrk/predis/): Cliente Redis flexible y con todas las funciones para PHP y HHVM.
- [firebase/php-jwt](https://github.com/firebase/php-jwt): Una biblioteca simple para codificar y decodificar JSON Web Tokens (JWT) en PHP.
- [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.

### LISTA DE DEPENDENCIAS DE DESARROLLO

Expand Down
2 changes: 1 addition & 1 deletion extras/bin/restart-db.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
$username = $db['username'];
$password = $db['password'];

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

$pdo->exec("DROP DATABASE IF EXISTS ${database}");
Expand Down
12 changes: 7 additions & 5 deletions src/App/Dependencies.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
declare(strict_types=1);

use App\Handler\ApiError;
use App\Service\LoggerService;
use App\Service\RedisService;
use Psr\Container\ContainerInterface;

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

$container['logger'] = static function ($container) {
$channel = $container->get('settings')['log']['channel'];
$path = $container->get('settings')['log']['path'];
$container['logger_service'] = static function ($container): LoggerService {
$channel = $container->get('settings')['logger']['channel'];
$path = $container->get('settings')['logger']['path'];
$logger = new \Monolog\Logger($channel);
$file_handler = new \Monolog\Handler\StreamHandler($path . date('Ymd') . '.log');
$logger->pushHandler($file_handler);
return $logger;

return new LoggerService($logger);
};
2 changes: 2 additions & 0 deletions src/App/Routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
use App\Controller\User;
use App\Middleware\Auth;

/** @var \Slim\App $app */

$app->get('/', 'App\Controller\DefaultController:getHelp');
$app->get('/status', 'App\Controller\DefaultController:getStatus');
$app->post('/login', \App\Controller\User\Login::class);
Expand Down
39 changes: 26 additions & 13 deletions src/App/Services.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
): User\Find {
return new User\Find(
$container->get('user_repository'),
$container->get('redis_service')
$container->get('redis_service'),
$container->get('logger_service')
);
};

Expand All @@ -21,7 +22,8 @@
): User\Create {
return new User\Create(
$container->get('user_repository'),
$container->get('redis_service')
$container->get('redis_service'),
$container->get('logger_service')
);
};

Expand All @@ -30,7 +32,8 @@
): User\Update {
return new User\Update(
$container->get('user_repository'),
$container->get('redis_service')
$container->get('redis_service'),
$container->get('logger_service')
);
};

Expand All @@ -39,7 +42,8 @@
): User\Delete {
return new User\Delete(
$container->get('user_repository'),
$container->get('redis_service')
$container->get('redis_service'),
$container->get('logger_service')
);
};

Expand All @@ -48,7 +52,8 @@
): User\Login {
return new User\Login(
$container->get('user_repository'),
$container->get('redis_service')
$container->get('redis_service'),
$container->get('logger_service')
);
};

Expand All @@ -57,7 +62,8 @@
): Task\Find {
return new Task\Find(
$container->get('task_repository'),
$container->get('redis_service')
$container->get('redis_service'),
$container->get('logger_service')
);
};

Expand All @@ -66,7 +72,8 @@
): Task\Create {
return new Task\Create(
$container->get('task_repository'),
$container->get('redis_service')
$container->get('redis_service'),
$container->get('logger_service')
);
};

Expand All @@ -75,7 +82,8 @@
): Task\Update {
return new Task\Update(
$container->get('task_repository'),
$container->get('redis_service')
$container->get('redis_service'),
$container->get('logger_service')
);
};

Expand All @@ -84,7 +92,8 @@
): Task\Delete {
return new Task\Delete(
$container->get('task_repository'),
$container->get('redis_service')
$container->get('redis_service'),
$container->get('logger_service')
);
};

Expand All @@ -93,7 +102,8 @@
): Note\Find {
return new Note\Find(
$container->get('note_repository'),
$container->get('redis_service')
$container->get('redis_service'),
$container->get('logger_service')
);
};

Expand All @@ -102,7 +112,8 @@
): Note\Create {
return new Note\Create(
$container->get('note_repository'),
$container->get('redis_service')
$container->get('redis_service'),
$container->get('logger_service')
);
};

Expand All @@ -111,7 +122,8 @@
): Note\Update {
return new Note\Update(
$container->get('note_repository'),
$container->get('redis_service')
$container->get('redis_service'),
$container->get('logger_service')
);
};

Expand All @@ -120,6 +132,7 @@
): Note\Delete {
return new Note\Delete(
$container->get('note_repository'),
$container->get('redis_service')
$container->get('redis_service'),
$container->get('logger_service')
);
};
3 changes: 2 additions & 1 deletion src/App/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
'enabled' => $_SERVER['REDIS_ENABLED'],
'url' => $_SERVER['REDIS_URL'],
],
'log' => [
'logger' => [
'enabled' => $_SERVER['LOGS_ENABLED'],
'path' => 'logs/',
'channel' => 'channel_api'
],
Expand Down
5 changes: 5 additions & 0 deletions src/Controller/BaseController.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,9 @@ protected static function isRedisEnabled(): bool
{
return filter_var($_SERVER['REDIS_ENABLED'], FILTER_VALIDATE_BOOLEAN);
}

protected static function isLoggerEnabled(): bool
{
return filter_var($_SERVER['LOGS_ENABLED'], FILTER_VALIDATE_BOOLEAN);
}
}
13 changes: 12 additions & 1 deletion src/Controller/DefaultController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

final class DefaultController extends BaseController
{
public const API_VERSION = '1.5.0';
public const API_VERSION = '1.6.0';

public function getHelp(Request $request, Response $response): Response
{
Expand Down Expand Up @@ -38,6 +38,7 @@ public function getStatus(Request $request, Response $response): Response
'stats' => $this->getDbStats(),
'MySQL' => 'OK',
'Redis' => $this->checkRedisConnection(),
'Logger' => $this->checkLoggerConnection(),
'version' => self::API_VERSION,
'timestamp' => time(),
];
Expand Down Expand Up @@ -70,4 +71,14 @@ private function checkRedisConnection(): string

return $redis;
}

private function checkLoggerConnection(): string
{
$logger = 'Disabled';
if (self::isLoggerEnabled() === true){
$logger = 'Enabled';
}

return $logger;
}
}
9 changes: 5 additions & 4 deletions src/Repository/NoteRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,17 @@
namespace App\Repository;

use App\Exception\NoteException;
use App\Entity\Note;

final class NoteRepository extends BaseRepository
{
public function checkAndGetNote(int $noteId): \App\Entity\Note
public function checkAndGetNote(int $noteId): Note
{
$query = 'SELECT * FROM `notes` WHERE `id` = :id';
$statement = $this->getDb()->prepare($query);
$statement->bindParam('id', $noteId);
$statement->execute();
$note = $statement->fetchObject(\App\Entity\Note::class);
$note = $statement->fetchObject(Note::class);
if (!$note) {
throw new NoteException('Note not found.', 404);
}
Expand Down Expand Up @@ -91,7 +92,7 @@ public function searchNotes(string $strNotes): array
return $notes;
}

public function createNote(\App\Entity\Note $note): \App\Entity\Note
public function createNote(Note $note): Note
{
$query = '
INSERT INTO `notes`
Expand All @@ -111,7 +112,7 @@ public function createNote(\App\Entity\Note $note): \App\Entity\Note
return $this->checkAndGetNote((int) $this->getDb()->lastInsertId());
}

public function updateNote(\App\Entity\Note $note): \App\Entity\Note
public function updateNote(Note $note): Note
{
$query = '
UPDATE `notes`
Expand Down
9 changes: 5 additions & 4 deletions src/Repository/TaskRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
namespace App\Repository;

use App\Exception\TaskException;
use App\Entity\Task;

final class TaskRepository extends BaseRepository
{
public function checkAndGetTask(int $taskId, int $userId): \App\Entity\Task
public function checkAndGetTask(int $taskId, int $userId): Task
{
$query = '
SELECT * FROM `tasks`
Expand All @@ -18,7 +19,7 @@ public function checkAndGetTask(int $taskId, int $userId): \App\Entity\Task
$statement->bindParam('id', $taskId);
$statement->bindParam('userId', $userId);
$statement->execute();
$task = $statement->fetchObject(\App\Entity\Task::class);
$task = $statement->fetchObject(Task::class);
if (!$task) {
throw new TaskException('Task not found.', 404);
}
Expand Down Expand Up @@ -124,7 +125,7 @@ public function searchTasks(string $tasksName, int $userId, ?int $status): array
return $tasks;
}

public function createTask(\App\Entity\Task $task): \App\Entity\Task
public function createTask(Task $task): Task
{
$query = '
INSERT INTO `tasks`
Expand All @@ -150,7 +151,7 @@ public function createTask(\App\Entity\Task $task): \App\Entity\Task
return $this->checkAndGetTask((int) $taskId, (int) $userId);
}

public function updateTask(\App\Entity\Task $task): \App\Entity\Task
public function updateTask(Task $task): Task
{
$query = '
UPDATE `tasks`
Expand Down
Loading

0 comments on commit 6b87720

Please sign in to comment.