Created
August 4, 2021 09:28
-
-
Save aurimasniekis/e10fe097c00a49fc391c7cce06804a43 to your computer and use it in GitHub Desktop.
Small example of generating Typescript interfaces from PHP classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class BaseView extends View | |
{ | |
} | |
class AuthorUserView extends BaseView | |
{ | |
#[Property(type: 'string')] | |
public Ulid $id; | |
public string $fullName; | |
public string $email; | |
public function __construct(User $user) | |
{ | |
$this->id = $user->getId(); | |
$this->fullName = $user->getFullName(); | |
$this->email = $user->getEmail(); | |
} | |
} | |
class HasCreatedBy extends View | |
{ | |
/** | |
* @template U | |
* | |
* @var U | |
*/ | |
#[GenericTypeVariable('U')] | |
private array $createdBy; | |
} | |
class FullClientView extends BaseView | |
{ | |
use HasIdTrait; | |
use HasTimestampsTrait; | |
use HasAuthorTrait; | |
public string $companyName; | |
public ?string $email; | |
} | |
/** | |
* @template T | |
*/ | |
#[GenericTypeVariable('U')] | |
class PaginatedResultView extends BaseView | |
{ | |
public int $total; | |
/** | |
* @var array<string, T> | |
*/ | |
#[GenericTypeVariable(extends: HasCreatedBy::class)] | |
public array $data; | |
} | |
#[GenericTypeValue(AuthorUserView::class, 'U')] | |
class ListClientView extends BaseView | |
{ | |
#[GenericTypeValue(FullClientView::class, variable: 'T')] | |
public PaginatedResultView $clients; | |
public function __construct(PaginatedResult $result) | |
{ | |
$this->clients = $this->paginated(FullClientView::class, $result); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface BaseView { | |
} | |
export interface AuthorUserView extends BaseView { | |
id: string; | |
fullName: string; | |
email: string; | |
} | |
export interface HasCreatedBy<U> { | |
createdBy: U; | |
} | |
export interface FullClientView extends BaseView { | |
companyName: string; | |
email: string | null; | |
id: string; | |
createdAt: number; | |
updatedAt: number | null; | |
createdBy: AuthorUserView; | |
updatedBy: AuthorUserView | null; | |
} | |
export interface PaginatedResultView<U, T extends HasCreatedBy<U>> extends BaseView { | |
total: number; | |
data: Record<string, T>; | |
} | |
export interface ListClientView extends BaseView { | |
clients: PaginatedResultView<AuthorUserView, FullClientView>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment