Don't use named parameters in code

This commit is contained in:
Sebastian Meyer 2024-10-14 14:51:42 +02:00
parent 97fee92f63
commit 396f8dc9e0
36 changed files with 533 additions and 704 deletions

View File

@ -31,8 +31,8 @@
"ext-dom": "*",
"ext-libxml": "*",
"ext-sqlite3": "*",
"doctrine/dbal": "^4.1",
"doctrine/orm": "^3.2",
"doctrine/dbal": "^4.2",
"doctrine/orm": "^3.3",
"opencultureconsulting/basics": "^2.1",
"opencultureconsulting/psr15": "^1.2",
"symfony/cache": "^6.4",

53
composer.lock generated
View File

@ -94,16 +94,16 @@
},
{
"name": "doctrine/dbal",
"version": "4.1.1",
"version": "4.2.1",
"source": {
"type": "git",
"url": "https://github.com/doctrine/dbal.git",
"reference": "7a8252418689feb860ea8dfeab66d64a56a64df8"
"reference": "dadd35300837a3a2184bd47d403333b15d0a9bd0"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/doctrine/dbal/zipball/7a8252418689feb860ea8dfeab66d64a56a64df8",
"reference": "7a8252418689feb860ea8dfeab66d64a56a64df8",
"url": "https://api.github.com/repos/doctrine/dbal/zipball/dadd35300837a3a2184bd47d403333b15d0a9bd0",
"reference": "dadd35300837a3a2184bd47d403333b15d0a9bd0",
"shasum": ""
},
"require": {
@ -116,7 +116,7 @@
"doctrine/coding-standard": "12.0.0",
"fig/log-test": "^1",
"jetbrains/phpstorm-stubs": "2023.2",
"phpstan/phpstan": "1.12.0",
"phpstan/phpstan": "1.12.6",
"phpstan/phpstan-phpunit": "1.4.0",
"phpstan/phpstan-strict-rules": "^1.6",
"phpunit/phpunit": "10.5.30",
@ -182,7 +182,7 @@
],
"support": {
"issues": "https://github.com/doctrine/dbal/issues",
"source": "https://github.com/doctrine/dbal/tree/4.1.1"
"source": "https://github.com/doctrine/dbal/tree/4.2.1"
},
"funding": [
{
@ -198,7 +198,7 @@
"type": "tidelift"
}
],
"time": "2024-09-03T08:58:39+00:00"
"time": "2024-10-10T18:01:27+00:00"
},
{
"name": "doctrine/deprecations",
@ -578,16 +578,16 @@
},
{
"name": "doctrine/orm",
"version": "3.2.2",
"version": "3.3.0",
"source": {
"type": "git",
"url": "https://github.com/doctrine/orm.git",
"reference": "831a1eb7d260925528cdbb49cc1866c0357cf147"
"reference": "69958152e661aa9c14e80d1ee4962863485aa60b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/doctrine/orm/zipball/831a1eb7d260925528cdbb49cc1866c0357cf147",
"reference": "831a1eb7d260925528cdbb49cc1866c0357cf147",
"url": "https://api.github.com/repos/doctrine/orm/zipball/69958152e661aa9c14e80d1ee4962863485aa60b",
"reference": "69958152e661aa9c14e80d1ee4962863485aa60b",
"shasum": ""
},
"require": {
@ -609,7 +609,10 @@
"require-dev": {
"doctrine/coding-standard": "^12.0",
"phpbench/phpbench": "^1.0",
"phpstan/phpstan": "1.11.1",
"phpdocumentor/guides-cli": "^1.4",
"phpstan/extension-installer": "^1.4",
"phpstan/phpstan": "1.12.6",
"phpstan/phpstan-deprecation-rules": "^1.2",
"phpunit/phpunit": "^10.4.0",
"psr/log": "^1 || ^2 || ^3",
"squizlabs/php_codesniffer": "3.7.2",
@ -660,9 +663,9 @@
],
"support": {
"issues": "https://github.com/doctrine/orm/issues",
"source": "https://github.com/doctrine/orm/tree/3.2.2"
"source": "https://github.com/doctrine/orm/tree/3.3.0"
},
"time": "2024-08-23T10:03:52+00:00"
"time": "2024-10-12T20:07:18+00:00"
},
{
"name": "doctrine/persistence",
@ -4225,16 +4228,16 @@
},
{
"name": "phpstan/phpdoc-parser",
"version": "1.32.0",
"version": "1.33.0",
"source": {
"type": "git",
"url": "https://github.com/phpstan/phpdoc-parser.git",
"reference": "6ca22b154efdd9e3c68c56f5d94670920a1c19a4"
"reference": "82a311fd3690fb2bf7b64d5c98f912b3dd746140"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpstan/phpdoc-parser/zipball/6ca22b154efdd9e3c68c56f5d94670920a1c19a4",
"reference": "6ca22b154efdd9e3c68c56f5d94670920a1c19a4",
"url": "https://api.github.com/repos/phpstan/phpdoc-parser/zipball/82a311fd3690fb2bf7b64d5c98f912b3dd746140",
"reference": "82a311fd3690fb2bf7b64d5c98f912b3dd746140",
"shasum": ""
},
"require": {
@ -4266,22 +4269,22 @@
"description": "PHPDoc parser with support for nullable, intersection and generic types",
"support": {
"issues": "https://github.com/phpstan/phpdoc-parser/issues",
"source": "https://github.com/phpstan/phpdoc-parser/tree/1.32.0"
"source": "https://github.com/phpstan/phpdoc-parser/tree/1.33.0"
},
"time": "2024-09-26T07:23:32+00:00"
"time": "2024-10-13T11:25:22+00:00"
},
{
"name": "phpstan/phpstan",
"version": "1.12.5",
"version": "1.12.6",
"source": {
"type": "git",
"url": "https://github.com/phpstan/phpstan.git",
"reference": "7e6c6cb7cecb0a6254009a1a8a7d54ec99812b17"
"reference": "dc4d2f145a88ea7141ae698effd64d9df46527ae"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/7e6c6cb7cecb0a6254009a1a8a7d54ec99812b17",
"reference": "7e6c6cb7cecb0a6254009a1a8a7d54ec99812b17",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/dc4d2f145a88ea7141ae698effd64d9df46527ae",
"reference": "dc4d2f145a88ea7141ae698effd64d9df46527ae",
"shasum": ""
},
"require": {
@ -4326,7 +4329,7 @@
"type": "github"
}
],
"time": "2024-09-26T12:45:22+00:00"
"time": "2024-10-06T15:03:59+00:00"
},
{
"name": "phpstan/phpstan-doctrine",

View File

@ -43,7 +43,7 @@ final class App
*/
public function __construct()
{
$this->requestHandler = new QueueRequestHandler(middlewares: [new Dispatcher()]);
$this->requestHandler = new QueueRequestHandler([new Dispatcher()]);
}
/**

View File

@ -72,22 +72,20 @@ final class Configuration
*/
private function __construct()
{
$configPath = Path::canonicalize(path: self::CONFIG_FILE);
if (!is_readable(filename: $configPath)) {
$configPath = Path::canonicalize(self::CONFIG_FILE);
if (!is_readable($configPath)) {
throw new FileNotFoundException(
message: 'Configuration file not found or not readable.',
code: 500,
path: $configPath
'Configuration file not found or not readable.',
500,
null,
$configPath
);
}
/** @var array<TKey, TValue> */
$config = Yaml::parseFile(filename: $configPath);
$violations = ConfigurationValidator::validate(config: $config);
$config = Yaml::parseFile($configPath);
$violations = ConfigurationValidator::validate($config);
if ($violations->count() > 0) {
throw new ValidationFailedException(
value: null,
violations: $violations
);
throw new ValidationFailedException(null, $violations);
}
$this->settings = $config;
}

View File

@ -91,13 +91,11 @@ abstract class Console extends Command
/** @var Application */
$app = $this->getApplication();
$app->doRun(
input: new ArrayInput(
parameters: [
new ArrayInput([
'command' => 'orm:clear-cache:result',
'--flush' => true
]
),
output: new NullOutput()
]),
new NullOutput()
);
}
@ -109,7 +107,7 @@ abstract class Console extends Command
protected function getPhpMemoryLimit(): int
{
if (!isset($this->memoryLimit)) {
$ini = trim(string: ini_get(option: 'memory_limit'));
$ini = trim(ini_get('memory_limit'));
$limit = (int) $ini;
if ($limit < 0) {
return -1;
@ -146,47 +144,41 @@ abstract class Console extends Command
if (array_key_exists('format', $this->arguments)) {
$formats = $this->em->getMetadataFormats();
if (!$formats->containsKey(key: $this->arguments['format'])) {
$output->writeln(
messages: [
if (!$formats->containsKey($this->arguments['format'])) {
$output->writeln([
'',
sprintf(
format: ' [ERROR] Metadata format "%s" is not supported. ',
values: $this->arguments['format']
' [ERROR] Metadata format "%s" is not supported. ',
$this->arguments['format']
),
''
]
);
]);
return false;
}
}
if (array_key_exists('file', $this->arguments) && !is_readable(filename: $this->arguments['file'])) {
$output->writeln(
messages: [
if (array_key_exists('file', $this->arguments) && !is_readable($this->arguments['file'])) {
$output->writeln([
'',
sprintf(
format: ' [ERROR] File "%s" not found or not readable. ',
values: $this->arguments['file']
' [ERROR] File "%s" not found or not readable. ',
$this->arguments['file']
),
''
]
);
]);
return false;
}
if (array_key_exists('sets', $this->arguments)) {
$sets = $this->em->getSets();
$invalidSets = array_diff($this->arguments['sets'], $sets->getKeys());
if (count($invalidSets) !== 0) {
$output->writeln(
messages: [
$output->writeln([
'',
sprintf(
format: ' [ERROR] Sets "%s" are not supported. ',
values: implode('", "', $invalidSets)
' [ERROR] Sets "%s" are not supported. ',
implode('", "', $invalidSets)
),
''
]
);
]);
return false;
}
}

View File

@ -84,30 +84,27 @@ class AddRecordCommand extends Console
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
if (!$this->validateInput(input: $input, output: $output)) {
if (!$this->validateInput($input, $output)) {
return Command::INVALID;
}
/** @var Format */
$format = $this->em->getMetadataFormat(prefix: $this->arguments['format']);
$content = file_get_contents(filename: $this->arguments['file']) ?: '';
$format = $this->em->getMetadataFormat($this->arguments['format']);
$content = file_get_contents($this->arguments['file']) ?: '';
$record = new Record(
identifier: $this->arguments['identifier'],
format: $format
);
$record = new Record($this->arguments['identifier'], $format);
if (trim($content) !== '') {
$record->setContent(data: $content);
$record->setContent($content);
}
if (array_key_exists('sets', $this->arguments)) {
foreach ($this->arguments['sets'] as $set) {
/** @var Set */
$setSpec = $this->em->getSet(spec: $set);
$record->addSet(set: $setSpec);
$setSpec = $this->em->getSet($set);
$record->addSet($setSpec);
}
}
$this->em->addOrUpdate(entity: $record);
$this->em->addOrUpdate($record);
$this->em->pruneOrphanedSets();
$this->clearResultCache();

View File

@ -81,20 +81,16 @@ class AddSetCommand extends Console
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
if (!$this->validateInput(input: $input, output: $output)) {
if (!$this->validateInput($input, $output)) {
return Command::INVALID;
}
if (array_key_exists('file', $this->arguments)) {
$description = file_get_contents(filename: $this->arguments['file']) ?: null;
$description = file_get_contents($this->arguments['file']) ?: null;
}
$set = new Set(
spec: $this->arguments['setSpec'],
name: $this->arguments['setName'],
description: $description ?? null
);
$this->em->addOrUpdate(entity: $set);
$set = new Set($this->arguments['setSpec'], $this->arguments['setName'], $description ?? null);
$this->em->addOrUpdate($set);
return Command::SUCCESS;
}

View File

@ -122,14 +122,14 @@ class CsvImportCommand extends Console
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
if (!$this->validateInput(input: $input, output: $output)) {
if (!$this->validateInput($input, $output)) {
return Command::INVALID;
}
/** @var resource */
$file = fopen(filename: $this->arguments['file'], mode: 'r');
$file = fopen($this->arguments['file'], 'r');
$columnMapping = $this->getColumnNames(input: $input, output: $output, file: $file);
$columnMapping = $this->getColumnNames($input, $output, $file);
if (!isset($columnMapping)) {
return Command::FAILURE;
@ -139,31 +139,25 @@ class CsvImportCommand extends Console
$progressIndicator = new ProgressIndicator($output, null, 100, ['⠏', '⠛', '⠹', '⢸', '⣰', '⣤', '⣆', '⡇']);
$progressIndicator->start('Importing...');
while ($row = fgetcsv(stream: $file)) {
while ($row = fgetcsv($file)) {
/** @var Format */
$format = $this->em->getMetadataFormat(prefix: $this->arguments['format']);
$record = new Record(
identifier: $row[$columnMapping['idColumn']],
format: $format
);
$format = $this->em->getMetadataFormat($this->arguments['format']);
$record = new Record($row[$columnMapping['idColumn']], $format);
if (strlen(trim($row[$columnMapping['contentColumn']])) > 0) {
$record->setContent(
data: $row[$columnMapping['contentColumn']],
validate: !$this->arguments['noValidation']
);
$record->setContent($row[$columnMapping['contentColumn']], !$this->arguments['noValidation']);
}
if (isset($columnMapping['dateColumn'])) {
$record->setLastChanged(dateTime: new DateTime($row[$columnMapping['dateColumn']]));
$record->setLastChanged(new DateTime($row[$columnMapping['dateColumn']]));
}
if (isset($columnMapping['setColumn'])) {
$sets = $row[$columnMapping['setColumn']];
foreach (explode(',', $sets) as $set) {
/** @var Set */
$setSpec = $this->em->getSet(spec: trim($set));
$record->addSet(set: $setSpec);
$setSpec = $this->em->getSet(trim($set));
$record->addSet($setSpec);
}
}
$this->em->addOrUpdate(entity: $record, bulkMode: true);
$this->em->addOrUpdate($record, true);
++$count;
$progressIndicator->advance();
@ -175,7 +169,7 @@ class CsvImportCommand extends Console
$progressIndicator->finish('All done!');
fclose(stream: $file);
fclose($file);
$this->clearResultCache();
@ -215,9 +209,9 @@ class CsvImportCommand extends Console
$output->writeln([
'',
sprintf(
format: ' [ERROR] File "%s" does not contain valid CSV. ',
' [ERROR] File "%s" does not contain valid CSV. ',
/** @phpstan-ignore-next-line - URI is always set for fopen() resources. */
values: stream_get_meta_data(stream: $file)['uri'] ?: 'unknown'
stream_get_meta_data($file)['uri'] ?: 'unknown'
),
''
]);
@ -236,9 +230,9 @@ class CsvImportCommand extends Console
$output->writeln([
'',
sprintf(
format: ' [ERROR] File "%s" does not contain mandatory columns. ',
' [ERROR] File "%s" does not contain mandatory columns. ',
/** @phpstan-ignore-next-line - URI is always set for fopen() resources. */
values: stream_get_meta_data($file)['uri'] ?: 'unknown'
stream_get_meta_data($file)['uri'] ?: 'unknown'
),
''
]);

View File

@ -71,17 +71,14 @@ class DeleteRecordCommand extends Console
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
if (!$this->validateInput(input: $input, output: $output)) {
if (!$this->validateInput($input, $output)) {
return Command::INVALID;
}
$record = $this->em->getRecord(
identifier: $this->arguments['identifier'],
format: $this->arguments['format']
);
$record = $this->em->getRecord($this->arguments['identifier'], $this->arguments['format']);
if (isset($record)) {
$this->em->delete(entity: $record);
$this->em->delete($record);
$this->clearResultCache();
$output->writeln([
'',

View File

@ -79,8 +79,8 @@ class PruneDeletedRecordsCommand extends Console
$output->writeln([
'',
sprintf(
format: ' [OK] %d deleted records were successfully removed! ',
values: $deleted
' [OK] %d deleted records were successfully removed! ',
$deleted
),
''
]);

View File

@ -54,8 +54,8 @@ class PruneResumptionTokensCommand extends Console
$output->writeln([
'',
sprintf(
format: ' [OK] %d expired resumption tokens were successfully deleted! ',
values: $expired
' [OK] %d expired resumption tokens were successfully deleted! ',
$expired
),
''
]);

View File

@ -69,24 +69,20 @@ class UpdateFormatsCommand extends Console
continue;
}
try {
$format = new Format(
prefix: $prefix,
namespace: $format['namespace'],
schema: $format['schema']
);
$this->em->addOrUpdate(entity: $format);
$format = new Format($prefix, $format['namespace'], $format['schema']);
$this->em->addOrUpdate($format);
$output->writeln([
sprintf(
format: ' [OK] Metadata format "%s" added or updated successfully! ',
values: $prefix
' [OK] Metadata format "%s" added or updated successfully! ',
$prefix
)
]);
} catch (ValidationFailedException $exception) {
$failure = true;
$output->writeln([
sprintf(
format: ' [ERROR] Could not add or update metadata format "%s". ',
values: $prefix
' [ERROR] Could not add or update metadata format "%s". ',
$prefix
),
$exception->getMessage()
]);
@ -95,11 +91,11 @@ class UpdateFormatsCommand extends Console
foreach (array_diff($inDatabase->getKeys(), array_keys($formats)) as $prefix) {
/** @var Format */
$format = $inDatabase[$prefix];
$this->em->delete(entity: $format);
$this->em->delete($format);
$output->writeln([
sprintf(
format: ' [OK] Metadata format "%s" and all associated records deleted successfully! ',
values: $prefix
' [OK] Metadata format "%s" and all associated records deleted successfully! ',
$prefix
)
]);
}

View File

@ -46,13 +46,10 @@ abstract class Entity
*/
protected function validateUrl(string $url): string
{
$url = trim(string: $url);
$violations = UrlValidator::validate(url: $url);
$url = trim($url);
$violations = UrlValidator::validate($url);
if ($violations->count() > 0) {
throw new ValidationFailedException(
value: null,
violations: $violations
);
throw new ValidationFailedException(null, $violations);
}
return $url;
}
@ -69,12 +66,9 @@ abstract class Entity
*/
protected function validateRegEx(string $string, string $regEx): string
{
$violations = RegExValidator::validate(string: $string, regEx: $regEx);
$violations = RegExValidator::validate($string, $regEx);
if ($violations->count() > 0) {
throw new ValidationFailedException(
value: null,
violations: $violations
);
throw new ValidationFailedException(null, $violations);
}
return $string;
}
@ -90,12 +84,9 @@ abstract class Entity
*/
protected function validateXml(string $xml): string
{
$violations = XmlValidator::validate(xml: $xml);
$violations = XmlValidator::validate($xml);
if ($violations->count() > 0) {
throw new ValidationFailedException(
value: null,
violations: $violations
);
throw new ValidationFailedException(null, $violations);
}
return $xml;
}

View File

@ -124,7 +124,7 @@ final class Format extends Entity
public function setNamespace(string $namespace): void
{
try {
$this->namespace = $this->validateUrl(url: $namespace);
$this->namespace = $this->validateUrl($namespace);
} catch (ValidationFailedException $exception) {
throw $exception;
}
@ -142,7 +142,7 @@ final class Format extends Entity
public function setSchema(string $schema): void
{
try {
$this->xmlSchema = $this->validateUrl(url: $schema);
$this->xmlSchema = $this->validateUrl($schema);
} catch (ValidationFailedException $exception) {
throw $exception;
}
@ -160,12 +160,9 @@ final class Format extends Entity
public function __construct(string $prefix, string $namespace, string $schema)
{
try {
$this->prefix = $this->validateRegEx(
string: $prefix,
regEx: '/^[A-Za-z0-9\-_\.!~\*\'\(\)]+$/'
);
$this->setNamespace(namespace: $namespace);
$this->setSchema(schema: $schema);
$this->prefix = $this->validateRegEx($prefix, '/^[A-Za-z0-9\-_\.!~\*\'\(\)]+$/');
$this->setNamespace($namespace);
$this->setSchema($schema);
$this->records = new ArrayCollection();
} catch (ValidationFailedException $exception) {
throw $exception;

View File

@ -106,9 +106,9 @@ final class Record extends Entity
*/
public function addSet(Set $set): void
{
if (!$this->sets->contains(element: $set)) {
$this->sets->add(element: $set);
$set->addRecord(record: $this);
if (!$this->sets->contains($set)) {
$this->sets->add($set);
$set->addRecord($this);
}
}
@ -161,7 +161,7 @@ final class Record extends Entity
*/
public function getSet(string $setSpec): ?Set
{
return $this->sets->get(key: $setSpec);
return $this->sets->get($setSpec);
}
/**
@ -196,9 +196,9 @@ final class Record extends Entity
*/
public function removeSet(Set $set): void
{
if ($this->sets->contains(element: $set)) {
$this->sets->removeElement(element: $set);
$set->removeRecord(record: $this);
if ($this->sets->contains($set)) {
$this->sets->removeElement($set);
$set->removeRecord($this);
}
}
@ -218,7 +218,7 @@ final class Record extends Entity
$data = trim($data);
if ($validate) {
try {
$data = $this->validateXml(xml: $data);
$data = $this->validateXml($data);
} catch (ValidationFailedException $exception) {
throw $exception;
}
@ -268,13 +268,13 @@ final class Record extends Entity
{
try {
$this->identifier = $this->validateRegEx(
string: $identifier,
$identifier,
// xs:anyURI
regEx: '/^(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?\/{0,2}[0-9a-zA-Z;\/?:@&=+$\\.\\-_!~*\'()%]+)?(#[0-9a-zA-Z;\/?:@&=+$\\.\\-_!~*\'()%]+)?$/'
'/^(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?\/{0,2}[0-9a-zA-Z;\/?:@&=+$\\.\\-_!~*\'()%]+)?(#[0-9a-zA-Z;\/?:@&=+$\\.\\-_!~*\'()%]+)?$/'
);
$this->setFormat(format: $format);
$this->setContent(data: $data);
$this->setLastChanged(dateTime: $lastChanged);
$this->setFormat($format);
$this->setContent($data);
$this->setLastChanged($lastChanged);
$this->sets = new ArrayCollection();
} catch (ValidationFailedException $exception) {
throw $exception;

View File

@ -80,9 +80,9 @@ final class Set extends Entity
*/
public function addRecord(Record $record): void
{
if (!$this->records->contains(element: $record)) {
$this->records->add(element: $record);
$record->addSet(set: $this);
if (!$this->records->contains($record)) {
$this->records->add($record);
$record->addSet($this);
}
}
@ -158,9 +158,9 @@ final class Set extends Entity
*/
public function removeRecord(Record $record): void
{
if ($this->records->contains(element: $record)) {
$this->records->removeElement(element: $record);
$record->removeSet(set: $this);
if ($this->records->contains($record)) {
$this->records->removeElement($record);
$record->removeSet($this);
}
}
@ -178,7 +178,7 @@ final class Set extends Entity
if (isset($description)) {
$description = trim($description);
try {
$description = $this->validateXml(xml: $description);
$description = $this->validateXml($description);
} catch (ValidationFailedException $exception) {
throw $exception;
}
@ -211,11 +211,11 @@ final class Set extends Entity
{
try {
$this->spec = $this->validateRegEx(
string: $spec,
regEx: '/^([A-Za-z0-9\-_\.!~\*\'\(\)])+(:[A-Za-z0-9\-_\.!~\*\'\(\)]+)*$/'
$spec,
'/^([A-Za-z0-9\-_\.!~\*\'\(\)])+(:[A-Za-z0-9\-_\.!~\*\'\(\)]+)*$/'
);
$this->setName(name: $name);
$this->setDescription(description: $description);
$this->setName($name);
$this->setDescription($description);
$this->records = new ArrayCollection();
} catch (ValidationFailedException $exception) {
throw $exception;

View File

@ -120,7 +120,7 @@ final class Token extends Entity
$this->verb = $verb;
$this->parameters = serialize($parameters);
$validUntil = new DateTime();
$validUntil->add(interval: new DateInterval(duration: 'PT' . Configuration::getInstance()->tokenValid . 'S'));
$validUntil->add(new DateInterval('PT' . Configuration::getInstance()->tokenValid . 'S'));
$this->validUntil = $validUntil;
}
}

View File

@ -80,7 +80,7 @@ final class EntityManager extends EntityManagerDecorator
*/
public function addOrUpdate(Format|Record|Set|Token $entity, bool $bulkMode = false): void
{
$this->getRepository(className: get_class($entity))->addOrUpdate(entity: $entity);
$this->getRepository(get_class($entity))->addOrUpdate($entity);
if (!$bulkMode) {
$this->flush();
}
@ -95,7 +95,7 @@ final class EntityManager extends EntityManagerDecorator
*/
public function delete(Format|Record|Set|Token $entity): void
{
$this->getRepository(className: get_class($entity))->delete(entity: $entity);
$this->getRepository(get_class($entity))->delete($entity);
}
/**
@ -107,11 +107,11 @@ final class EntityManager extends EntityManagerDecorator
{
$timestamp = '0000-00-00T00:00:00Z';
$dql = $this->createQueryBuilder();
$dql->select(select: $dql->expr()->min('record.lastChanged'));
$dql->from(from: Record::class, alias: 'record');
$dql->select($dql->expr()->min('record.lastChanged'));
$dql->from(Record::class, 'record');
$query = $dql->getQuery()->enableResultCache();
/** @var ?string $result */
$result = $query->getOneOrNullResult(hydrationMode: AbstractQuery::HYDRATE_SCALAR_COLUMN);
$result = $query->getOneOrNullResult(AbstractQuery::HYDRATE_SCALAR_COLUMN);
return $result ?? $timestamp;
}
@ -124,7 +124,7 @@ final class EntityManager extends EntityManagerDecorator
*/
public function getMetadataFormat(string $prefix): ?Format
{
return $this->getReference(entityName: Format::class, id: $prefix);
return $this->getReference(Format::class, $prefix);
}
/**
@ -138,21 +138,21 @@ final class EntityManager extends EntityManagerDecorator
{
$entities = [];
if ($recordIdentifier === null) {
$formats = $this->getRepository(className: Format::class)->findAll();
$formats = $this->getRepository(Format::class)->findAll();
} else {
$dql = $this->createQueryBuilder();
$dql->select(select: 'record.format')
->from(from: Record::class, alias: 'record')
->where(predicates: $dql->expr()->eq('record.identifier', ':recordIdentifier'))
->setParameter(key: 'recordIdentifier', value: $recordIdentifier);
$dql->select('record.format')
->from(Record::class, 'record')
->where($dql->expr()->eq('record.identifier', ':recordIdentifier'))
->setParameter('recordIdentifier', $recordIdentifier);
$query = $dql->getQuery()->enableResultCache();
/** @var Format[] */
$formats = $query->getResult(hydrationMode: AbstractQuery::HYDRATE_OBJECT);
$formats = $query->getResult(AbstractQuery::HYDRATE_OBJECT);
}
foreach ($formats as $format) {
$entities[$format->getPrefix()] = $format;
}
return new ResultSet(elements: $entities);
return new ResultSet($entities);
}
/**
@ -165,12 +165,10 @@ final class EntityManager extends EntityManagerDecorator
*/
public function getRecord(string $identifier, string $format): ?Record
{
return $this->getRepository(className: Record::class)->findOneBy(
criteria: [
return $this->getRepository(Record::class)->findOneBy([
'identifier' => $identifier,
'format' => $this->getMetadataFormat(prefix: $format)
]
);
'format' => $this->getMetadataFormat($format)
]);
}
/**
@ -198,45 +196,42 @@ final class EntityManager extends EntityManagerDecorator
$cursor = $counter * $maxRecords;
$dql = $this->createQueryBuilder();
$dql->select(select: 'record')
->from(from: Record::class, alias: 'record', indexBy: 'record.identifier')
->where(predicates: $dql->expr()->eq('record.format', ':metadataPrefix'))
->setParameter(
key: 'metadataPrefix',
value: $this->getMetadataFormat(prefix: $metadataPrefix)
)
->setFirstResult(firstResult: $cursor)
->setMaxResults(maxResults: $maxRecords);
$dql->select('record')
->from(Record::class, 'record', 'record.identifier')
->where($dql->expr()->eq('record.format', ':metadataPrefix'))
->setParameter('metadataPrefix', $this->getMetadataFormat($metadataPrefix))
->setFirstResult($cursor)
->setMaxResults($maxRecords);
if (isset($from)) {
$dql->andWhere(where: $dql->expr()->gte('record.lastChanged', ':from'));
$dql->setParameter(key: 'from', value: new DateTime($from));
$dql->andWhere($dql->expr()->gte('record.lastChanged', ':from'));
$dql->setParameter('from', new DateTime($from));
}
if (isset($until)) {
$dql->andWhere(where: $dql->expr()->lte('record.lastChanged', ':until'));
$dql->setParameter(key: 'until', value: new DateTime($until));
$dql->andWhere($dql->expr()->lte('record.lastChanged', ':until'));
$dql->setParameter('until', new DateTime($until));
}
if (isset($set)) {
$dql->innerJoin(
join: Set::class,
alias: 'sets',
conditionType: Join::WITH,
condition: $dql->expr()->orX(
Set::class,
'sets',
Join::WITH,
$dql->expr()->orX(
$dql->expr()->eq('sets.spec', ':setSpec'),
$dql->expr()->like('sets.spec', ':setLike')
)
);
$dql->setParameter(key: 'setSpec', value: $set);
$dql->setParameter(key: 'setLike', value: $set . ':%');
$dql->setParameter('setSpec', $set);
$dql->setParameter('setLike', $set . ':%');
}
$query = $dql->getQuery();
/** @var array<string, Record> */
$queryResult = $query->getResult();
$result = new ResultSet(elements: $queryResult);
$paginator = new Paginator(query: $query, fetchJoinCollection: true);
$result = new ResultSet($queryResult);
$paginator = new Paginator($query, true);
if (count($paginator) > ($cursor + count($result))) {
$token = new Token(
verb: $verb,
parameters: [
$verb,
[
'verb' => $verb,
'identifier' => null,
'metadataPrefix' => $metadataPrefix,
@ -248,9 +243,9 @@ final class EntityManager extends EntityManagerDecorator
'completeListSize' => count($paginator)
]
);
$this->persist(object: $token);
$this->persist($token);
$this->flush();
$result->setResumptionToken(token: $token);
$result->setResumptionToken($token);
}
return $result;
}
@ -265,14 +260,12 @@ final class EntityManager extends EntityManagerDecorator
*/
public function getResumptionToken(string $token, string $verb): ?Token
{
$resumptionToken = $this->getRepository(className: Token::class)->findOneBy(
criteria: [
$resumptionToken = $this->getRepository(Token::class)->findOneBy([
'token' => $token,
'verb' => $verb
]
);
]);
if (isset($resumptionToken) && $resumptionToken->getValidUntil() < new DateTime()) {
$this->delete(entity: $resumptionToken);
$this->delete($resumptionToken);
return null;
}
return $resumptionToken;
@ -287,7 +280,7 @@ final class EntityManager extends EntityManagerDecorator
*/
public function getSet(string $spec): ?Set
{
return $this->getReference(entityName: Set::class, id: $spec);
return $this->getReference(Set::class, $spec);
}
/**
@ -303,19 +296,19 @@ final class EntityManager extends EntityManagerDecorator
$cursor = $counter * $maxRecords;
$dql = $this->createQueryBuilder();
$dql->select(select: 'set')
->from(from: Set::class, alias: 'set', indexBy: 'set.spec')
->setFirstResult(firstResult: $cursor)
->setMaxResults(maxResults: $maxRecords);
$dql->select('set')
->from(Set::class, 'set', 'set.spec')
->setFirstResult($cursor)
->setMaxResults($maxRecords);
$query = $dql->getQuery()->enableResultCache();
/** @var array<string, Set> */
$queryResult = $query->getResult(hydrationMode: AbstractQuery::HYDRATE_OBJECT);
$result = new ResultSet(elements: $queryResult);
$paginator = new Paginator(query: $query);
$queryResult = $query->getResult(AbstractQuery::HYDRATE_OBJECT);
$result = new ResultSet($queryResult);
$paginator = new Paginator($query);
if (count($paginator) > ($cursor + count($result))) {
$token = new Token(
verb: 'ListSets',
parameters: [
'ListSets',
[
'verb' => 'ListSets',
'identifier' => null,
'metadataPrefix' => null,
@ -327,9 +320,9 @@ final class EntityManager extends EntityManagerDecorator
'completeListSize' => count($paginator)
]
);
$this->persist(object: $token);
$this->persist($token);
$this->flush();
$result->setResumptionToken(token: $token);
$result->setResumptionToken($token);
}
return $result;
}
@ -343,7 +336,7 @@ final class EntityManager extends EntityManagerDecorator
*/
public function isValidRecordIdentifier(string $identifier): bool
{
$records = $this->getRepository(className: Record::class)->findBy(criteria: ['identifier' => $identifier]);
$records = $this->getRepository(Record::class)->findBy(['identifier' => $identifier]);
return (bool) count($records) > 0;
}
@ -355,8 +348,8 @@ final class EntityManager extends EntityManagerDecorator
public function pruneDeletedRecords(): int
{
$dql = $this->createQueryBuilder();
$dql->delete(delete: Record::class, alias: 'record')
->where(predicates: $dql->expr()->isNull('record.content'));
$dql->delete(Record::class, 'record')
->where($dql->expr()->isNull('record.content'));
/** @var int */
$deleted = $dql->getQuery()->execute();
if ($deleted > 0) {
@ -373,8 +366,8 @@ final class EntityManager extends EntityManagerDecorator
public function pruneExpiredTokens(): int
{
$dql = $this->createQueryBuilder();
$dql->delete(delete: Token::class, alias: 'token')
->where(predicates: $dql->expr()->lt('token.validUntil', new DateTime()));
$dql->delete(Token::class, 'token')
->where($dql->expr()->lt('token.validUntil', new DateTime()));
/** @var int */
return $dql->getQuery()->execute();
}
@ -386,12 +379,12 @@ final class EntityManager extends EntityManagerDecorator
*/
public function pruneOrphanedSets(): int
{
$sets = $this->getRepository(className: Set::class)->findAll();
$sets = $this->getRepository(Set::class)->findAll();
$count = 0;
foreach ($sets as $set) {
if ($set->isEmpty()) {
$count += 1;
$this->remove(object: $set);
$this->remove($set);
}
}
if ($count > 0) {
@ -406,66 +399,39 @@ final class EntityManager extends EntityManagerDecorator
private function __construct()
{
$config = new DoctrineConfiguration();
$config->setAutoGenerateProxyClasses(
autoGenerate: ProxyFactory::AUTOGENERATE_NEVER
);
$config->setMetadataCache(
cache: new PhpFilesAdapter(
namespace: 'Metadata',
directory: __DIR__ . '/../var/cache'
)
);
$config->setMetadataDriverImpl(
driverImpl: new AttributeDriver(
paths: [__DIR__ . '/Entity']
)
);
$config->setProxyDir(dir: __DIR__ . '/../var/generated');
$config->setProxyNamespace(ns: 'OCC\OaiPmh2\Entity\Proxy');
$config->setQueryCache(
cache: new PhpFilesAdapter(
namespace: 'Query',
directory: __DIR__ . '/../var/cache'
)
);
$config->setResultCache(
cache: new PhpFilesAdapter(
namespace: 'Result',
directory: __DIR__ . '/../var/cache'
)
);
$config->setAutoGenerateProxyClasses(ProxyFactory::AUTOGENERATE_NEVER);
$config->setMetadataCache(new PhpFilesAdapter('Metadata', 0, __DIR__ . '/../var/cache'));
$config->setMetadataDriverImpl(new AttributeDriver([__DIR__ . '/Entity']));
$config->setProxyDir(__DIR__ . '/../var/generated');
$config->setProxyNamespace('OCC\OaiPmh2\Entity\Proxy');
$config->setQueryCache(new PhpFilesAdapter('Query', 0, __DIR__ . '/../var/cache'));
$config->setResultCache(new PhpFilesAdapter('Result', 0, __DIR__ . '/../var/cache'));
$config->setSchemaAssetsFilter(
schemaAssetsFilter: static function (string|AbstractAsset $assetName): bool {
static function (string|AbstractAsset $assetName): bool {
if ($assetName instanceof AbstractAsset) {
$assetName = $assetName->getName();
}
return in_array(needle: $assetName, haystack: self::TABLES, strict: true);
return in_array($assetName, self::TABLES, true);
}
);
$baseDir = Path::canonicalize(path: __DIR__ . '/../');
$dsn = str_replace(
search: '%BASEDIR%',
replace: $baseDir,
subject: Configuration::getInstance()->database
);
$parser = new DsnParser(
schemeMapping: [
$baseDir = Path::canonicalize(__DIR__ . '/../');
$dsn = str_replace('%BASEDIR%', $baseDir, Configuration::getInstance()->database);
$parser = new DsnParser([
'mariadb' => 'pdo_mysql',
'mssql' => 'pdo_sqlsrv',
'mysql' => 'pdo_mysql',
'oracle' => 'pdo_oci',
'postgresql' => 'pdo_pgsql',
'sqlite' => 'pdo_sqlite'
]
);
]);
$conn = DriverManager::getConnection(
// Generic return type of DsnParser::parse() is not correctly recognized.
// phpcs:ignore
params: $parser->parse(dsn: $dsn),
config: $config
$parser->parse(dsn: $dsn),
$config
);
parent::__construct(new DoctrineEntityManager(conn: $conn, config: $config));
parent::__construct(new DoctrineEntityManager($conn, $config));
}
}

View File

@ -88,24 +88,24 @@ abstract class Middleware extends AbstractMiddleware
protected function addResumptionToken(DOMElement $node, ?Token $token): void
{
if (isset($token) || isset($this->arguments['resumptionToken'])) {
$resumptionToken = $this->preparedResponse->createElement(localName: 'resumptionToken');
$resumptionToken = $this->preparedResponse->createElement('resumptionToken');
if (isset($token)) {
$resumptionToken->nodeValue = $token->getToken();
$resumptionToken->setAttribute(
qualifiedName: 'expirationDate',
value: $token->getValidUntil()->format(format: 'Y-m-d\TH:i:s\Z')
'expirationDate',
$token->getValidUntil()->format('Y-m-d\TH:i:s\Z')
);
$this->arguments['completeListSize'] = $token->getParameters()['completeListSize'];
}
$resumptionToken->setAttribute(
qualifiedName: 'completeListSize',
value: (string) $this->arguments['completeListSize']
'completeListSize',
(string) $this->arguments['completeListSize']
);
$resumptionToken->setAttribute(
qualifiedName: 'cursor',
value: (string) ($this->arguments['counter'] * Configuration::getInstance()->maxRecords)
'cursor',
(string) ($this->arguments['counter'] * Configuration::getInstance()->maxRecords)
);
$node->appendChild(node: $resumptionToken);
$node->appendChild($resumptionToken);
}
}
@ -117,14 +117,11 @@ abstract class Middleware extends AbstractMiddleware
protected function checkResumptionToken(): void
{
if (isset($this->arguments['resumptionToken'])) {
$token = $this->em->getResumptionToken(
token: $this->arguments['resumptionToken'],
verb: $this->arguments['verb']
);
$token = $this->em->getResumptionToken($this->arguments['resumptionToken'], $this->arguments['verb']);
if (isset($token)) {
$this->arguments = array_merge($this->arguments, $token->getParameters());
} else {
ErrorHandler::getInstance()->withError(errorCode: 'badResumptionToken');
ErrorHandler::getInstance()->withError('badResumptionToken');
}
}
}
@ -150,7 +147,7 @@ abstract class Middleware extends AbstractMiddleware
/** @var OaiRequestMetadata */
$arguments = $request->getAttributes();
$this->arguments = array_merge($this->arguments, $arguments);
$this->prepareResponse(request: $request);
$this->prepareResponse($request);
return $request;
}
@ -164,11 +161,7 @@ abstract class Middleware extends AbstractMiddleware
protected function processResponse(ResponseInterface $response): ResponseInterface
{
if (!ErrorHandler::getInstance()->hasErrors() && isset($this->preparedResponse)) {
$response = $response->withBody(
body: Utils::streamFor(
resource: (string) $this->preparedResponse
)
);
$response = $response->withBody(Utils::streamFor((string) $this->preparedResponse));
}
return $response;
}

View File

@ -65,14 +65,14 @@ class Dispatcher extends AbstractMiddleware
/** @var array<string, string> */
$arguments = $request->getQueryParams();
} elseif ($request->getMethod() === 'POST') {
if ($request->getHeaderLine(name: 'Content-Type') === 'application/x-www-form-urlencoded') {
if ($request->getHeaderLine('Content-Type') === 'application/x-www-form-urlencoded') {
/** @var array<string, string> */
$arguments = (array) $request->getParsedBody();
}
}
if ($this->validateArguments(arguments: $arguments)) {
if ($this->validateArguments($arguments)) {
foreach ($arguments as $param => $value) {
$request = $request->withAttribute(name: $param, value: $value);
$request = $request->withAttribute($param, $value);
}
}
return $request;
@ -87,17 +87,17 @@ class Dispatcher extends AbstractMiddleware
*/
protected function processRequest(ServerRequestInterface $request): ServerRequestInterface
{
$request = $this->getRequestWithAttributes(request: $request);
$request = $this->getRequestWithAttributes($request);
$errorHandler = ErrorHandler::getInstance();
if (!$errorHandler->hasErrors()) {
/** @var string */
$verb = $request->getAttribute(name: 'verb');
$verb = $request->getAttribute('verb');
$middleware = __NAMESPACE__ . '\\' . $verb;
if (is_a(object_or_class: $middleware, class: Middleware::class, allow_string: true)) {
$this->requestHandler->queue->enqueue(value: new $middleware());
if (is_a($middleware, Middleware::class, true)) {
$this->requestHandler->queue->enqueue(new $middleware());
}
}
$this->requestHandler->queue->enqueue(value: $errorHandler);
$this->requestHandler->queue->enqueue($errorHandler);
return $request;
}
@ -113,7 +113,7 @@ class Dispatcher extends AbstractMiddleware
// TODO: Add support for content compression
// https://openarchives.org/OAI/openarchivesprotocol.html#ResponseCompression
// https://github.com/middlewares/encoder
return $response->withHeader(name: 'Content-Type', value: 'text/xml');
return $response->withHeader('Content-Type', 'text/xml');
}
/**
@ -131,20 +131,20 @@ class Dispatcher extends AbstractMiddleware
count(array_diff(array_keys($arguments), self::OAI_PARAMS)) !== 0
or !isset($arguments['verb'])
) {
ErrorHandler::getInstance()->withError(errorCode: 'badArgument');
ErrorHandler::getInstance()->withError('badArgument');
} else {
match ($arguments['verb']) {
'GetRecord' => $this->validateGetRecord(arguments: $arguments),
'Identify' => $this->validateIdentify(arguments: $arguments),
'ListIdentifiers', 'ListRecords' => $this->validateListRecords(arguments: $arguments),
'ListMetadataFormats' => $this->validateListFormats(arguments: $arguments),
'ListSets' => $this->validateListSets(arguments: $arguments),
default => ErrorHandler::getInstance()->withError(errorCode: 'badVerb')
'GetRecord' => $this->validateGetRecord($arguments),
'Identify' => $this->validateIdentify($arguments),
'ListIdentifiers', 'ListRecords' => $this->validateListRecords($arguments),
'ListMetadataFormats' => $this->validateListFormats($arguments),
'ListSets' => $this->validateListSets($arguments),
default => ErrorHandler::getInstance()->withError('badVerb')
};
if (!ErrorHandler::getInstance()->hasErrors()) {
$this->validateMetadataPrefix(prefix: $arguments['metadataPrefix'] ?? null);
$this->validateDateTime(datetime: $arguments['from'] ?? null);
$this->validateDateTime(datetime: $arguments['until'] ?? null);
$this->validateMetadataPrefix($arguments['metadataPrefix'] ?? null);
$this->validateDateTime($arguments['from'] ?? null);
$this->validateDateTime($arguments['until'] ?? null);
$this->validateSet($arguments['set'] ?? null);
}
}
@ -161,9 +161,9 @@ class Dispatcher extends AbstractMiddleware
protected function validateDateTime(?string $datetime): void
{
if (isset($datetime)) {
$date = date_parse(datetime: $datetime);
$date = date_parse($datetime);
if ($date['warning_count'] > 0 || $date['error_count'] > 0) {
ErrorHandler::getInstance()->withError(errorCode: 'badArgument');
ErrorHandler::getInstance()->withError('badArgument');
}
}
}
@ -182,7 +182,7 @@ class Dispatcher extends AbstractMiddleware
or !isset($arguments['identifier'])
or !isset($arguments['metadataPrefix'])
) {
ErrorHandler::getInstance()->withError(errorCode: 'badArgument');
ErrorHandler::getInstance()->withError('badArgument');
}
}
@ -196,7 +196,7 @@ class Dispatcher extends AbstractMiddleware
protected function validateIdentify(array $arguments): void
{
if (count($arguments) !== 1) {
ErrorHandler::getInstance()->withError(errorCode: 'badArgument');
ErrorHandler::getInstance()->withError('badArgument');
}
}
@ -211,7 +211,7 @@ class Dispatcher extends AbstractMiddleware
{
if (count($arguments) !== 1) {
if (!isset($arguments['identifier']) || count($arguments) !== 2) {
ErrorHandler::getInstance()->withError(errorCode: 'badArgument');
ErrorHandler::getInstance()->withError('badArgument');
}
}
}
@ -233,10 +233,10 @@ class Dispatcher extends AbstractMiddleware
(isset($arguments['resumptionToken']) && count($arguments) !== 2)
or isset($arguments['identifier'])
) {
ErrorHandler::getInstance()->withError(errorCode: 'badArgument');
ErrorHandler::getInstance()->withError('badArgument');
}
} else {
ErrorHandler::getInstance()->withError(errorCode: 'badArgument');
ErrorHandler::getInstance()->withError('badArgument');
}
}
@ -251,7 +251,7 @@ class Dispatcher extends AbstractMiddleware
{
if (count($arguments) !== 1) {
if (!isset($arguments['resumptionToken']) || count($arguments) !== 2) {
ErrorHandler::getInstance()->withError(errorCode: 'badArgument');
ErrorHandler::getInstance()->withError('badArgument');
}
}
}
@ -267,8 +267,8 @@ class Dispatcher extends AbstractMiddleware
{
if (isset($prefix)) {
$formats = EntityManager::getInstance()->getMetadataFormats();
if (!$formats->containsKey(key: $prefix)) {
ErrorHandler::getInstance()->withError(errorCode: 'cannotDisseminateFormat');
if (!$formats->containsKey($prefix)) {
ErrorHandler::getInstance()->withError('cannotDisseminateFormat');
}
}
}
@ -284,8 +284,8 @@ class Dispatcher extends AbstractMiddleware
{
if (isset($spec)) {
$sets = EntityManager::getInstance()->getSets();
if (!$sets->containsKey(key: $spec)) {
ErrorHandler::getInstance()->withError(errorCode: 'badArgument');
if (!$sets->containsKey($spec)) {
ErrorHandler::getInstance()->withError('badArgument');
}
}
}

View File

@ -70,19 +70,16 @@ class ErrorHandler extends AbstractMiddleware
*/
protected function getResponseBody(): StreamInterface
{
$response = new Response(serverRequest: $this->requestHandler->request);
$response = new Response($this->requestHandler->request);
foreach (array_unique($this->errors) as $errorCode) {
$error = $response->createElement(
localName: 'error',
value: self::OAI_ERRORS[$errorCode],
appendToRoot: true
);
$error->setAttribute(
qualifiedName: 'code',
value: $errorCode
'error',
self::OAI_ERRORS[$errorCode],
true
);
$error->setAttribute('code', $errorCode);
}
return Utils::streamFor(resource: (string) $response);
return Utils::streamFor((string) $response);
}
/**
@ -105,7 +102,7 @@ class ErrorHandler extends AbstractMiddleware
protected function processResponse(ResponseInterface $response): ResponseInterface
{
if ($this->hasErrors()) {
$response = $response->withBody(body: $this->getResponseBody());
$response = $response->withBody($this->getResponseBody());
}
return $response;
}
@ -125,11 +122,11 @@ class ErrorHandler extends AbstractMiddleware
$this->errors[] = $errorCode;
} else {
throw new DomainException(
message: sprintf(
format: 'Valid OAI-PMH error code expected, "%s" given.',
values: $errorCode
sprintf(
'Valid OAI-PMH error code expected, "%s" given.',
$errorCode
),
code: 500
500
);
}
return $this;

View File

@ -46,64 +46,51 @@ class GetRecord extends Middleware
protected function prepareResponse(ServerRequestInterface $request): void
{
$oaiRecord = $this->em->getRecord(
identifier: (string) $this->arguments['identifier'],
format: (string) $this->arguments['metadataPrefix']
(string) $this->arguments['identifier'],
(string) $this->arguments['metadataPrefix']
);
if (!isset($oaiRecord)) {
if ($this->em->isValidRecordIdentifier(identifier: (string) $this->arguments['identifier'])) {
ErrorHandler::getInstance()->withError(errorCode: 'cannotDisseminateFormat');
if ($this->em->isValidRecordIdentifier((string) $this->arguments['identifier'])) {
ErrorHandler::getInstance()->withError('cannotDisseminateFormat');
} else {
ErrorHandler::getInstance()->withError(errorCode: 'idDoesNotExist');
ErrorHandler::getInstance()->withError('idDoesNotExist');
}
return;
}
$response = new Response(serverRequest: $request);
$getRecord = $response->createElement(
localName: 'GetRecord',
value: '',
appendToRoot: true
);
$response = new Response($request);
$getRecord = $response->createElement('GetRecord', '', true);
$record = $response->createElement(localName: 'record');
$getRecord->appendChild(node: $record);
$record = $response->createElement('record');
$getRecord->appendChild($record);
$header = $response->createElement(localName: 'header');
$header = $response->createElement('header');
if (!$oaiRecord->hasContent()) {
$header->setAttribute(
qualifiedName: 'status',
value: 'deleted'
);
$header->setAttribute('status', 'deleted');
}
$record->appendChild(node: $header);
$record->appendChild($header);
$identifier = $response->createElement(
localName: 'identifier',
value: $oaiRecord->getIdentifier()
);
$header->appendChild(node: $identifier);
$identifier = $response->createElement('identifier', $oaiRecord->getIdentifier());
$header->appendChild($identifier);
$datestamp = $response->createElement(
localName: 'datestamp',
value: $oaiRecord->getLastChanged()->format(format: 'Y-m-d\TH:i:s\Z')
'datestamp',
$oaiRecord->getLastChanged()->format('Y-m-d\TH:i:s\Z')
);
$header->appendChild(node: $datestamp);
$header->appendChild($datestamp);
foreach ($oaiRecord->getSets() as $set) {
$setSpec = $response->createElement(
localName: 'setSpec',
value: $set->getName()
);
$header->appendChild(node: $setSpec);
$setSpec = $response->createElement('setSpec', $set->getName());
$header->appendChild($setSpec);
}
if ($oaiRecord->hasContent()) {
$metadata = $response->createElement(localName: 'metadata');
$record->appendChild(node: $metadata);
$metadata = $response->createElement('metadata');
$record->appendChild($metadata);
$data = $response->importData(data: $oaiRecord->getContent());
$metadata->appendChild(node: $data);
$data = $response->importData($oaiRecord->getContent());
$metadata->appendChild($data);
}
$this->preparedResponse = $response;

View File

@ -47,74 +47,55 @@ class Identify extends Middleware
*/
protected function prepareResponse(ServerRequestInterface $request): void
{
$response = new Response(serverRequest: $request);
$identify = $response->createElement(
localName: 'Identify',
value: '',
appendToRoot: true
);
$response = new Response($request);
$identify = $response->createElement('Identify', '', true);
$repositoryName = $response->createElement(
localName: 'repositoryName',
value: Configuration::getInstance()->repositoryName
'repositoryName',
Configuration::getInstance()->repositoryName
);
$identify->appendChild(node: $repositoryName);
$identify->appendChild($repositoryName);
$uri = Uri::composeComponents(
scheme: $request->getUri()->getScheme(),
authority: $request->getUri()->getAuthority(),
path: $request->getUri()->getPath(),
query: null,
fragment: null
$request->getUri()->getScheme(),
$request->getUri()->getAuthority(),
$request->getUri()->getPath(),
null,
null
);
$baseURL = $response->createElement(
localName: 'baseURL',
value: $uri
);
$identify->appendChild(node: $baseURL);
$baseURL = $response->createElement('baseURL', $uri);
$identify->appendChild($baseURL);
$protocolVersion = $response->createElement(
localName: 'protocolVersion',
value: '2.0'
);
$identify->appendChild(node: $protocolVersion);
$protocolVersion = $response->createElement('protocolVersion', '2.0');
$identify->appendChild($protocolVersion);
$adminEmail = $response->createElement(
localName: 'adminEmail',
value: Configuration::getInstance()->adminEmail
'adminEmail',
Configuration::getInstance()->adminEmail
);
$identify->appendChild(node: $adminEmail);
$identify->appendChild($adminEmail);
$earliestDatestamp = $response->createElement(
localName: 'earliestDatestamp',
value: $this->em->getEarliestDatestamp()
'earliestDatestamp',
$this->em->getEarliestDatestamp()
);
$identify->appendChild(node: $earliestDatestamp);
$identify->appendChild($earliestDatestamp);
$deletedRecord = $response->createElement(
localName: 'deletedRecord',
value: Configuration::getInstance()->deletedRecords
'deletedRecord',
Configuration::getInstance()->deletedRecords
);
$identify->appendChild(node: $deletedRecord);
$identify->appendChild($deletedRecord);
$granularity = $response->createElement(
localName: 'granularity',
value: 'YYYY-MM-DDThh:mm:ssZ'
);
$identify->appendChild(node: $granularity);
$granularity = $response->createElement('granularity', 'YYYY-MM-DDThh:mm:ssZ');
$identify->appendChild($granularity);
// TODO: Implement explicit content compression support.
// $compressionDeflate = $response->createElement(
// localName: 'compression',
// value: 'deflate'
// );
// $identify->appendChild(node: $compressionDeflate);
// $compressionDeflate = $response->createElement('compression', 'deflate');
// $identify->appendChild($compressionDeflate);
// $compressionGzip = $response->createElement(
// localName: 'compression',
// value: 'gzip'
// );
// $identify->appendChild(node: $compressionGzip);
// $compressionGzip = $response->createElement('compression', 'gzip');
// $identify->appendChild($compressionGzip);
$this->preparedResponse = $response;
}

View File

@ -48,75 +48,62 @@ class ListIdentifiers extends Middleware
$this->checkResumptionToken();
$records = $this->em->getRecords(
verb: $this->arguments['verb'],
metadataPrefix: (string) $this->arguments['metadataPrefix'],
counter: $this->arguments['counter'],
from: $this->arguments['from'],
until: $this->arguments['until'],
set: $this->arguments['set']
$this->arguments['verb'],
(string) $this->arguments['metadataPrefix'],
$this->arguments['counter'],
$this->arguments['from'],
$this->arguments['until'],
$this->arguments['set']
);
if (count($records) === 0) {
ErrorHandler::getInstance()->withError(errorCode: 'noRecordsMatch');
ErrorHandler::getInstance()->withError('noRecordsMatch');
return;
}
$response = new Response(serverRequest: $request);
$list = $response->createElement(
localName: $this->arguments['verb'],
value: '',
appendToRoot: true
);
$response = new Response($request);
$list = $response->createElement($this->arguments['verb'], '', true);
$baseNode = $list;
foreach ($records as $oaiRecord) {
if ($this->arguments['verb'] === 'ListRecords') {
$record = $response->createElement(localName: 'record');
$list->appendChild(node: $record);
$record = $response->createElement('record');
$list->appendChild($record);
$baseNode = $record;
}
$header = $response->createElement(localName: 'header');
$baseNode->appendChild(node: $header);
$header = $response->createElement('header');
$baseNode->appendChild($header);
$identifier = $response->createElement(
localName: 'identifier',
value: $oaiRecord->getIdentifier()
'identifier',
$oaiRecord->getIdentifier()
);
$header->appendChild(node: $identifier);
$header->appendChild($identifier);
$datestamp = $response->createElement(
localName: 'datestamp',
value: $oaiRecord->getLastChanged()->format(format: 'Y-m-d\TH:i:s\Z')
'datestamp',
$oaiRecord->getLastChanged()->format('Y-m-d\TH:i:s\Z')
);
$header->appendChild(node: $datestamp);
$header->appendChild($datestamp);
foreach ($oaiRecord->getSets() as $oaiSet) {
$setSpec = $response->createElement(
localName: 'setSpec',
value: $oaiSet->getName()
);
$header->appendChild(node: $setSpec);
$setSpec = $response->createElement('setSpec', $oaiSet->getName());
$header->appendChild($setSpec);
}
if (!$oaiRecord->hasContent()) {
$header->setAttribute(
qualifiedName: 'status',
value: 'deleted'
);
$header->setAttribute('status', 'deleted');
} elseif ($this->arguments['verb'] === 'ListRecords') {
$metadata = $response->createElement(localName: 'metadata');
$baseNode->appendChild(node: $metadata);
$metadata = $response->createElement('metadata');
$baseNode->appendChild($metadata);
$data = $response->importData(data: $oaiRecord->getContent());
$metadata->appendChild(node: $data);
$data = $response->importData($oaiRecord->getContent());
$metadata->appendChild($data);
}
}
$this->preparedResponse = $response;
$this->addResumptionToken(
node: $list,
token: $records->getResumptionToken() ?? null
);
$this->addResumptionToken($list, $records->getResumptionToken() ?? null);
}
}

View File

@ -45,48 +45,44 @@ class ListMetadataFormats extends Middleware
*/
protected function prepareResponse(ServerRequestInterface $request): void
{
$formats = $this->em->getMetadataFormats(recordIdentifier: $this->arguments['identifier']);
$formats = $this->em->getMetadataFormats($this->arguments['identifier']);
if (count($formats) === 0) {
if (
!isset($this->arguments['identifier'])
|| $this->em->isValidRecordIdentifier(identifier: $this->arguments['identifier'])
|| $this->em->isValidRecordIdentifier($this->arguments['identifier'])
) {
ErrorHandler::getInstance()->withError(errorCode: 'noMetadataFormats');
ErrorHandler::getInstance()->withError('noMetadataFormats');
} else {
ErrorHandler::getInstance()->withError(errorCode: 'idDoesNotExist');
ErrorHandler::getInstance()->withError('idDoesNotExist');
}
return;
}
$response = new Response(serverRequest: $request);
$listMetadataFormats = $response->createElement(
localName: 'ListMetadataFormats',
value: '',
appendToRoot: true
);
$response = new Response($request);
$listMetadataFormats = $response->createElement('ListMetadataFormats', '', true);
foreach ($formats as $oaiFormat) {
$metadataFormat = $response->createElement(localName: 'metadataFormat');
$listMetadataFormats->appendChild(node: $metadataFormat);
$metadataFormat = $response->createElement('metadataFormat');
$listMetadataFormats->appendChild($metadataFormat);
$metadataPrefix = $response->createElement(
localName: 'metadataPrefix',
value: $oaiFormat->getPrefix()
'metadataPrefix',
$oaiFormat->getPrefix()
);
$metadataFormat->appendChild(node: $metadataPrefix);
$metadataFormat->appendChild($metadataPrefix);
$schema = $response->createElement(
localName: 'schema',
value: $oaiFormat->getSchema()
'schema',
$oaiFormat->getSchema()
);
$metadataFormat->appendChild(node: $schema);
$metadataFormat->appendChild($schema);
$metadataNamespace = $response->createElement(
localName: 'metadataNamespace',
value: $oaiFormat->getNamespace()
'metadataNamespace',
$oaiFormat->getNamespace()
);
$metadataFormat->appendChild(node: $metadataNamespace);
$metadataFormat->appendChild($metadataNamespace);
}
$this->preparedResponse = $response;

View File

@ -47,50 +47,43 @@ class ListSets extends Middleware
{
$this->checkResumptionToken();
$sets = $this->em->getSets(counter: $this->arguments['counter']);
$sets = $this->em->getSets($this->arguments['counter']);
if (count($sets) === 0) {
ErrorHandler::getInstance()->withError(errorCode: 'noSetHierarchy');
ErrorHandler::getInstance()->withError('noSetHierarchy');
return;
}
$response = new Response(serverRequest: $request);
$list = $response->createElement(
localName: 'ListSets',
value: '',
appendToRoot: true
);
$response = new Response($request);
$list = $response->createElement('ListSets', '', true);
foreach ($sets as $oaiSet) {
$set = $response->createElement(localName: 'set');
$list->appendChild(node: $set);
$set = $response->createElement('set');
$list->appendChild($set);
$setSpec = $response->createElement(
localName: 'setSpec',
value: $oaiSet->getSpec()
'setSpec',
$oaiSet->getSpec()
);
$set->appendChild(node: $setSpec);
$set->appendChild($setSpec);
$setName = $response->createElement(
localName: 'setName',
value: $oaiSet->getName()
'setName',
$oaiSet->getName()
);
$set->appendChild(node: $setName);
$set->appendChild($setName);
if ($oaiSet->hasDescription()) {
$setDescription = $response->createElement(localName: 'setDescription');
$set->appendChild(node: $setDescription);
$setDescription = $response->createElement('setDescription');
$set->appendChild($setDescription);
$data = $response->importData(data: $oaiSet->getDescription());
$setDescription->appendChild(node: $data);
$data = $response->importData($oaiSet->getDescription());
$setDescription->appendChild($data);
}
}
$this->preparedResponse = $response;
$this->addResumptionToken(
node: $list,
token: $sets->getResumptionToken() ?? null
);
$this->addResumptionToken($list, $sets->getResumptionToken() ?? null);
}
}

View File

@ -45,12 +45,12 @@ final class FormatRepository extends EntityRepository
*/
public function addOrUpdate(Format $entity): void
{
$oldFormat = $this->find(id: $entity->getPrefix());
$oldFormat = $this->find($entity->getPrefix());
if (isset($oldFormat)) {
$oldFormat->setNamespace(namespace: $entity->getNamespace());
$oldFormat->setSchema(schema: $entity->getSchema());
$oldFormat->setNamespace($entity->getNamespace());
$oldFormat->setSchema($entity->getSchema());
} else {
$this->getEntityManager()->persist(object: $entity);
$this->getEntityManager()->persist($entity);
}
}
@ -65,7 +65,7 @@ final class FormatRepository extends EntityRepository
{
/** @var EntityManager */
$entityManager = $this->getEntityManager();
$entityManager->remove(object: $entity);
$entityManager->remove($entity);
$entityManager->flush();
$entityManager->pruneOrphanedSets();
}

View File

@ -49,32 +49,30 @@ final class RecordRepository extends EntityRepository
{
/** @var EntityManager */
$entityManager = $this->getEntityManager();
$oldRecord = $this->find(
id: [
$oldRecord = $this->find([
'identifier' => $entity->getIdentifier(),
'format' => $entity->getFormat()
]
);
]);
if (isset($oldRecord)) {
if ($entity->hasContent() || Configuration::getInstance()->deletedRecords !== 'no') {
$oldRecord->setContent(data: $entity->getContent(), validate: false);
$oldRecord->setLastChanged(dateTime: $entity->getLastChanged());
$oldRecord->setContent($entity->getContent(), false);
$oldRecord->setLastChanged($entity->getLastChanged());
$newSets = $entity->getSets()->toArray();
$oldSets = $oldRecord->getSets()->toArray();
// Add new sets.
foreach (array_diff(array: $newSets, arrays: $oldSets) as $newSet) {
$oldRecord->addSet(set: $newSet);
foreach (array_diff($newSets, $oldSets) as $newSet) {
$oldRecord->addSet($newSet);
}
// Remove old sets.
foreach (array_diff(array: $oldSets, arrays: $newSets) as $oldSet) {
$oldRecord->removeSet(set: $oldSet);
foreach (array_diff($oldSets, $newSets) as $oldSet) {
$oldRecord->removeSet($oldSet);
}
} else {
$entityManager->remove(object: $oldRecord);
$entityManager->remove($oldRecord);
}
} else {
if ($entity->hasContent() || Configuration::getInstance()->deletedRecords !== 'no') {
$entityManager->persist(object: $entity);
$entityManager->persist($entity);
}
}
}
@ -91,12 +89,12 @@ final class RecordRepository extends EntityRepository
/** @var EntityManager */
$entityManager = $this->getEntityManager();
if (Configuration::getInstance()->deletedRecords === 'no') {
$entityManager->remove(object: $entity);
$entityManager->remove($entity);
$entityManager->flush();
$entityManager->pruneOrphanedSets();
} else {
$entity->setContent();
$entity->setLastChanged(dateTime: new DateTime());
$entity->setLastChanged(new DateTime());
$entityManager->flush();
}
}

View File

@ -23,9 +23,7 @@ declare(strict_types=1);
namespace OCC\OaiPmh2\Repository;
use Doctrine\ORM\EntityRepository;
use OCC\OaiPmh2\Configuration;
use OCC\OaiPmh2\Entity\Set;
use OCC\OaiPmh2\ResultSet;
/**
* Doctrine/ORM Repository for sets.
@ -46,12 +44,12 @@ final class SetRepository extends EntityRepository
*/
public function addOrUpdate(Set $entity): void
{
$oldSet = $this->find(id: $entity->getSpec());
$oldSet = $this->find($entity->getSpec());
if (isset($oldSet)) {
$oldSet->setName(name: $entity->getName());
$oldSet->setDescription(description: $entity->getDescription());
$oldSet->setName($entity->getName());
$oldSet->setDescription($entity->getDescription());
} else {
$this->getEntityManager()->persist(object: $entity);
$this->getEntityManager()->persist($entity);
}
}
@ -65,7 +63,7 @@ final class SetRepository extends EntityRepository
public function delete(Set $entity): void
{
$entityManager = $this->getEntityManager();
$entityManager->remove(object: $entity);
$entityManager->remove($entity);
$entityManager->flush();
}
}

View File

@ -22,7 +22,6 @@ declare(strict_types=1);
namespace OCC\OaiPmh2\Repository;
use DateTime;
use Doctrine\ORM\EntityRepository;
use OCC\OaiPmh2\Entity\Token;
@ -45,7 +44,7 @@ final class TokenRepository extends EntityRepository
*/
public function addOrUpdate(Token $entity): void
{
$this->getEntityManager()->persist(object: $entity);
$this->getEntityManager()->persist($entity);
}
/**
@ -58,7 +57,7 @@ final class TokenRepository extends EntityRepository
public function delete(Token $entity): void
{
$entityManager = $this->getEntityManager();
$entityManager->remove(object: $entity);
$entityManager->remove($entity);
$entityManager->flush();
}
}

View File

@ -56,24 +56,24 @@ final class Response
{
$uri = $this->serverRequest->getUri();
$basePath = $uri->getPath();
if (str_ends_with(haystack: $basePath, needle: 'index.php')) {
$basePath = pathinfo(path: $basePath, flags: PATHINFO_DIRNAME);
if (str_ends_with($basePath, 'index.php')) {
$basePath = pathinfo($basePath, PATHINFO_DIRNAME);
}
$stylesheet = Uri::composeComponents(
scheme: $uri->getScheme(),
authority: $uri->getAuthority(),
path: rtrim(string: $basePath, characters: '/') . '/resources/stylesheet.xsl',
query: null,
fragment: null
$uri->getScheme(),
$uri->getAuthority(),
rtrim($basePath, '/') . '/resources/stylesheet.xsl',
null,
null
);
$xslt = $this->dom->createProcessingInstruction(
target: 'xml-stylesheet',
data: sprintf(
format: 'type="text/xsl" href="%s"',
values: $stylesheet
'xml-stylesheet',
sprintf(
'type="text/xsl" href="%s"',
$stylesheet
)
);
$this->dom->appendChild(node: $xslt);
$this->dom->appendChild($xslt);
}
/**
@ -85,27 +85,19 @@ final class Response
{
$uri = $this->serverRequest->getUri();
$baseUrl = Uri::composeComponents(
scheme: $uri->getScheme(),
authority: $uri->getAuthority(),
path: $uri->getPath(),
query: null,
fragment: null
);
$request = $this->createElement(
localName: 'request',
value: $baseUrl,
appendToRoot: true
$uri->getScheme(),
$uri->getAuthority(),
$uri->getPath(),
null,
null
);
$request = $this->createElement('request', $baseUrl, true);
/** @var array<string, string> */
$params = $this->serverRequest->getAttributes();
foreach ($params as $param => $value) {
$request->setAttribute(
qualifiedName: $param,
value: htmlspecialchars(
string: $value,
flags: ENT_XML1 | ENT_COMPAT,
encoding: 'UTF-8'
)
$param,
htmlspecialchars($value, ENT_XML1 | ENT_COMPAT, 'UTF-8')
);
}
}
@ -117,11 +109,7 @@ final class Response
*/
protected function appendResponseDate(): void
{
$this->createElement(
localName: 'responseDate',
value: gmdate(format: 'Y-m-d\TH:i:s\Z'),
appendToRoot: true
);
$this->createElement('responseDate', gmdate('Y-m-d\TH:i:s\Z'), true);
}
/**
@ -131,20 +119,20 @@ final class Response
*/
protected function appendRootElement(): void
{
$this->rootNode = $this->dom->createElement(localName: 'OAI-PMH');
$this->rootNode = $this->dom->createElement('OAI-PMH');
$this->rootNode->setAttribute(
qualifiedName: 'xmlns',
value: 'http://www.openarchives.org/OAI/2.0/'
'xmlns',
'http://www.openarchives.org/OAI/2.0/'
);
$this->rootNode->setAttribute(
qualifiedName: 'xmlns:xsi',
value: 'http://www.w3.org/2001/XMLSchema-instance'
'xmlns:xsi',
'http://www.w3.org/2001/XMLSchema-instance'
);
$this->rootNode->setAttribute(
qualifiedName: 'xsi:schemaLocation',
value: 'http://www.openarchives.org/OAI/2.0/ https://www.openarchives.org/OAI/2.0/OAI-PMH.xsd'
'xsi:schemaLocation',
'http://www.openarchives.org/OAI/2.0/ https://www.openarchives.org/OAI/2.0/OAI-PMH.xsd'
);
$this->dom->appendChild(node: $this->rootNode);
$this->dom->appendChild($this->rootNode);
}
/**
@ -154,7 +142,7 @@ final class Response
*/
protected function createDocument(): void
{
$this->dom = new DOMDocument(version: '1.0', encoding: 'UTF-8');
$this->dom = new DOMDocument('1.0', 'UTF-8');
$this->dom->preserveWhiteSpace = false;
$this->addProcessingInstructions();
}
@ -170,16 +158,9 @@ final class Response
*/
public function createElement(string $localName, string $value = '', bool $appendToRoot = false): DOMElement
{
$node = $this->dom->createElement(
localName: $localName,
value: htmlspecialchars(
string: $value,
flags: ENT_XML1,
encoding: 'UTF-8'
)
);
$node = $this->dom->createElement($localName, htmlspecialchars($value, ENT_XML1, 'UTF-8'));
if ($appendToRoot) {
$this->rootNode->appendChild(node: $node);
$this->rootNode->appendChild($node);
}
return $node;
}
@ -195,17 +176,17 @@ final class Response
*/
public function importData(string $data): DOMNode
{
$document = new DOMDocument(version: '1.0', encoding: 'UTF-8');
$document = new DOMDocument('1.0', 'UTF-8');
$document->preserveWhiteSpace = false;
if ($document->loadXML(source: $data) === true) {
if ($document->loadXML($data) === true) {
/** @var DOMElement */
$rootNode = $document->documentElement;
$node = $this->dom->importNode(node: $rootNode, deep: true);
$node = $this->dom->importNode($rootNode, true);
return $node;
} else {
throw new DOMException(
message: 'Could not import the XML data. Most likely it is not well-formed.',
code: 500
'Could not import the XML data. Most likely it is not well-formed.',
500
);
}
}

View File

@ -71,7 +71,7 @@ final class ResultSet extends ArrayCollection
*/
public function __construct(array $elements = [], Token $token = null)
{
parent::__construct(elements: $elements);
parent::__construct($elements);
$this->resumptionToken = $token;
}
}

View File

@ -43,57 +43,51 @@ class ConfigurationValidator
protected static function getValidationConstraints(): array
{
return [
new Assert\Collection(
fields: [
new Assert\Collection([
'repositoryName' => [
new Assert\Type(type: 'string'),
new Assert\Type('string'),
new Assert\NotBlank()
],
'adminEmail' => [
new Assert\Type(type: 'string'),
new Assert\Email(options: ['mode' => 'html5']),
new Assert\Type('string'),
new Assert\Email(['mode' => 'html5']),
new Assert\NotBlank()
],
'database' => [
new Assert\Type(type: 'string'),
new Assert\Type('string'),
new Assert\NotBlank()
],
'metadataPrefix' => [
new Assert\Type(type: 'array'),
new Assert\All(
constraints: [
new Assert\Collection(
fields: [
new Assert\Type('array'),
new Assert\All([
new Assert\Collection([
'schema' => [
new Assert\Type(type: 'string'),
new Assert\Type('string'),
new Assert\Url(),
new Assert\NotBlank()
],
'namespace' => [
new Assert\Type(type: 'string'),
new Assert\Type('string'),
new Assert\Url(),
new Assert\NotBlank()
]
]
)
]
)
])
])
],
'deletedRecords' => [
new Assert\Type(type: 'string'),
new Assert\Choice(options: ['no', 'persistent', 'transient']),
new Assert\Type('string'),
new Assert\Choice(['no', 'persistent', 'transient']),
new Assert\NotBlank()
],
'maxRecords' => [
new Assert\Type(type: 'int'),
new Assert\Range(options: ['min' => 1, 'max' => 100])
new Assert\Type('int'),
new Assert\Range(['min' => 1, 'max' => 100])
],
'tokenValid' => [
new Assert\Type(type: 'int'),
new Assert\Range(options: ['min' => 300, 'max' => 86400])
new Assert\Type('int'),
new Assert\Range(['min' => 300, 'max' => 86400])
]
]
)
])
];
}
@ -107,8 +101,8 @@ class ConfigurationValidator
public static function validate(array $config): ConstraintViolationListInterface
{
return Validation::createValidator()->validate(
value: $config,
constraints: self::getValidationConstraints()
$config,
self::getValidationConstraints()
);
}
}

View File

@ -45,12 +45,10 @@ class RegExValidator
protected static function getValidationConstraints(string $regEx): array
{
return [
new Assert\Regex(
pattern: [
new Assert\Regex([
'pattern' => $regEx,
'message' => 'This value does not match the regular expression "{{ pattern }}".'
]
)
])
];
}
@ -65,8 +63,8 @@ class RegExValidator
public static function validate(string $string, string $regEx): ConstraintViolationListInterface
{
return Validation::createValidator()->validate(
value: $string,
constraints: self::getValidationConstraints(regEx: $regEx)
$string,
self::getValidationConstraints($regEx)
);
}
}

View File

@ -58,8 +58,8 @@ class UrlValidator
public static function validate(string $url): ConstraintViolationListInterface
{
return Validation::createValidator()->validate(
value: $url,
constraints: self::getValidationConstraints()
$url,
self::getValidationConstraints()
);
}
}

View File

@ -44,7 +44,7 @@ class XmlValidator
protected static function getValidationConstraints(): array
{
return [
new Assert\Type(type: 'string'),
new Assert\Type('string'),
new Assert\NotBlank()
];
}
@ -59,18 +59,18 @@ class XmlValidator
public static function validate(string $xml): ConstraintViolationListInterface
{
$violations = Validation::createValidator()->validate(
value: $xml,
constraints: self::getValidationConstraints()
$xml,
self::getValidationConstraints()
);
if (simplexml_load_string(data: $xml) === false) {
if (simplexml_load_string($xml) === false) {
$violations->add(
violation: new ConstraintViolation(
message: 'Value could not be parsed as XML.',
messageTemplate: 'Value could not be parsed as XML.',
parameters: [],
root: $xml,
propertyPath: null,
invalidValue: $xml
new ConstraintViolation(
'Value could not be parsed as XML.',
'Value could not be parsed as XML.',
[],
$xml,
null,
$xml
)
);
}