PHP code example of le0daniel / php-ts-bindings

1. Go to this page and download the library: Download le0daniel/php-ts-bindings 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/ */

    

le0daniel / php-ts-bindings example snippets


/**
 * @param array{id: UserId} $input
 * @return array{email: Email, slug: Slug}
 */
#[Query('users')]
public function get(array $input): array { /* ... */ }

namespace App\Operations;

use Le0daniel\PhpTsBindings\Contracts\Attributes\Command;
use Le0daniel\PhpTsBindings\Contracts\Attributes\Query;

final class UserOperations
{
    /**
     * @param array{id: UserId} $input
     * @return array{email: Email, slug: Slug}
     */
    #[Query('users')]
    public function get(array $input): array
    {
        return [
            'email' => Email::fromStringValue('[email protected]'),
            'slug' => Slug::fromStringValue("user-{$input['id']->toIntValue()}"),
        ];
    }

    /**
     * @param array{name: string} $input
     * @return array{id: UserId}
     */
    #[Command('users')]
    public function create(array $input): array
    {
        return ['id' => UserId::fromIntValue(strlen($input['name']))];
    }
}

use Le0daniel\PhpTsBindings\CodeGen\CodeGenerators;
use Le0daniel\PhpTsBindings\CodeGen\Data\ServerMetadata;
use Le0daniel\PhpTsBindings\CodeGen\TypescriptServerCodeGenerator;
use Le0daniel\PhpTsBindings\CodeGen\Utils\OutputDirectory;
use Le0daniel\PhpTsBindings\Server\KeyGenerators\PlainlyExposedKeyGenerator;
use Le0daniel\PhpTsBindings\Server\Operations\EagerlyLoadedOperationRegistry;
use Le0daniel\PhpTsBindings\Server\Server;

$server = new Server(
    EagerlyLoadedOperationRegistry::eagerlyDiscover(
        __DIR__ . '/app/Operations',
        keyGenerator: new PlainlyExposedKeyGenerator(),
    ),
);

$files = new TypescriptServerCodeGenerator(
    CodeGenerators::fromDefaults('name'),
)->generate($server, new ServerMetadata(
    '/query/{key}',
    '/command/{key}',
    $server->configuration,
));

OutputDirectory::write(__DIR__ . '/resources/js/operations', $files);

use Le0daniel\PhpTsBindings\Server\Client\NullClient;

// GET /query/{key}  — each query parameter JSON-decoded back into a value
$result = $server->query($key, $input, $myContext, new NullClient());

// POST /command/{key}  — the JSON body
$result = $server->command($key, $input, $myContext, new NullClient());

respondJson($result->statusCode, $result->jsonSerialize());

public function query(string $name, mixed $input, mixed $context, Client $client): RpcSuccess|RpcError
public function command(string $name, mixed $input, mixed $context, Client $client): RpcSuccess|RpcError

public function get(array $input, MyContext $context, Client $client): array

#[Command('users')]
#[Throws(InvalidNameException::class, name: 'invalid-name')]
public function create(array $input): array { /* ... */ }

json_encode([0 => $a, 1 => $b]);  // ["…","…"]   a JSON array
json_encode([1 => $a, 2 => $b]);  // {"1":…,"2":…}   a JSON object
json_encode([]);                  // []   an array, even for a type that is conceptually a map

/** @return array<int, User> */
public function active(): array
{
    return array_filter($this->users, fn (User $u) => $u->isActive());
}

/** @return array<int, User> */   →   Record<string, User>

/** @return array<'draft'|'live', int> */   →   Partial<Record<"draft"|"live", number>>
neon
# phpstan.neon
niel/php-ts-bindings/extension.neon