PHP code example of monkeyscloud / monkeyslegion-resources

1. Go to this page and download the library: Download monkeyscloud/monkeyslegion-resources library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

monkeyscloud / monkeyslegion-resources example snippets



declare(strict_types=1);

namespace App\Resource;

use MonkeysLegion\Resources\JsonResource;
use MonkeysLegion\Resources\Attributes\{Expose, Hidden, Computed, Groups, When, WhenLoaded, ApiField};

final class UserResource extends JsonResource
{
    #[Expose]
    #[ApiField(type: 'string', format: 'email')]
    public string $email {
        get => $this->entity->email;
    }

    #[Expose]
    public string $name {
        get => $this->entity->name;
    }

    #[Expose]
    #[Groups(['admin'])]
    public string $role {
        get => $this->entity->role;
    }

    #[Computed]
    public string $displayName {
        get => "{$this->entity->name} <{$this->entity->email}>";
    }

    #[Expose]
    #[When('isAdmin')]
    public string $secretField {
        get => $this->entity->secret;
    }

    #[Expose]
    #[WhenLoaded('orders')]
    public int $orderCount {
        get => count($this->entity->orders);
    }

    #[Hidden]
    public string $password {
        get => $this->entity->password;
    }

    protected function isAdmin(): bool
    {
        return $this->entity->role === 'admin';
    }
}

final class UserResource extends JsonResource
{
    protected function toFields(): array
    {
        return [
            'email'        => $this->entity->email,
            'name'         => $this->entity->name,
            'display_name' => "{$this->entity->name} <{$this->entity->email}>",
        ];
    }
}

final class UserResource extends JsonApiResource
{
    protected string $type = 'users';

    protected function toAttributes(object $entity): array
    {
        return [
            'email'      => $entity->email,
            'name'       => $entity->name,
            'created_at' => $entity->createdAt->format('c'),
        ];
    }

    protected function toRelationships(object $entity): array
    {
        return [
            'roles'  => RoleResource::collection($entity->roles),
            'orders' => fn() => OrderResource::collection($entity->orders),
        ];
    }

    protected function toLinks(object $entity): array
    {
        return ['self' => "/api/v2/users/{$entity->id}"];
    }
}

// Single resource
return UserResource::make($user)->toResponse();

// With status
return UserResource::make($user)->toResponse(status: 201);

// With message envelope
return UserResource::make($user)
    ->withMessage('User created')
    ->toResponse(status: 201);

// Collection
return UserResource::collection($users)->toResponse();

// Collection with pagination
return UserResource::collection($users)
    ->paginate(total: 150, page: 3, perPage: 25)
    ->toResponse();

// Collection with groups, message, and meta
return UserResource::collection($users)
    ->withGroups(['admin'])
    ->withMessage('Admin listing')
    ->withMeta(['source' => 'api_v2'])
    ->toResponse();

// Serialization groups
return UserResource::make($user)
    ->withGroups(['admin'])
    ->toResponse();

// JSON:API sparse fieldsets
return UserResource::make($user)
    ->withSparseFields(['name', 'email'])
    ->toResponse();

// JSON:API 

use MonkeysLegion\Resources\OpenApi\ResourceSchemaGenerator;
use MonkeysLegion\OpenApi\OpenApiGenerator;

// Standalone (no injected generator)
$generator = new ResourceSchemaGenerator();
$schema = $generator->generate(UserResource::class);

// With OpenApiGenerator (reads base spec)
$generator = new ResourceSchemaGenerator($openApiGenerator);

// Merge resource schemas into a full OpenAPI spec
$spec = $generator->mergeIntoSpec([
    UserResource::class,
    OrderResource::class,
]);
// Returns a full OpenAPI 3.1 array with components.schemas populated

use MonkeysLegion\Resources\Bridge\SerializerBridge;
use MonkeysLegion\Serializer\Serializer;

$bridge = new SerializerBridge(Serializer::create());

// Normalize an entity using the serializer
$data = $bridge->normalize($user);
$data = $bridge->normalizeCollection($users, groups: ['public']);
$json = $bridge->toJson($user, groups: ['api']);

interface ResourceCollectionInterface
{
    public function toArray(): array;
    public function paginate(int $total, int $page, int $perPage): static;
    public function withMeta(array $meta): static;
    public function withWrap(?string $wrap): static;
    public function withGroups(array $groups): static;
    public function withMessage(string $message): static;
    public function count(): int;
    public function toResponse(int $status = 200): ResponseInterface;
}