| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130 |
- <?php
- namespace Controllers;
- use Libs\BashExecutor;
- use Libs\ResponseLib;
- use Models\CprModel;
- use Models\StatusModel;
- use Psr\Http\Message\ServerRequestInterface;
- use Respect\Validation\Exceptions\ValidationException;
- use Respect\Validation\Validator as val;
- use Services\PaymentService;
- class RegisterCprController
- {
- private CprModel $cprModel;
- private StatusModel $statusModel;
- private PaymentService $paymentService;
- private const PIX_VALUE = '1000.00';
- public function __construct()
- {
- $this->cprModel = new CprModel();
- $this->statusModel = new StatusModel();
- $this->paymentService = new PaymentService();
- }
- public function __invoke(ServerRequestInterface $request)
- {
- $body = json_decode((string)$request->getBody(), true) ?? [];
- try {
- val::key('cpr_children_codes', val::arrayType()->notEmpty()->each(val::stringType()->notEmpty()))
- ->assert($body);
- } catch (ValidationException $e) {
- return ResponseLib::sendFail(
- 'Validation failed: ' . $e->getFullMessage(),
- [],
- 'E_VALIDATE'
- )->withStatus(400);
- }
- $userId = (int)($request->getAttribute('api_user_id') ?? 0);
- if ($userId <= 0) {
- return ResponseLib::sendFail('Authenticated user not found', [], 'E_VALIDATE')->withStatus(401);
- }
- $statusId = $this->statusModel->getIdByStatus('pending');
- if ($statusId === null) {
- return ResponseLib::sendFail('Pending status not found', [], 'E_DATABASE')->withStatus(500);
- }
- try {
- $pixData = $this->generateDynamicQrcode();
- } catch (\Throwable $e) {
- return ResponseLib::sendFail('Failed to generate PIX QR Code: ' . $e->getMessage(), [], 'E_INTERNAL')->withStatus(500);
- }
- try {
- $paymentId = $this->paymentService->createPendingPayment($pixData['item_id'], $statusId, $userId);
- } catch (\Throwable $e) {
- return ResponseLib::sendFail('Failed to create payment record: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
- }
- try {
- $record = $this->cprModel->create($body, $statusId, $paymentId);
- } catch (\InvalidArgumentException $e) {
- return ResponseLib::sendFail($e->getMessage(), [], 'E_VALIDATE')->withStatus(400);
- } catch (\Throwable $e) {
- return ResponseLib::sendFail('Failed to create CPR: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
- }
- return ResponseLib::sendOk([
- 'cpr' => $record,
- 'payment' => [
- 'payment_id' => $paymentId,
- 'payment_external_id' => $pixData['item_id'],
- 'status_id' => $statusId,
- ],
- 'pix' => [
- 'qrcode_url' => $pixData['qrcode_url'],
- ]
- ], 'S_CREATED');
- }
- private function generateDynamicQrcode(): array
- {
- $cliPath = dirname(__DIR__) . '/bin/genial-cli';
- if (!is_file($cliPath) || !is_executable($cliPath)) {
- throw new \RuntimeException('genial-cli executable not found or not executable');
- }
- $amount = self::PIX_VALUE;
- $command = sprintf('%s qrcodedynamic %s', escapeshellarg($cliPath), escapeshellarg($amount));
- $result = BashExecutor::run($command, 60);
- if (($result['exitCode'] ?? 1) !== 0) {
- $message = $result['error'] ?: $result['output'] ?: 'Unknown error';
- throw new \RuntimeException($message);
- }
- $output = $result['output'] ?? '';
- $itemId = $this->extractCliValue('itemId', $output);
- $qrcodeUrl = $this->extractCliValue('qrcodeURL', $output);
- if (!$itemId || !$qrcodeUrl) {
- throw new \RuntimeException('Unable to parse itemId or qrcodeURL from genial-cli output');
- }
- return [
- 'item_id' => $itemId,
- 'qrcode_url' => $qrcodeUrl,
- ];
- }
- private function extractCliValue(string $key, string $content): ?string
- {
- $pattern = sprintf('#%s\s*[:=]\s*(?:"([^"]+)"|\' . "'" . '([^\' . "'" . ']+)\' . "'" . '|([^\s,{}]+))#i', preg_quote($key, '#'));
- if (preg_match($pattern, $content, $matches)) {
- foreach (array_slice($matches, 1) as $match) {
- if ($match !== '' && $match !== null) {
- return trim($match);
- }
- }
- }
- return null;
- }
- }
|