Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
abibak committed May 7, 2024
0 parents commit bc99c66
Show file tree
Hide file tree
Showing 54 changed files with 8,718 additions and 0 deletions.
15 changes: 15 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false

[*.{yml,yaml}]
indent_size = 2
21 changes: 21 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
APP_NAME=Lumen
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost:9090
APP_TIMEZONE=UTC

LOG_CHANNEL=stack
LOG_SLACK_WEBHOOK_URL=

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=loans
DB_USERNAME=root
DB_PASSWORD=

CACHE_DRIVER=file
QUEUE_CONNECTION=sync

JWT_SECRET=
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/vendor
/.idea
Homestead.json
Homestead.yaml
.env
.phpunit.result.cache
6 changes: 6 additions & 0 deletions .styleci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
php:
preset: laravel
disabled:
- unused_use
js: true
css: true
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# REST API Lumen framework

---

## Для того чтобы начать:

### Установка зависимостей
```
composer install
```

### Установка ключей приложения и JWT
```
php artisan key:generate
php artisan jwt:secret
```

### Выполнение миграций и сидеров
```
php artisan migrate --seed
```

### Запуск локального сервера
```
php artisan serve
```
**По умолчанию:** http://localhost:9090

### Дополнительно
#### Tlint для проверки стиля кода, запускает через команду `vendor/bin/tlint`
```
composer tlint
```

### Тестирование
#### Тестирование выполняется через **PHPUnit**
```
composer test
```

### API роуты
| HTTP метод | Роут | Действие | Описание |
|------------|----------------|----------|----------------------------------|
| POST | api/login | login | Авторизация пользователя |
| GET | api/loans | index | Получает все займы |
| POST | api/loans | store | Создает новый займ |
| GET | api/loans/{id} | show | Получает займ по id |
| PUT | api/loans/{id} | update | Обновляет информацию займа по id |
| DELETE | api/loans/{id} | delete | Удаляет займ по id |



Empty file added app/Console/Commands/.gitkeep
Empty file.
29 changes: 29 additions & 0 deletions app/Console/Commands/GenerateKeyCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace App\Console\Commands;

use App\Traits\HelperEnvTrait;
use Illuminate\Console\Command;
use Illuminate\Encryption\Encrypter;

class GenerateKeyCommand extends Command
{
use HelperEnvTrait;

private string $key = 'APP_KEY';

protected $signature = 'key:generate';

protected $description = 'Generate key application.';

public function handle(): void
{
$this->setEnvValue($this->key, $this->generateRandomKey());
$this->info('App key set successfully.');
}

private function generateRandomKey(): string
{
return 'base64:' . base64_encode(Encrypter::generateKey($this->laravel['config']['app.cipher']));
}
}
29 changes: 29 additions & 0 deletions app/Console/Commands/JWTGenerateSecretCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace App\Console\Commands;

use App\Traits\HelperEnvTrait;
use Illuminate\Console\Command;
use Illuminate\Encryption\Encrypter;

class JWTGenerateSecretCommand extends Command
{
use HelperEnvTrait;

private string $key = 'JWT_SECRET';

protected $signature = 'jwt:secret';

protected $description = 'Generating secret jwt key';

public function handle()
{
$this->setEnvValue($this->key, $this->generateSecretJwtKey());
$this->info('Successfully set secret jwt key.');
}

public function generateSecretJwtKey(): string
{
return base64_encode(Encrypter::generateKey($this->laravel['config']['app.cipher']));
}
}
36 changes: 36 additions & 0 deletions app/Console/Commands/ServeCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class ServeCommand extends Command
{
protected $signature = 'serve {--host=} {--port=}';

protected $description = 'Command starting development server.';

public function handle()
{
exec($this->serveCommand());
}

private function serveCommand(): string
{
return 'php -S ' . $this->host() . ':' . $this->port() . ' -t ' . base_path('public');
}

private function host(): string
{
return $this->input->getOption('host') ??
parse_url(getenv('APP_URL'), PHP_URL_HOST) ??
'localhost';
}

private function port(): int
{
return $this->input->getOption('port') ??
parse_url(getenv('APP_URL'), PHP_URL_PORT) ??
9090;
}
}
34 changes: 34 additions & 0 deletions app/Console/Kernel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace App\Console;

use App\Console\Commands\GenerateKeyCommand;
use App\Console\Commands\JWTGenerateSecretCommand;
use App\Console\Commands\ServeCommand;
use Illuminate\Console\Scheduling\Schedule;
use Laravel\Lumen\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
GenerateKeyCommand::class,
ServeCommand::class,
JWTGenerateSecretCommand::class,
];

/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
//
}
}
10 changes: 10 additions & 0 deletions app/Events/Event.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace App\Events;

use Illuminate\Queue\SerializesModels;

abstract class Event
{
use SerializesModels;
}
16 changes: 16 additions & 0 deletions app/Events/ExampleEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace App\Events;

class ExampleEvent extends Event
{
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
//
}
}
25 changes: 25 additions & 0 deletions app/Exceptions/APIException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace App\Exceptions;


use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\Response;

class APIException extends HttpResponseException
{
public function __construct(string $message = "", int $code = 0, array $errors = [])
{
$data = [
'data' => [
'message' => $message,
],
];

if (!empty($errors)) {
$data['errors'] = $errors;
}

parent::__construct(new Response($data, $code, ['Content-type', 'application\json']));
}
}
74 changes: 74 additions & 0 deletions app/Exceptions/Handler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

namespace App\Exceptions;

use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];

/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Throwable $exception
* @return void
*
* @throws \Exception
*/
public function report(Throwable $e)
{
parent::report($e);
}

public function render($request, Throwable $e)
{
if ($e instanceof QueryException) {
return $this->newResponseApiException('Request error', 400);
}

if ($e instanceof ModelNotFoundException) {
return $this->newResponseApiException('Model not found', 404);
}

if ($e instanceof MethodNotAllowedHttpException) {
return $this->newResponseApiException('Method not allowed', 405);
}

if ($e instanceof NotFoundHttpException) {
return $this->newResponseApiException('Resource not found', 404);
}

return parent::render($request, $e);
}

protected function newResponseApiException
(
string $message,
int $status,
array $headers = ['Content-type' => 'application/json']): Response
{
return new Response(['message' => $message], $status, $headers);
}
}
Loading

0 comments on commit bc99c66

Please sign in to comment.