---
name: integrate-php-legacy-client
description: >
  Use the generated php-legacy client in a PHP 7.3/7.4 application that has no
  Composer. Covers loading src/ with RobotLoader or any PSR-4 loader, building
  the client with CurlTransport and Auth\ClientCredentials, the TokenStore
  choice (MemoryTokenStore vs FileTokenStore for short-lived processes),
  immutable models with fromArray/toArray, lenient enums, DateTimeImmutable,
  FilePart uploads, the exception hierarchy (ApiException::getErrorCode,
  TransportException, UnexpectedResponseException), and the --php-version 7.3|7.4,
  --namespace and --token-scope flags. Load when importing or using a client
  generated with -m php-legacy.
type: framework
library: openapi-client-generator
library_version: "3.0.0"
requires:
  - generate-client
sources:
  - "bazo/openapi-client-generator:src/modes/php-legacy/index.ts"
  - "bazo/openapi-client-generator:src/modes/php-legacy/client.ts"
  - "bazo/openapi-client-generator:src/modes/php-legacy/runtime.ts"
  - "bazo/openapi-client-generator:src/converter/schema-to-php-legacy.ts"
---

This skill builds on generate-client. Read it first for CLI usage.

# Integrate the PHP 7.3 (php-legacy) client

## Setup

Unlike every other mode, php-legacy writes **into the output directory itself**: a `README.md` and a `src/` tree.

```bash
openapi-client-generator spec/sync.openapi.json clients/php -n MedelySyncClient -m php-legacy \
  --namespace 'Medely\Client' --php-version 7.3
```

`--php-version` takes `7.3` (default) or `7.4`; 7.4 only adds typed properties. `--namespace` defaults to the client name. The generator removes nothing: delete `src/` before regenerating if a schema may have disappeared, or its stale model class stays.

Requirements: `ext-curl` and `ext-json`. No Composer, no packages. Load `src/` with Nette RobotLoader (or any PSR-4 loader mapping the namespace to `src/`):

```php
$loader = new Nette\Loaders\RobotLoader();
$loader->addDirectory(__DIR__ . '/clients/php/src');
$loader->setTempDirectory(__DIR__ . '/temp');
$loader->register();
```

## Core patterns

### Build the client

```php
use Medely\Client\Auth\ClientCredentials;
use Medely\Client\Auth\FileTokenStore;
use Medely\Client\Http\CurlTransport;
use Medely\Client\MedelySyncClient;

$client = new MedelySyncClient(
    new CurlTransport(),
    new ClientCredentials($clientId, $clientSecret, new FileTokenStore('/var/cache/my-app')),
    'https://api.medely.dev.healthpro.group'
);
```

The constructor is `(Transport $transport, ?Authenticator $authenticator, string $baseUrl)`; `$baseUrl` has a default only when the spec declares `servers`. `ClientCredentials` is handed the client's transport and base URL by the client itself (`Auth\TransportAware`), so you never pass either twice. The class exists when the spec declares an OAuth2 `clientCredentials` scheme, or has a `POST` operation whose path ends in `/token` (then pass `--token-scope` at generation time, or a scope to the constructor).

**Pick the token store on purpose.** `MemoryTokenStore` (the default) lives as long as the PHP process, which in php-fpm or cron is one request: every request would fetch a new token. `FileTokenStore` shares it between processes (files mode 0600; use a directory outside the web root). The token is cached until `expires_in` minus 60 seconds, and dropped and refetched once if the API answers 401.

### Call operations

Every operation is a method named by its `operationId`, taking path parameters first, then the body, then query/header parameters (optionals default to `null`):

```php
$doctor = $client->syncUpsertDoctor('r-1', new Model\UpsertDoctorRequest('Jana', 'Nova')); // Model\DoctorResponse
$page = $client->syncListRequests('pending', null, null, null, 1, 50);                     // positional: no named arguments on 7.3
$bytes = $client->getSyncRequestAttachmentContent($id, $attachmentId);                     // string (raw bytes)
$client->syncDeleteDoctor('r-1');                                                          // void for a 204
```

An operation with different success shapes per status (a 200 with a body and a 204 without) has no native return type and returns the model or `null`.

### Models

Immutable: private properties, getters only, constructor with 7.1 hints. `Model::fromArray($decoded)` throws `UnexpectedResponseException` for a missing required key or a wrong type; `$model->toArray()` returns only the declared fields under their wire names (the API rejects undeclared ones) and leaves out a `null` optional field. Date-times and dates are `\DateTimeImmutable`.

**Enums are lenient on purpose.** An enumerated property is a plain string (or int) holding whatever the API sent, so a value added later does not crash an old client. The `Model\<EnumName>` class is a constants holder with `values()` and `isKnown($value)`:

```php
if ($decision === Model\ListSyncRequestsQueryDecision::ACCEPTED) { ... }
```

### Errors

All extend `Exception\MedelyException` (a `\RuntimeException`):

```php
try {
    $client->syncGetDoctor('x');
} catch (ApiException $e) {
    $e->getStatusCode();       // 404
    $e->getErrorCode();        // the API's {"code": "..."} (or an OAuth2 "error"), null if neither
    $e->getBody();             // raw body
    $e->getResponseHeaders();  // lower-cased names
} catch (TransportException $e) {
    $e->getCurlErrno();        // cURL error number: no response at all
} catch (UnexpectedResponseException $e) {
    // the response does not match the contract, or is not JSON, or has an undocumented 2xx status
}
```

### Uploads

```php
use Medely\Client\Multipart\FilePart;

$client->syncCreateUpload(new Model\SyncCreateUploadMultipartFormDataRequest(
    $requestId,
    FilePart::fromString($bytes, 'scan.pdf', 'application/pdf') // or new FilePart('/path/to/file')
));
```

cURL uploads by path; `fromString()` writes a temp file that is deleted with the object. An array field in a multipart body goes out as `name[0]`, `name[1]`.

## Common mistakes

- Using named arguments or `fn`/`match` in code that calls the client: the client itself is plain 7.3, but the caller's runtime is too.
- Leaving the default `MemoryTokenStore` in a per-request PHP: one token fetch per request.
- Expecting a typed enum: compare against the constants, and treat an unknown value as possible.
- Passing a model's `toArray()` for a body: the client does that itself.
