ldc-bogt/app/Jobs/CafelJobs.php
2022-12-06 11:03:38 +01:00

133 lines
4.7 KiB
PHP

<?php
namespace App\Jobs;
use App\Lib\CafelApi\Models\CafelClientModel;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;
use Illuminate\Validation\ValidationException;
abstract class CafelJobs implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* Invalid Rows that should be reported.
*
* @var array
*/
private $invalidRows = [];
/**
* Sync with with cafel api using paginate method.
*
* @param string $apiClassName The CafelClientModel class to use.
* @param string $routeName The route name to use.
* @param array $args Arguments to pass.
* @param callable $saveCallback The save callback to use.
* @return void
* @throws \ErrorException If $apiClassName is not a CafelClientModel class.
*/
protected function syncWithCafelApi(string $apiClassName, string $routeName, array $args, callable $saveCallback)
{
if (!is_subclass_of($apiClassName, CafelClientModel::class)) {
throw new \ErrorException(sprintf(
'%s n\'est pas une class de type %s',
$apiClassName,
CafelClientModel::class
));
}
$pageNumber = 0;
$perPage = 100;
$args = array_merge([
'routeName' => $routeName,
'page' => $pageNumber,
'pageSize' => $perPage
], $args);
do {
/** @var array $result */
$result = \forward_static_call_array([$apiClassName, 'paginate'], $args);
$args['page'] = ++$pageNumber;
foreach ($result as $row) {
if (!is_array($row)) {
throw new \ErrorException(\sprintf(
'Unexpected type for $row got %s',
\gettype($row)
));
}
try {
$saveCallback($row);
} catch (ValidationException $e) {
/** @var \Illuminate\Validation\Validator $validator */
$validator = $e->validator;
/** @var array<string,integer|string> */
$failed = $validator->invalid();
$this->invalidRows[] = collect($row)->put('validation_message', collect($e->errors())
->mapWithKeys(function (array $messages, string $attribute) use ($failed) {
$verifiedValue = '';
if (array_key_exists($attribute, $failed)) {
$verifiedValue = ' Valeur vérifiée : ' . \json_encode($failed[$attribute]);
}
return [
$attribute => collect($messages)->implode(', ') . $verifiedValue
];
})->implode(' '))->all();
} catch (ConnectException | RequestException $e) {
// ! Guzzle SSL Error connection failure
\report($e);
$this->invalidRows[] = collect($row)->put('validation_message', $e->getMessage())->all();
}//end try
}//end foreach
} while (!empty($result));
}
/**
* Send an email with invalid rows
*
* @param array $uniqueKeys
* @param string $jobClass
* @return void
*/
protected function mailInvalidRows(array $uniqueKeys, string $jobClass)
{
/** @var array Unique Key columns */
$invalidRowKeys = [];
$uniqueKeys = \array_merge(['validation_message'], $uniqueKeys);
\collect($this->invalidRows)
->map(function ($invalidRow) use ($uniqueKeys, &$invalidRowKeys) {
$o = [];
foreach ($uniqueKeys as $uField) {
$o[$uField] = $invalidRow[$uField];
}
$invalidRowKeys[] = $o;
});
if (!count($invalidRowKeys)) {
return;
}
Mail::send('mails.invalidApiRows', [
'invalidkeys' => $invalidRowKeys,
'jobClass' => $jobClass
], function ($m) {
$m->to(
config('mail.contactsList.invalidCafel'),
sprintf('%s Exception Handler', config('app.name'))
)->subject('There are invalid data sheets provided by Cafel api.');
});
}
}