JwtPayloadFormat.php 1.44 KB
<?php

namespace App\Support;

use App;
use Hikoon\LaravelJwt\Support\Format;
use Illuminate\Support\Arr;

class JwtPayloadFormat extends Format
{
    /**
     * @param array<string,mixed> $payload
     * @return array<string,mixed>
     */
    public function encrypt(array $payload): array
    {
        $data = $this->getBasicPayload($payload);

        if (in_array($this->guard, ['admin', 'manage', 'user'], true)) {
            $data['extend'] = ['id' => $data['jti'], ...Arr::get($payload, 'extend', [])];
            return $data;
        }

        if ($this->guard === 'app') {
            $data['data'] = ['id' => $data['jti'], 'env' => App::isProduction() ? 'pro' : 'dev', ...Arr::get($payload, 'extend', [])];
            return Arr::only($data, ['data', 'iat', 'exp', 'jti']);
        }

        return $payload;
    }

    /**
     * @param array<string,mixed> $payload
     * @return array<string,mixed>
     */
    public function decrypt(array $payload): array
    {
        $data = $this->getBasicPayload($payload);

        if (in_array($this->guard, ['admin', 'manage', 'user'], true)) {
            $data['jti'] = $data['jti'] ?? Arr::get($payload, 'extend.id', 0);
            return $data;
        }

        if ($this->guard === 'app') {
            $data['jti']    = $data['jti'] ?? Arr::get($payload, 'data.id', 0);
            $data['extend'] = Arr::get($payload, 'data', []);
            return $data;
        }

        return $payload;
    }
}