Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions generate.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,12 @@

$refresh = in_array('--refresh', $argv ?? [], true);

$setupHasRun = false;

foreach ($versions as $version) {
foreach ($versions as $version => $url) {
echo "Generating API namespace $version...\n";

$generator = new Webparking\Logic4Client\Generator\Generator();
$generator->setRefresh($refresh);
$generator->generate($version);
$generator->generate($version, $url);
}

echo 'API classes generated at '.now()->toDateTimeString()."...\n";
29 changes: 18 additions & 11 deletions generator/ComponentClassGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ public function resolve(string $name, string $namespace, string $version): strin
$typedParameters = [];
$arrayParameters = [];
$dateParameters = [];
$requiredProperties = $component->required ?? [];

foreach ($component->properties as $parameterName => $parameter) {
if ($parameter instanceof Reference) {
Expand Down Expand Up @@ -78,7 +79,9 @@ public function resolve(string $name, string $namespace, string $version): strin
}
}

$nullable = !\in_array($parameterName, ['Records', 'ValidationMessages'], true) && (($parameter->nullable ?? false) || class_exists($type));
$isRequired = \in_array($parameterName, $requiredProperties, true);
$nullable = !\in_array($parameterName, ['Records', 'ValidationMessages'], true)
&& (($parameter->nullable ?? false) || (class_exists($type) && !$isRequired));

$constructor
->addPromotedParameter($this->propertyName($parameterName))
Expand All @@ -90,30 +93,34 @@ public function resolve(string $name, string $namespace, string $version): strin
foreach ($component->properties as $property => $propertyObject) {
$constructorProperty = $constructor->getParameter($this->propertyName($property));

$isPropertyRequired = \in_array($property, $requiredProperties, true);
$default = $constructorProperty->isNullable()
? ' ?? null'
: match ($constructorProperty->getType()) {
'int' => ' ?? 0',
'float' => ' ?? 0.0',
'bool' => ' ?? false',
'string' => ' ?? \'\'',
'array' => ' ?? []',
default => ' ?? null',
};
: ($isPropertyRequired
? ''
: match ($constructorProperty->getType()) {
'int' => ' ?? 0',
'float' => ' ?? 0.0',
'bool' => ' ?? false',
'string' => ' ?? \'\'',
'array' => ' ?? []',
default => ' ?? null',
});

$assignment = null;
$assignmentValue = "\$data['$property']$default";
if ($typedParameter = $typedParameters[$property] ?? null) {
$assignment = "\\$typedParameter::make(\$data['$property'])";
} elseif ($arrayParameter = $arrayParameters[$property] ?? null) {
$assignmentValue = "array_map(static fn (array \$item) => \\$arrayParameter::make(\$item), \$data['$property'] ?? [])";
$arrayDefault = $isPropertyRequired ? '' : ' ?? []';
$assignmentValue = "array_map(static fn (array \$item) => \\$arrayParameter::make(\$item), \$data['$property']$arrayDefault)";
} elseif (\in_array($property, $dateParameters, true)) {
$assignment = \sprintf("\\%s::parse(\$data['%s'])", Carbon::class, $property);
}

if (null === $assignment) {
$assignment = $assignmentValue;
} else {
} elseif ($constructorProperty->isNullable()) {
$assignment = "isset(\$data['$property']) ? $assignment : null";
}

Expand Down
39 changes: 23 additions & 16 deletions generator/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@

class Generator
{
public static string $swaggerUrl = 'https://api.logic4server.nl/swagger/index.js';
public string $remoteApi = 'https://api.logic4server.nl/swagger/%s/swagger.json';
public static string $scalarUrl = 'https://api.logic4server.nl/scalar/';
public static string $baseUrl = 'https://api.logic4server.nl/';
public string $localApi = __DIR__.'/../logic4-api-%s.json';

public string $baseDirectory = __DIR__.'/../src/';
Expand All @@ -36,28 +36,36 @@ public function setup(): void
}
}

/** @return array<string> */
/** @return array<string, string> version => url */
public static function resolveVersions(): array
{
$contents = file_get_contents(self::$swaggerUrl);
$contents = file_get_contents(self::$scalarUrl);

Assert::string($contents, 'Could not fetch API documentation');

preg_match('/configObject = JSON.parse\(\'(.*)\'\);/', $contents, $matches);
preg_match('/initialize\([^,]+,\s*\w+,\s*(\{.+\})\s*,\s*\'/s', $contents, $matches);

$versions = json_decode($matches[1], true, 512, \JSON_THROW_ON_ERROR);
Assert::keyExists($matches, 1, 'Could not find Scalar configuration');

Assert::keyExists($versions, 'urls', 'Could not find API versions');
$config = json_decode($matches[1], true, 512, \JSON_THROW_ON_ERROR);

return array_diff(
array_map(static fn ($version) => explode('/', $version['url'], 2)[0], $versions['urls']),
['latest'],
);
Assert::keyExists($config, 'sources', 'Could not find API sources');

$versions = [];
foreach ($config['sources'] as $source) {
if (preg_match('/Version v(\d+\.\d+)/', $source['title'], $versionMatch)
&& !str_starts_with($versionMatch[1], '3.')
) {
$versions[$versionMatch[1]] = self::$baseUrl.$source['url'];
}
}

return $versions;
}

public function generate(string $version): void
public function generate(string $version, string $remoteUrl): void
{
$localFile = $this->downloadApiDocumentation($version);
$localFile = $this->downloadApiDocumentation($version, $remoteUrl);

$openapi = Reader::readFromJsonFile($localFile, resolveReferences: false);

Expand Down Expand Up @@ -96,17 +104,16 @@ public function generate(string $version): void
}
}

public function downloadApiDocumentation(string $version): string
public function downloadApiDocumentation(string $version, string $remoteUrl): string
{
$localFile = \sprintf($this->localApi, $this->getVersion($version));
$remoteFile = \sprintf($this->remoteApi, $version);

if ($this->refresh && is_file($localFile)) {
unlink($localFile);
}

if (!is_file($localFile)) {
file_put_contents($localFile, file_get_contents($remoteFile));
file_put_contents($localFile, file_get_contents($remoteUrl));
}

return $localFile;
Expand Down
10 changes: 7 additions & 3 deletions generator/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,10 @@ public static function resolveParameterType(Schema|Reference $property): string
}
} elseif ('object' === $property->type) {
$properties = [];
$requiredProps = $property->required ?? [];
foreach ($property->properties as $parameterName => $propertyValue) {
$properties[] = \sprintf('%s?: %s', $parameterName, self::resolveParameterType($propertyValue));
$separator = \in_array($parameterName, $requiredProps, true) ? ':' : '?:';
$properties[] = \sprintf('%s%s %s', $parameterName, $separator, self::resolveParameterType($propertyValue));
}

$type = \sprintf('array{%s}', implode(', ', $properties));
Expand All @@ -76,10 +78,11 @@ public static function resolveParameterType(Schema|Reference $property): string

/**
* @param Reference[]|Schema[] $properties
* @param string[] $required
*
* @return array<mixed>
*/
public static function makePhpDoc(array $properties, string $format): array
public static function makePhpDoc(array $properties, string $format, array $required = []): array
{
$parameters = [];
foreach ($properties as $name => $property) {
Expand All @@ -88,7 +91,8 @@ public static function makePhpDoc(array $properties, string $format): array
}

if ($property instanceof Schema) {
$parameters[] = \sprintf($format, \sprintf('%s?: %s', $name, self::resolveParameterType($property)));
$separator = \in_array($name, $required, true) ? ':' : '?:';
$parameters[] = \sprintf($format, \sprintf('%s%s %s', $name, $separator, self::resolveParameterType($property)));
}
}

Expand Down
24 changes: 17 additions & 7 deletions generator/RequestClassGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,25 +53,35 @@ public function addMethod(string $httpMethod, string $uri, Operation $operation,
$requestParameters['query'][$parameter->name] = \sprintf('{$%s}', $parameter->name);
}

$hasRequiredProps = false;

if ($requestSchema instanceof Reference
|| 'array' === $requestSchema?->type
) {
if ($requestSchema instanceof Reference) {
$requestProperties = $requestSchema->resolve()?->properties ?? [];
$parameterDoc = "array{\n".implode("\n", Helpers::makePhpDoc($requestProperties, ' %s,'))."\n}";
$resolvedSchema = $requestSchema->resolve();
$requestProperties = $resolvedSchema?->properties ?? [];
$requiredProps = $resolvedSchema?->required ?? [];
$hasRequiredProps = !empty($requiredProps);
$parameterDoc = "array{\n".implode("\n", Helpers::makePhpDoc($requestProperties, ' %s,', $requiredProps))."\n}";
} else {
if ($requestSchema->items instanceof Schema) {
$parameterDoc = "array<{$requestSchema->items->type}>";
} else {
$requestProperties = $requestSchema->items->resolve()->properties;
$resolvedItems = $requestSchema->items->resolve();
$requestProperties = $resolvedItems->properties;
$requiredProps = $resolvedItems->required ?? [];

$parameterDoc = "array<array{\n".implode("\n", Helpers::makePhpDoc($requestProperties, ' %s,'))."\n}>";
$parameterDoc = "array<array{\n".implode("\n", Helpers::makePhpDoc($requestProperties, ' %s,', $requiredProps))."\n}>";
}
}

$method->addParameter('parameters')
->setType('array')
->setDefaultValue([]);
$parameterProp = $method->addParameter('parameters')
->setType('array');

if (!$hasRequiredProps) {
$parameterProp->setDefaultValue([]);
}

$method
->addComment("@param $parameterDoc \$parameters");
Expand Down
2 changes: 1 addition & 1 deletion src/Data/V10/BuyOrderDeliveryRead.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public static function make(array $data): self
remarks: $data['Remarks'] ?? null,
description: $data['Description'] ?? null,
branchId: $data['BranchId'] ?? null,
rows: array_map(static fn (array $item) => BuyOrderDeliveryRowRead::make($item), $data['Rows'] ?? []),
rows: array_map(static fn (array $item) => BuyOrderDeliveryRowRead::make($item), $data['Rows']),
pickingListNumber: $data['PickingListNumber'] ?? null,
);
}
Expand Down
4 changes: 2 additions & 2 deletions src/Data/V10/CreditorThirdPartyExternalIdentifer.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ public function __construct(
public static function make(array $data): self
{
return new self(
creditorId: $data['CreditorId'] ?? 0,
typeId: $data['TypeId'] ?? 0,
creditorId: $data['CreditorId'],
typeId: $data['TypeId'],
value: $data['Value'] ?? null,
);
}
Expand Down
4 changes: 2 additions & 2 deletions src/Data/V10/CustomerThirdPartyExternalIdentifer.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ public function __construct(
public static function make(array $data): self
{
return new self(
debtorId: $data['DebtorId'] ?? 0,
typeId: $data['TypeId'] ?? 0,
debtorId: $data['DebtorId'],
typeId: $data['TypeId'],
value: $data['Value'] ?? null,
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Data/V10/EmailAttachment.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public static function make(array $data): self
{
return new self(
id: $data['Id'] ?? 0,
emailMessageId: $data['EmailMessageId'] ?? 0,
emailMessageId: $data['EmailMessageId'],
name: $data['Name'] ?? null,
contentId: $data['ContentId'] ?? null,
isEmbeddedContent: $data['IsEmbeddedContent'] ?? false,
Expand Down
2 changes: 1 addition & 1 deletion src/Data/V10/EmailMessage.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public static function make(array $data): self
isReplyedOn: isset($data['IsReplyedOn']) ? \Carbon\Carbon::parse($data['IsReplyedOn']) : null,
isForwardedOn: isset($data['IsForwardedOn']) ? \Carbon\Carbon::parse($data['IsForwardedOn']) : null,
status: isset($data['Status']) ? EmailMessageStatus::make($data['Status']) : null,
toEmailAddresses: array_map(static fn (array $item) => EmailAddress::make($item), $data['ToEmailAddresses'] ?? []),
toEmailAddresses: array_map(static fn (array $item) => EmailAddress::make($item), $data['ToEmailAddresses']),
fromEmailAddress: isset($data['FromEmailAddress']) ? EmailAddress::make($data['FromEmailAddress']) : null,
CCEmailAddresses: array_map(static fn (array $item) => EmailAddress::make($item), $data['CCEmailAddresses'] ?? []),
BCCEmailAddresses: array_map(static fn (array $item) => EmailAddress::make($item), $data['BCCEmailAddresses'] ?? []),
Expand Down
10 changes: 5 additions & 5 deletions src/Data/V10/HRMTimeRegistrationRow.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class HRMTimeRegistrationRow
public function __construct(
public int $userId,
public ?int $periodId,
public ?\Carbon\Carbon $date,
public \Carbon\Carbon $date,
public int $activityId,
public ?int $ITSTaskId,
public ?int $CRMProjectId,
Expand All @@ -27,15 +27,15 @@ public function __construct(
public static function make(array $data): self
{
return new self(
userId: $data['UserId'] ?? 0,
userId: $data['UserId'],
periodId: $data['PeriodId'] ?? null,
date: isset($data['Date']) ? \Carbon\Carbon::parse($data['Date']) : null,
activityId: $data['ActivityId'] ?? 0,
date: \Carbon\Carbon::parse($data['Date']),
activityId: $data['ActivityId'],
ITSTaskId: $data['ITSTaskId'] ?? null,
CRMProjectId: $data['CRMProjectId'] ?? null,
ITSIssueId: $data['ITSIssueId'] ?? null,
description: $data['Description'] ?? null,
minutes: $data['Minutes'] ?? 0,
minutes: $data['Minutes'],
createPeriod: $data['CreatePeriod'] ?? false,
periodeStatusId: $data['PeriodeStatusId'] ?? null,
rowIsAddedToPeriod: $data['RowIsAddedToPeriod'] ?? false,
Expand Down
6 changes: 3 additions & 3 deletions src/Data/V10/Order.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public function __construct(
public ?string $lastClickUtmValues,
public ?CustomerAddress $deliveryAddress,
public ?CustomerAddress $invoiceAddress,
public ?\Carbon\Carbon $creationDate,
public \Carbon\Carbon $creationDate,
public ?string $description,
public ?string $reference,
public ?int $branchId,
Expand Down Expand Up @@ -72,12 +72,12 @@ public static function make(array $data): self
payments: array_map(static fn (array $item) => Payment::make($item), $data['Payments'] ?? []),
costCentre: isset($data['CostCentre']) ? DebtorCostCentre::make($data['CostCentre']) : null,
accountAddress: isset($data['AccountAddress']) ? CustomerAddress::make($data['AccountAddress']) : null,
orderRows: array_map(static fn (array $item) => OrderRow::make($item), $data['OrderRows'] ?? []),
orderRows: array_map(static fn (array $item) => OrderRow::make($item), $data['OrderRows']),
lastClickGclIdValues: $data['LastClickGclIdValues'] ?? null,
lastClickUtmValues: $data['LastClickUtmValues'] ?? null,
deliveryAddress: isset($data['DeliveryAddress']) ? CustomerAddress::make($data['DeliveryAddress']) : null,
invoiceAddress: isset($data['InvoiceAddress']) ? CustomerAddress::make($data['InvoiceAddress']) : null,
creationDate: isset($data['CreationDate']) ? \Carbon\Carbon::parse($data['CreationDate']) : null,
creationDate: \Carbon\Carbon::parse($data['CreationDate']),
description: $data['Description'] ?? null,
reference: $data['Reference'] ?? null,
branchId: $data['BranchId'] ?? null,
Expand Down
6 changes: 3 additions & 3 deletions src/Data/V10/Payment.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ public static function make(array $data): self
orderId: $data['OrderId'] ?? null,
invoiceId: $data['InvoiceId'] ?? null,
amountIncl: $data['AmountIncl'] ?? 0.0,
description: $data['Description'] ?? '',
bookingId: $data['BookingId'] ?? 0,
matchingLedgerId: $data['MatchingLedgerId'] ?? 0,
description: $data['Description'],
bookingId: $data['BookingId'],
matchingLedgerId: $data['MatchingLedgerId'],
dateTime: isset($data['DateTime']) ? \Carbon\Carbon::parse($data['DateTime']) : null,
ledgerCode: $data['LedgerCode'] ?? null,
);
Expand Down
2 changes: 1 addition & 1 deletion src/Data/V10/ProductStockMutation.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public static function make(array $data): self
productId: $data['ProductId'] ?? 0,
amount: $data['Amount'] ?? 0.0,
remarks: $data['Remarks'] ?? null,
stockLocationId: $data['StockLocationId'] ?? 0,
stockLocationId: $data['StockLocationId'],
stockMutationTypeId: $data['StockMutationTypeId'] ?? 0,
);
}
Expand Down
6 changes: 3 additions & 3 deletions src/Data/V11/Order.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public function __construct(
public ?string $lastClickUtmValues,
public ?CustomerAddress $deliveryAddress,
public ?CustomerAddress $invoiceAddress,
public ?\Carbon\Carbon $creationDate,
public \Carbon\Carbon $creationDate,
public ?string $description,
public ?string $reference,
public ?int $branchId,
Expand Down Expand Up @@ -72,12 +72,12 @@ public static function make(array $data): self
payments: array_map(static fn (array $item) => Payment::make($item), $data['Payments'] ?? []),
costCentre: isset($data['CostCentre']) ? DebtorCostCentre::make($data['CostCentre']) : null,
accountAddress: isset($data['AccountAddress']) ? CustomerAddress::make($data['AccountAddress']) : null,
orderRows: array_map(static fn (array $item) => OrderRow::make($item), $data['OrderRows'] ?? []),
orderRows: array_map(static fn (array $item) => OrderRow::make($item), $data['OrderRows']),
lastClickGclIdValues: $data['LastClickGclIdValues'] ?? null,
lastClickUtmValues: $data['LastClickUtmValues'] ?? null,
deliveryAddress: isset($data['DeliveryAddress']) ? CustomerAddress::make($data['DeliveryAddress']) : null,
invoiceAddress: isset($data['InvoiceAddress']) ? CustomerAddress::make($data['InvoiceAddress']) : null,
creationDate: isset($data['CreationDate']) ? \Carbon\Carbon::parse($data['CreationDate']) : null,
creationDate: \Carbon\Carbon::parse($data['CreationDate']),
description: $data['Description'] ?? null,
reference: $data['Reference'] ?? null,
branchId: $data['BranchId'] ?? null,
Expand Down
6 changes: 3 additions & 3 deletions src/Data/V11/Payment.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ public static function make(array $data): self
orderId: $data['OrderId'] ?? null,
invoiceId: $data['InvoiceId'] ?? null,
amountIncl: $data['AmountIncl'] ?? 0.0,
description: $data['Description'] ?? '',
bookingId: $data['BookingId'] ?? 0,
matchingLedgerId: $data['MatchingLedgerId'] ?? 0,
description: $data['Description'],
bookingId: $data['BookingId'],
matchingLedgerId: $data['MatchingLedgerId'],
dateTime: isset($data['DateTime']) ? \Carbon\Carbon::parse($data['DateTime']) : null,
ledgerCode: $data['LedgerCode'] ?? null,
);
Expand Down
Loading