andro-adel/microservice-package

initialize packages required for logging , messaging with rabbitmq , redis caching

0.1.40 2024-02-26 10:51 UTC

README

Build Status Total Downloads Latest Stable Version License

About Package

This is a laravel package to be used with each microservice to setup main packages and configurations.

Packages that will be installed

Installation

You can install the package via composer:

composer require andro-adel/microservice-package -W

Vendor Publish

Publish all the files

php artisan vendor:publish --provider="DD\MicroserviceCore\MicroserviceCoreServiceProvider"

Publish the config files individually

php artisan vendor:publish --tag=dd-config

Publish the lang files individually

php artisan vendor:publish --tag=dd-lang

Publish the tests files individually

./vendor/bin/pest --init

Configuration

This package has the configuration files in the config folder upon installation, extending the project configuration from ddconfig. and this files are:

  • ddconfig.php - This file will be used to configure the logging.channels and database.redis that will be used in the microservice.
  • excel.php - This file will be used to configure the exporting and importing of excel files.
  • scribe.php - This file will be used to configure the API documentation.
  • services-communication.php - This file will be used to configure the services communication.
  • snappy.php - This file will be used to configure the downloading and streaming of PDF files.

Usage

ApiResponses

This functions will be used by the microservice to return the response in a standard way.

use DD\MicroserviceCore\Classes\ApiResponses;

Success Response

This function will be used to return a success response with the data, reason, message, additionData, status.

ApiResponses::successResponse(array $data, string $reason, string|null $message = null, array $additionData = [], $status = 200)

example:

return ApiResponses::successResponse(data: ["user" : $user], reason: "User retrieved successfully", additionData: ["extra" : "extra value"]);
{
  "status": 200,
  "success": true,
  "type": "success",
  "data": {
    "user": {
      "id": 1,
      "name": "John Doe",
      "email": "John@gmail.com"
    }
  },
  "reason": "User retrieved successfully",
  "message": "Done successfully",
  "extra": "extra value"
}

Success No Content Response

This function will be used to return a success response with no content.

ApiResponses::successNoContentResponse()

example:

return ApiResponses::successNoContentResponse();

Not Modified Response

This function will be used to return a not modified response.

ApiResponses::notModifiedResponse(string|null $resourceName = null,string|null $message = null,array $additionData = [])

example:

return ApiResponses::notModifiedResponse(resource: "User", message: "User not modified", additionData: ["extra" : "extra value"]);
{
  "status": 304,
  "success": false,
  "type": "error",
  "reason": "Failure",
  "message": "User not modified",
  "extra": "extra value"
}

Bad Request Response

This function will be used to return a bad request response.

ApiResponses::badRequestResponse(string|null $message = null, array $additionData = [], $status = 400)

example:

return ApiResponses::badRequestResponse(message: "Invalid data", additionData: ["extra" : "extra value"]);
{
  "status": 400,
  "success": false,
  "type": "error",
  "reason": "Bad Request",
  "message": "Invalid data",
  "extra": "extra value"
}

Unauthorized Response

This function will be used to return an unauthorized response.

ApiResponses::unauthorizedResponse(string|null $message = null, array $additionData = [])

example:

return ApiResponses::unauthorizedResponse(message: "Unauthorized User", additionData: ["extra" : "extra value"]);
{
  "status": 403,
  "success": false,
  "type": "error",
  "reason": "Unauthorized",
  "message": "Unauthorized User",
  "extra": "extra value"
}

Unauthenticated Response

This function will be used to return an unauthenticated response.

ApiResponses::unauthenticatedResponse(string|null $message = null, array $additionData = [])

example:

return ApiResponses::unauthenticatedResponse(message: "Unauthenticated User", additionData: ["extra" : "extra value"]);
{
  "status": 401,
  "success": false,
  "type": "error",
  "reason": "Unauthenticated",
  "message": "Unauthenticated User",
  "extra": "extra value"
}

Not Found Response

This function will be used to return a not found response.

ApiResponses::notFoundResponse(string|null $resourceName = null, string|null $message = null, array $additionData = [])

example:

return ApiResponses::notFoundResponse(resource: "User", message: "User not found", additionData: ["extra" : "extra value"]);
{
  "status": 404,
  "success": false,
  "type": "error",
  "reason": "Not Found",
  "message": "User not found",
  "extra": "extra value"
}

Conflict Response

This function will be used to return a conflict response.

ApiResponses::conflictResponse(string $type,array $data,string|null $resourceName = null, string|null $message = null, array $additionData = [])

example:

return ApiResponses::conflictResponse(type:"User",data: ["user" : $user], resourceName: "User", message: "User already exists", additionData: ["extra" : "extra value"]);
{
  "status": 409,
  "success": false,
  "type": "User",
  "data": {
    "user": {
      "id": 1,
      "name": "John Doe",
      "email": "John@gmail.com"
    }
  },
  "reason": "Failure",
  "message": "User already exists",
  "extra": "extra value"
}

Not Valid Response

This function will be used to return a not valid response.

ApiResponses::notValidResponse(array $errors, array $data, string|null $message = null, array $additionData = [])

example:

return ApiResponses::notValidResponse(errors: ["name" : "Name is required"], data: ["user" : $user], message: "Invalid data", additionData: ["extra" : "extra value"]);
{
  "status": 422,
  "success": false,
  "type": "error",
  "reason": "Validation",
  "message": "Invalid data",
  "errors": {
    "name": "Name is required"
  },
  "data": {
    "user": {
      "id": 1,
      "email": "john.doe@gmail.com"
    }
  },
  "extra": "extra value"
}

Server Error Response

This function will be used to return a server error response.

ApiResponses::serverErrorResponse(string|int  $errorCode,string|null $message = null, array $additionData = [])

example:

return ApiResponses::serverErrorResponse(errorCode: 500, message: "Server error", additionData: ["extra" : "extra value"]);
{
  "status": 500,
  "success": false,
  "type": "error",
  "reason": "Exceptions",
  "message": "Server error",
  "errorCode": 500,
  "extra": "extra value"
}

Success Pagination Response

This function will be used to return a success pagination response.

ApiResponses::successPaginationResponse(LengthAwarePaginator $data, string $reason = 'Show', string|null $message = null, array $additionData = [])

example:

return ApiResponses::successPaginationResponse(data: $users, reason: "Users retrieved successfully", additionData: ["extra" : "extra value"]);
{
  "status": 200,
  "success": true,
  "type": "success",
  "data": {
    "current_page": 1,
    "data": [
      {
        "id": 1,
        "name": "John Doe",
        "email": "john.doe@gmail.com"
      },
      {
        "id": 2,
        "name": "Jane Doe",
        "email": "jane.doe@gmail.com"
      },
      {
        "id": 3,
        "name": "Ahmed",
        "email": "ahmed@gmail.com"
      }
    ],
    "first_page_url": "http://localhost:8000/api/users?page=1",
    "from": 1,
    "last_page": 1
  },
  "reason": "Users retrieved successfully",
  "message": "Done successfully",
  "extra": "extra value"
}

Success Show Pagination Response

This function will be used to return a success show pagination response.

ApiResponses::successShowPaginationResponse($data, $meta, string $reason = 'Show')

example:

return ApiResponses::successShowPaginationResponse(data: $users, meta: $meta, reason: "Users retrieved successfully");
{
  "status": 200,
  "success": true,
  "type": "success",
  "data": {
    "current_page": 1,
    "data": [
      {
        "id": 1,
        "name": "John Doe",
        "email": "john.doe@gmail.com",
        "created_at": "2022-01-01T00:00:00.000000Z",
        "updated_at": "2022-01-01T00:00:00.000000Z"
      },
      {
        "id": 2,
        "name": "ahmed Doe",
        "email": "ahmed.doe@gmail.com",
        "created_at": "2022-01-01T00:00:00.000000Z",
        "updated_at": "2022-01-01T00:00:00.000000Z"
      }
    ],
    "first_page_url": "http://localhost:8000/api/users?page=1",
    "from": 1,
    "last_page": 1
  },
  "reason": "Users retrieved successfully",
  "meta": {
    "current_page": 1,
    "from": 1,
    "last_page": 1,
    "path": "http://localhost:8000/api/users",
    "per_page": 15,
    "to": 2,
    "total": 2
  }
}

Success Show Paginated Data Response

This function will be used to return a success show paginated data response.

ApiResponses::successShowPaginatedDataResponse(JsonResource $data, string $reason = 'Show')

example:

return ApiResponses::successShowPaginatedDataResponse(data: $users, reason: "Users retrieved successfully");
{
  "status": 200,
  "success": true,
  "type": "success",
  "data": {
    "id": 1,
    "name": "John Doe",
    "email": "john.doe@gmail.com",
    "created_at": "2022-01-01T00:00:00.000000Z",
    "updated_at": "2022-01-01T00:00:00.000000Z"
  },
  "reason": "Users retrieved successfully",
  "count": 1
}

Created Successfully Response

This function will be used to return a created successfully response.

ApiResponses::createdSuccessfullyResponse($data = null, string|null $resourceName = null,?string $message = null)

example:

return ApiResponses::createdSuccessfullyResponse(data: ["user" : $user], resourceName: "User", message: "User created successfully");
{
  "status": 201,
  "success": true,
  "type": "success",
  "data": {
    "user": {
      "id": 1,
      "name": "John Doe",
      "email": "john.doe@gmail.com",
      "created_at": "2022-01-01T00:00:00.000000Z",
      "updated_at": "2022-01-01T00:00:00.000000Z"
    }
  },
  "reason": "Created",
  "message": "User created successfully"
}

Caching

This functions will be used by the microservice to handle caching data.

use DD\MicroserviceCore\Classes\Caching;

Creating Object From Caching class

  • Creating Object From Caching class
$caching = new Caching();

and you can change the default connection on object creation by passing the connection name to the constructor.

$caching = new Caching('connection_name');

or you can change the default connection after object creation by using the setConnection function.

$caching->setConnection('connection_name');
  • Injecting Caching class
public function __construct(protected readonly Caching $caching) {}

and you can change the default connection after object creation by using the setConnection function.

$caching->setConnection('connection_name');

Caching Functions

  • Set Cache
$caching->set(string $key, mixed $value);
  • Set Cache With Options
use DD\MicroserviceCore\Classes\SetOptions;
$options = new SetOptions();
$options->setExpiration(int $ttl);
$options->setExpirationTimestamp(string $timestamp);
$options->setExpirationInMilliseconds(int $ttl);
$options->setExpirationTimestampInMilliseconds(string $timestamp);
$options->setExpirationSameAsOld();
$options->returnOldValue();
$options->setIfNew();
$options->setIfExist();
$caching->set(string $key, mixed $value, SetOptions $options);
  • Set Multiple Cache
$values = [
   'key1' => 'value1',
   'key2' => 'value2',
   'key3' => 'value3',
];
$caching->setMany(array $values);
  • Get Cache
$caching->get(string|array $key);
  • Rename Key
$caching->rename(string $oldKey, string $newKey);
  • Delete Cache
$caching->delete(string|array $key);
  • Get Key Type
$caching->getType(string $key);
  • Set Expire
$caching->setExpire(string $key, int $ttl);
  • Set Expire With Options
use DD\MicroserviceCore\Classes\ExpireOptions;
$options = new ExpireOptions();
$options->setIfNew();
$options->setIfExist();
$options->setIfGreaterThanCurrent();
$options->setIfLessThanCurrent();
$caching->set(string $key, int $ttl, ExpireOptions $options);
  • Check If Cache Exists
$caching->isKeyExist(string|array $key);
  • Key Searching
$caching->keySearching(string $pattern);
  • Get All Keys
$caching->getAllKeys();
  • Run Set of commands together
$caching->transaction(Closure $callback);
  • Run Command
$caching->command(string $command, array $values);

Filters

This functions will be used by the microservice to handle filtering data.

use DD\MicroserviceCore\Classes\FilterManager;

Creating Object From FilterManager class

  • Creating Object From FilterManager class
$filterManager = new FilterManager();

filters data is the data that will be used to apply filters.

the default filters data will be set to the request data with key filter, and you can set filters data on object creation by passing the filters data to the constructor.

$filterManager = new FilterManager(array $filtersData);

or you can set the filters data after object creation by using the setFiltersData function.

$filterManager->setFiltersData(array $filtersData);
  • Injecting FilterManager class
public function __construct(protected readonly FilterManager $filterManager) {}

and you can set the filters data after object creation by using the setFiltersData function.

$caching->setFiltersData(array $filtersData);

Build Filters

  • Add Where Filter
$filterManager->addWhereFilter(string $column);

by default the operator will be set to =, you can pass the operator to the function to apply the operator to the filter.

$filterManager->addWhereFilter(string $column, string $operator);

by default, when applying the filters the value for this where filter will be taken from the filters data with the same key as the column name, you can pass difference key to the function to apply the value to the filter.

$filterManager->addWhereFilter(string $column, string $operator, string $valueKey);
  • Add Where In Filter
$filterManager->addWhereInFilter(string $column);

by default, when applying the filters the value for this where filter will be taken from the filters data with the same key as the column name, you can pass difference key to the function to apply the value to the filter.

$filterManager->addWhereInFilter(string $column, string $valueKey);
  • Add Where Not In Filter
$filterManager->addWhereNotInFilter(string $column);

by default, when applying the filters the value for this where filter will be taken from the filters data with the same key as the column name, you can pass difference key to the function to apply the value to the filter.

$filterManager->addWhereNotInFilter(string $column, string $valueKey);
  • Add Where Has Filter [NOTE: you can't use this function with collection or array data.]
$filterManager->addWhereHasFilter(string $relationName, Closure $callback);

by default, when applying the filters the value for this where filter will be taken from the filters data with the same key as the relation name, you can pass difference key to the function to apply the value to the filter.

$filterManager->addWhereHasFilter(string $relationName, Closure $callback, string $valueKey);
  • Add Where Has Morph Filter [NOTE: you can't use this function with collection or array data.]
$filterManager->addWhereHasMorphFilter(string $relationName, string|array $types, Closure $callback);

by default, when applying the filters the value for this where filter will be taken from the filters data with the same key as the relation name, you can pass difference key to the function to apply the value to the filter.

$filterManager->addWhereHasMorphFilter(string $relationName, string|array $types, Closure $callback, string $valueKey);
  • Add Has Filter [NOTE: you can't use this function with collection or array data.]
$filterManager->addHasFilter(string $relationName);

by default the operator will be set to >=, you can pass the operator to the function to apply the operator to the filter.

$filterManager->addHasFilter(string $relationName, string $operator);

by default, when applying the filters the value for this where filter will be taken from the filters data with the same key as the column name, you can pass difference key to the function to apply the value to the filter.

$filterManager->addHasFilter(string $relationName, string $operator, string $valueKey);
  • Add Where Between Filter there are four ways to use this function.

    • First way
    $filtersData = [
         $column => ['value1','value2'],
    ];
    $filterManager->addWhereBetweenFilter(string $column);
    • Second way
    $filtersData = [
         $valueKey => ['value1','value2'],
    ];
    $filterManager->addWhereBetweenFilter(string $column, string $valueKey);
    • Third way
    $filtersData = [
       'valueKey1' => 'value1',
       'valueKey2' => 'value2',
    ];
    $filterManager->addWhereBetweenFilter(string $column, ['valueKey1','valueKey2']);
    • Forth way if you have a different logic to apply the where between filter you can pass a callback to the function to apply the logic to the filter.
    $callback = function(): array {};
    $filterManager->addWhereBetweenFilter(string $column, Closure $callback);
    • Add Where Not Between Filter there are four ways to use this function.

      • First way
      $filtersData = [
         $column => ['value1','value2'],
      ];
      $filterManager->addWhereBetweenFilter(string $column);
      • Second way
      $filtersData = [
         $valueKey => ['value1','value2'],
      ];
      $filterManager->addWhereBetweenFilter(string $column, string $valueKey);
      • Third way
      $filtersData = [
         'valueKey1' => 'value1',
         'valueKey2' => 'value2',
      ];
      $filterManager->addWhereBetweenFilter(string $column, ['valueKey1','valueKey2']);
      • Forth way

      if you have a different logic to apply the where between filter you can pass a callback to the function to apply the logic to the filter.

      $callback = function(): array {};
      $filterManager->addWhereBetweenFilter(string $column, Closure $callback);
  • Add Where Function Filter

$filterManager->addWhereFunctionFilter(Closure $callback, string $filterKey);

$filterKey is the key that will be used to check if this filter will be applied or not.

  • Add Multiple Where Filter
$columns = [
   'column1',
   'column2' => 'valueKey',
   'column3'
];
$filterManager->addMultipleWhereFilter(array $columns);

by default the operator will be set to =, you can pass the operator to the function to apply the operator to the filter.

$filterManager->addMultipleWhereFilter(array $columns, string $operator);
  • Add Multiple Where In Filter
$columns = [
   'column1',
   'column2' => 'valueKey',
   'column3'
];
$filterManager->addMultipleWhereInFilter(array $columns);
  • Add Multiple Where Not In Filter
$columns = [
   'column1',
   'column2' => 'valueKey',
   'column3'
];
$filterManager->addMultipleWhereNotInFilter(array $columns);
  • Add Multiple Where Has Filter [NOTE: you can't use this function with collection or array data.]
$relations = [
   'relation1' => function($query){},
   'relation2' => function($query){},
   'relation3' => function($query){}
];
$filterManager->addMultipleWhereHasFilter(array $relations);
  • Add Multiple Has Filter
$relations = [
   'relation1',
   'relation2' => 'valueKey',
   'relation3'
];
$filterManager->addMultipleHasFilter(array $relations);

by default the operator will be set to >=, you can pass the operator to the function to apply the operator to the filter.

$filterManager->addMultipleHasFilter(array $relations, string $operator);
  • Add Multiple Where Between Filter
$data = [
   'column1',
   'column2' => 'valueKey',
   'column3' => ['valueKey1', 'valueKey2'],
   'column4' => functioin(): array {}
];
$filterManager->addMultipleWhereBetweenFilter(array $data);
  • Add Multiple Where Not Between Filter
$data = [
   'column1',
   'column2' => 'valueKey',
   'column3' => ['valueKey1', 'valueKey2'],
   'column4' => functioin(): array {}
];
$filterManager->addMultipleWhereNotBetweenFilter(array $data);

Applying Filters

Now you can simply call function applyFilters from $filterManager object.

$filterManager->applyFilters(Relation|Builder|Collection|array &$data)

And your data will be filtered.

Example

use DD\MicroserviceCore\Classes\FilterManager;
use DD\MicroserviceCore\Interfaces\ServiceInterface;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Collection;

class ModelService implements ServiceInterface
{

   /**
   * @inheritDoc
   */
   public function applyFilters(Relation|Builder|array|Collection &$data, ?array $filtersData = null): void
   {
      $filterManager = new FilterManager($filtersData);

      $filterManager->addMultipleWhereFilter(['name', 'email' => 'mail'], 'LIKE');
      $filterManager->addWhereInFilter('id');

      $filterManager->applyFilters($data);
   }
}

Logging

use DD\MicroserviceCore\Classes\Logging

Logging Types

  • emergency
  • alert
  • critical
  • error
  • warning
  • notice
  • info
  • debug

Functions

For each type there are an static function to handle it, all function have two parameters string $message and array $context = [].

Logging::emergency(string $message, array $context);
Logging::alert(string $message, array $context);
Logging::critical(string $message, array $context);
Logging::error(string $message, array $context);
Logging::warning(string $message, array $context);
Logging::notice(string $message, array $context);
Logging::info(string $message, array $context);
Logging::debug(string $message, array $context);

Form Request

extends the DD\MicroserviceCore\Abstracts\ApiFormRequest abstract class.

use DD\MicroserviceCore\Abstracts\ApiFormRequest;
class YourRequestForm extends ApiFormRequest
{}