Search by

uxf / gen

uxf

Package info

gitlab.com/uxf/gen

Issues

pkg:composer/uxf/gen

Statistics

Installs: 21 177

Dependents: 0

Suggesters: 0

Stars: 1

3.89.0 2026-11-15 15:54 UTC

README

Install

$ composer req uxf/gen

Run

$ bin/console uxf:gen

Config

// config/routes/uxf.php
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;

return static function (RoutingConfigurator $routingConfigurator): void {
    $routingConfigurator->import('@UXFGenBundle/config/routes.php');
};
// config/packages/uxf.php
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $containerConfigurator): void {
    $containerConfigurator->extension('uxf_gen', [
        'config' => [
            'prefix' => '/wow', // default '/api'
            // default config -> values from UXF bridge
            'disable_uxf_bridge' => false,
            'route_body_attribute' => FromBody::class,
            'route_query_attribute' => FromQuery::class,
            'route_header_attribute' => FromHeader::class,
            'route_entity_attribute' => Entity::class,
            'route_form_attribute' => FromForm::class,
            'ignored_types' => [NotSet::class],
            'enum_as_union' => true, // default false
            'typescript_types' => [
                'DateTime' => '`${number}-${number}-${number}T${number}:${number}:${number}+${number}:${number}`',
                'Date' => '`${number}-${number}-${number}`',
                'Time' => '`${number}:${number}:${number}`',
            ],
        ],
        'open_api' => [
            'areas' => [
                'app' => [
                    'path_pattern' => '/^\/api\/article/',
                ],
            ],
        ],
        'hook' => [
            'areas' => [
                'admin' => [
                    'path_pattern' => '/^\/api\/article/',
                    'output' => 'swr', // default legacy (options: swr, swr-2.2, legacy, empty, keys, fetch)
                    'with_enum_options' => true, // default false
                    'destination' => '%kernel.project_dir%/tests/generated/hook.ts', // or array
                    'prepends' => [
                        '/* eslint-disable */',
                        'import { useAxiosRequest, axiosRequest, RequestConfig } from "@lib/api";'
                    ],
                ],
            ],
        ],
        'apollo' => [
            'areas' => [
                'app' => [
                    'path_pattern' => '/^\/api\/article/',
                    'destination' => '%kernel.project_dir%/tests/generated/apollo.ts', // or array
                ],
            ],
        ],
    ]);
};

Output swr

const { data } = useArticleAllQuery(
    { query, skip: !isOpen },
    {
        fallbackData: [], // data: FunArticleResponse[] (without fallbackData / suspense: FunArticleResponse[] | undefined)
        onSuccess: (response) => {}, // response: FunArticleResponse[], no annotation needed
        onError: (error) => {}, // error: ApiError
    },
);
  • skip: true disables the request (SWR null key).
  • A custom key changes only the cache key, the request is always built from config (the fetcher ignores the key, so a SWR middleware changing the key does not change the request). E.g. key: [...pickArticleAllKey(config), offerIds] loads again when offerIds change.
  • Mutation hooks take any key: it is the cache key revalidated after the mutation, e.g. useArticleUpdateMutation({ path, key: pickArticleAllKey({ query }) }) reloads the article list.
  • Keep the query (e.g. datagrid filters) in the key, otherwise changing it does not load new data. To reload a list after a mutation for any query, revalidate all its keys with a matcher (SWR 2 passes the original key to it):
const { mutate } = useSWRConfig();
const listUrl = pickArticleAllKey({ query })[0];

const { trigger } = useArticleUpdateMutation(
    { path },
    { onSuccess: () => mutate((key) => Array.isArray(key) && key[0] === listUrl) },
);

Output fetch

Typed fetch functions without SWR (e.g. for a project using Apollo which sometimes calls REST). It is the swr output without hooks and SWR imports, so it also contains pick*Key functions from the keys output.

// GET /api/article
export const pickArticleAllKey = (config: { query: FunArticleRequestQuery }) => [`/api/article`, config.query] as const;
export const getArticleAll = (config: { query: FunArticleRequestQuery }): Promise<Array<FunArticleResponse>> => _fetch(_url(pickArticleAllKey(config)), 'GET', undefined);

// POST /api/article
export const pickArticleCreateKey = () => [`/api/article`] as const;
export const articleCreate = (config: { body: FunArticleRequestBody }): Promise<FunArticleResponse> => _fetch(pickArticleCreateKey()[0], 'POST', config.body);

Errors are thrown as ApiError. The default implementation calls fetch(_baseUrl + url), where the exported _baseUrl is process.env.API_URL, read once when the module is loaded (a bundler replacement via define works too). Without process (e.g. Vite in the browser without define) or without API_URL it is "", so the relative URL (/api/...) on the same origin is called. _baseUrl can also be used for absolute URLs, e.g. _baseUrl + _url(pickExportKey(config)).

To replace the default implementation (e.g. to add an auth header), provide _customFetch(url, method, body) with the same signature as _defaultFetch, preferably through prepends (same as in the swr output):

'prepends' => ['import { myFetch as _customFetch } from "@lib/api";'],

The generated file declares declare global { var _customFetch: any; }, so a global _customFetch works too and more generated files (e.g. admin swr + public fetch) can live in one TypeScript project. Your own global declaration of _customFetch must also be var _customFetch: any, another type fails with TS2403.

Example

PersonRequestBody.php

InspectorPlugin

use UXF\Gen\Inspector\Schema\AppSchema;
use UXF\Gen\Inspector\Schema\RouteSchema;
use UXF\Gen\Inspector\Schema\TypeSchema;
use UXF\Gen\Inspector\Schema\TypeVariant;
use UXF\Gen\Inspector\TypeMap;
use UXF\Gen\Plugin\InspectorPluginInterface;
use UXF\GenTests\Project\FunZone\Entity\EntityNames;

class TestPlugin implements InspectorPluginInterface
{
    public function pre(string $configName, TypeMap $typeMap): void
    {
        if ($configName === 'hook') {
            $typeMap->add(new TypeSchema(EntityNames::class, TypeVariant::ENUM, EntityNames::class, onlyWhenUsed: false));
        }
    }

    public function post(string $configName, AppSchema $appSchema): void
    {
        if ($configName === 'apollo') {
            $appSchema->routes['plugin'] = new RouteSchema(
                name: 'plugin',
                path: '/plugin',
                controller: 'FunZone\Ok',
                requestBody: null,
                requestQuery: null,
                pathParams: [],
                response: null,
                description: '',
                methods: ['get' => false],
            );
        }
    }
}

Types used by routes only

Only types used by a route (body, query, headers, path params, response) and everything they reference are generated. This is decided by TypeSchema::$onlyWhenUsed:

  • onlyWhenUsed: true (default): the type is generated only when a route uses it. This applies to types found by the inspector, built-in scalars, UXF\Core\Type\Money and UXF\Core\Type\Currency.
  • onlyWhenUsed: false: the type is always generated, even when no route uses it, together with everything it references. Use it for types you add manually in InspectorPlugin::pre(), like EntityNames above.

To always generate a built-in type, change it in your plugin (it runs after the built-in one):

public function pre(string $configName, TypeMap $typeMap): void
{
    $typeMap->getStrict(Currency::class)->onlyWhenUsed = false;
}

The keys output follows the same rule, it just starts from the query and path params of routes only.

ConverterPlugin

use UXF\Core\Type\Date;
use UXF\Core\Type\DateTime;
use UXF\Core\Type\Time;
use UXF\Gen\Inspector\Schema\TypeSchema;
use UXF\Gen\Inspector\Schema\TypeVariant;
use UXF\Gen\Plugin\TypeConverterPlugin;

class UxfCoreTypeConverterPlugin implements TypeConverterPlugin
{
    public function convertToTypescript(TypeSchema $typeSchema): ?string
    {
        if (
            $typeSchema->variant === TypeVariant::SIMPLE &&
            in_array($typeSchema->name, [Date::class, DateTime::class, Time::class], true)
        ) {
            return 'string';
        }

        return null;
    }

    /**
     * @inheritDoc
     */
    public function convertToOpenApi(TypeSchema $typeSchema): ?array
    {
        if ($typeSchema->variant !== TypeVariant::SIMPLE) {
            return null;
        }

        return match ($typeSchema->name) {
            Date::class => [
                'type' => 'string',
                'format' => 'date',
            ],
            DateTime::class => [
                'type' => 'string',
                'format' => 'date-time',
            ],
            Time::class => [
                'type' => 'string',
                'pattern' => '^\d{2}:\d{2}:\d{2}$',
            ],
            default => null,
        };
    }
}

Description support

class TestController
{
    /**
     * PRIVATE INTERNAL DESCRIPTION (MUST BE BEFORE @description)
     *
     * @description Public hello world description
     * with multiline support bro!
     */
    public function __invoke(): StatusResponse
    {
        return new StatusResponse();
    }
}