code
stringlengths 31
1.39M
| docstring
stringlengths 23
16.8k
| func_name
stringlengths 1
126
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 7
166
| url
stringlengths 50
220
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
protected function execute(InputInterface $input, OutputInterface $output): int
{
$loggerHelper = $this->getHelper('logger');
assert($loggerHelper instanceof LoggerHelper);
$logger = $loggerHelper->create($output);
[, $errors] = (new IteratorHelper())->getTestFiles($logger);
if (! empty($errors)) {
return self::FAILURE;
}
return self::SUCCESS;
} | @return int null or 0 if everything went fine, or an error code
@throws UnexpectedValueException
@throws LogicException
@throws InvalidArgumentException
@throws \InvalidArgumentException | execute | php | browscap/browscap | src/Browscap/Command/CheckDuplicateTestsCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/CheckDuplicateTestsCommand.php | MIT |
protected function execute(InputInterface $input, OutputInterface $output): int
{
$loggerHelper = $this->getHelper('logger');
assert($loggerHelper instanceof LoggerHelper);
$logger = $loggerHelper->create($output);
$resources = $input->getOption('resources');
assert(is_string($resources));
$browserResourcePath = $resources . '/browsers';
$logger->info(sprintf('Resource folder: %s', $resources));
$schema = 'file://' . realpath(__DIR__ . '/../../../schema/browsers.json');
$rewriteHelper = $this->getHelper('rewrite');
assert($rewriteHelper instanceof RewriteHelper);
$rewriteHelper->rewrite($logger, $browserResourcePath, $schema, true);
$output->writeln('Done');
return self::SUCCESS;
} | @return int 0 if everything went fine, or an error code
@throws InvalidArgumentException
@throws LogicException
@throws InvalidNewLineString
@throws InvalidIndentStyle
@throws InvalidIndentSize
@throws InvalidJsonEncodeOptions
@throws \InvalidArgumentException | execute | php | browscap/browscap | src/Browscap/Command/RewriteBrowsersCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/RewriteBrowsersCommand.php | MIT |
protected function execute(InputInterface $input, OutputInterface $output): int
{
$loggerHelper = $this->getHelper('logger');
assert($loggerHelper instanceof LoggerHelper);
$logger = $loggerHelper->create($output);
$resources = $input->getOption('resources');
assert(is_string($resources));
$coreResourcePath = $resources . '/core';
$logger->info(sprintf('Resource folder: %s', $resources));
$schema = 'file://' . realpath(__DIR__ . '/../../../schema/core-divisions.json');
$rewriteHelper = $this->getHelper('rewrite');
assert($rewriteHelper instanceof RewriteHelper);
$rewriteHelper->rewrite($logger, $coreResourcePath, $schema, false);
$output->writeln('Done');
return self::SUCCESS;
} | @return int 0 if everything went fine, or an error code
@throws InvalidArgumentException
@throws LogicException
@throws InvalidNewLineString
@throws InvalidIndentStyle
@throws InvalidIndentSize
@throws InvalidJsonEncodeOptions
@throws \InvalidArgumentException | execute | php | browscap/browscap | src/Browscap/Command/RewriteCoreDivisionsCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/RewriteCoreDivisionsCommand.php | MIT |
protected function execute(InputInterface $input, OutputInterface $output): int
{
$loggerHelper = $this->getHelper('logger');
assert($loggerHelper instanceof LoggerHelper);
$logger = $loggerHelper->create($output);
$resources = $input->getOption('resources');
assert(is_string($resources));
$devicesResourcePath = $resources . '/devices';
$logger->info(sprintf('Resource folder: %s', $resources));
$schema = 'file://' . realpath(__DIR__ . '/../../../schema/devices.json');
$rewriteHelper = $this->getHelper('rewrite');
assert($rewriteHelper instanceof RewriteHelper);
$rewriteHelper->rewrite($logger, $devicesResourcePath, $schema, true);
$output->writeln('Done');
return self::SUCCESS;
} | @return int 0 if everything went fine, or an error code
@throws InvalidArgumentException
@throws LogicException
@throws InvalidNewLineString
@throws InvalidIndentStyle
@throws InvalidIndentSize
@throws InvalidJsonEncodeOptions
@throws \InvalidArgumentException | execute | php | browscap/browscap | src/Browscap/Command/RewriteDevicesCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/RewriteDevicesCommand.php | MIT |
protected function execute(InputInterface $input, OutputInterface $output): int
{
$loggerHelper = $this->getHelper('logger');
assert($loggerHelper instanceof LoggerHelper);
$logger = $loggerHelper->create($output);
$resources = $input->getOption('resources');
assert(is_string($resources));
$divisionsResourcePath = $resources . '/user-agents';
$logger->info('Resource folder: ' . $resources);
$loader = new FilesystemLoader(__DIR__ . '/../../../templates/');
$twig = new Environment($loader, [
'cache' => false,
'optimizations' => 0,
'autoescape' => false,
]);
$content = file_get_contents($resources . '/platforms/platforms.json');
if ($content === false) {
$logger->critical(
'File "{File}" is not readable',
[
'File' => $resources . '/platforms.json',
],
);
return self::FAILURE;
}
try {
$allPlatforms = json_decode($content, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
$logger->critical(
'File "{File}" is not valid',
[
'File' => $resources . '/platforms.json',
'Exception' => $e,
],
);
return self::FAILURE;
}
assert(is_array($allPlatforms));
$finder = new Finder();
$finder->files();
$finder->name('*.json');
$finder->ignoreDotFiles(true);
$finder->ignoreVCS(true);
$finder->sortByName();
$finder->ignoreUnreadableDirs();
$finder->in($divisionsResourcePath);
foreach ($finder as $file) {
/** @var SplFileInfo $file */
$logger->info('read source file ' . $file->getPathname());
try {
$json = $file->getContents();
} catch (RuntimeException $e) {
$logger->critical(
'File "{File}" is not readable',
[
'File' => $file->getPathname(),
'Exception' => $e,
],
);
continue;
}
try {
$divisionData = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
$logger->critical(
'File "{File}" is not valid',
[
'File' => $file->getPathname(),
'Exception' => $e,
],
);
continue;
}
assert(is_array($divisionData));
if (! array_key_exists('division', $divisionData)) {
$logger->critical(
'File "{File}" is not valid! "division" property is missing',
[
'File' => $file->getPathname(),
],
);
continue;
}
if (! array_key_exists('sortIndex', $divisionData)) {
$logger->critical(
'File "{File}" is not valid! "sortIndex" property is missing',
[
'File' => $file->getPathname(),
],
);
continue;
}
if (! array_key_exists('lite', $divisionData)) {
$logger->critical(
'File "{File}" is not valid! "lite" property is missing',
[
'File' => $file->getPathname(),
],
);
continue;
}
if (! array_key_exists('standard', $divisionData)) {
$logger->critical(
'File "{File}" is not valid! "standard" property is missing',
[
'File' => $file->getPathname(),
],
);
continue;
}
if (! array_key_exists('userAgents', $divisionData)) {
$logger->critical(
'File "{File}" is not valid! userAgents section is missing',
[
'File' => $file->getPathname(),
],
);
continue;
}
if (! is_array($divisionData['userAgents'])) {
$logger->critical(
'File "{File}" is not valid! userAgents section is not an array',
[
'File' => $file->getPathname(),
],
);
unset($divisionData['userAgents']);
continue;
}
if (array_key_exists('versions', $divisionData)) {
if (is_array($divisionData['versions'])) {
$divisionData['versions'] = $this->sortVersions($divisionData);
} else {
$logger->critical(
'File "{File}" is not valid! versions section is not an array',
[
'File' => $file->getPathname(),
],
);
unset($divisionData['versions']);
}
}
foreach ($divisionData['userAgents'] as $key => $useragentData) {
if (! is_int($key)) {
$logger->critical(
'File "{File}" is not valid! not-numeric key in userAgents section found',
[
'File' => $file->getPathname(),
],
);
unset($divisionData['userAgents'][$key]);
continue;
}
$useragentData = $this->rewriteUserAgents(
$useragentData,
$file,
$logger,
$allPlatforms,
);
if (empty($useragentData)) {
$logger->critical(
'File "{File}" is not valid! userAgents section is empty',
[
'File' => $file->getPathname(),
],
);
unset($divisionData['userAgents'][$key]);
continue;
}
$divisionData['userAgents'][$key] = $useragentData;
}
try {
$normalized = $twig->render('division.json.twig', ['divisionData' => $divisionData]);
} catch (LoaderError | RuntimeError | SyntaxError $e) {
$logger->critical($e);
continue;
}
file_put_contents($file->getPathname(), $normalized);
}
$output->writeln('Done');
return self::SUCCESS;
} | @return int 0 if everything went fine, or an error code
@throws InvalidArgumentException
@throws DirectoryNotFoundException
@throws JsonException
@throws LogicException
@throws \InvalidArgumentException | execute | php | browscap/browscap | src/Browscap/Command/RewriteDivisionsCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/RewriteDivisionsCommand.php | MIT |
private function sortPlatforms(array $platforms, array $allPlatforms): array
{
$platformVersions = [];
foreach ($platforms as $key => $platform) {
$x = array_intersect($allPlatforms, [$platform]);
$platformVersions[$key] = key($x);
}
array_multisort(
$platformVersions,
SORT_NUMERIC,
SORT_ASC,
$platforms,
);
return $platforms;
} | @param array<string> $platforms
@param array<int, (int|string)> $allPlatforms
@return array<string> | sortPlatforms | php | browscap/browscap | src/Browscap/Command/RewriteDivisionsCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/RewriteDivisionsCommand.php | MIT |
private function sortVersions(array $divisionData): array
{
$majorVersions = [];
$minorVersions = [];
$keyVersions = [];
foreach ($divisionData['versions'] as $key => $version) {
$parts = explode('.', (string) $version, 2);
$majorVersions[$key] = (int) $parts[0];
if (! isset($parts[1]) || $parts[1] === '0') {
$divisionData['versions'][$key] = (int) $version;
} else {
$divisionData['versions'][$key] = (string) $version;
}
if (isset($parts[1])) {
$minorVersions[$key] = (int) $parts[1];
} else {
$minorVersions[$key] = 0;
}
$keyVersions[$key] = $key;
}
array_multisort(
$majorVersions,
SORT_DESC,
SORT_NUMERIC,
$minorVersions,
SORT_DESC,
SORT_NUMERIC,
$keyVersions,
SORT_ASC,
SORT_NUMERIC,
$divisionData['versions'],
);
assert(is_array($divisionData['versions']));
foreach ($divisionData['versions'] as $key => $version) {
$divisionData['versions'][$key] = json_encode($version, JSON_THROW_ON_ERROR);
}
assert(is_array($divisionData['versions']));
return $divisionData['versions'];
} | @param array<array<string>> $divisionData
@return array<string|int>
@throws JsonException | sortVersions | php | browscap/browscap | src/Browscap/Command/RewriteDivisionsCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/RewriteDivisionsCommand.php | MIT |
private function rewriteUserAgents(
array $useragentData,
SplFileInfo $file,
LoggerInterface $logger,
array $allPlatforms,
): array {
if (! array_key_exists('userAgent', $useragentData)) {
$logger->critical(
'File "{File}" is not valid! userAgent property is missing',
[
'File' => $file->getPathname(),
],
);
return [];
}
if (array_key_exists('properties', $useragentData)) {
if (! is_array($useragentData['properties'])) {
unset($useragentData['properties']);
} else {
unset(
$useragentData['properties']['Browser'],
$useragentData['properties']['Browser_Type'],
$useragentData['properties']['Browser_Maker'],
$useragentData['properties']['isSyndicationReader'],
$useragentData['properties']['Crawler'],
$useragentData['properties']['Division'],
);
if (empty($useragentData['properties'])) {
unset($useragentData['properties']);
}
}
}
if (! array_key_exists('children', $useragentData)) {
return $useragentData;
}
if (! is_array($useragentData['children'])) {
$logger->critical(
'File "{File}" is not valid! children section is not an array',
[
'File' => $file->getPathname(),
],
);
unset($useragentData['children']);
return $useragentData;
}
foreach ($useragentData['children'] as $key => $childData) {
if (! is_int($key)) {
$logger->critical(
'File "{File}" is not valid! not-numeric key in children section found',
[
'File' => $file->getPathname(),
],
);
unset($useragentData['children'][$key]);
continue;
}
$childData = $this->rewriteChildren(
$childData,
$file,
$logger,
$allPlatforms,
);
if (empty($childData)) {
$logger->critical(
'File "{File}" is not valid! children section is empty',
[
'File' => $file->getPathname(),
],
);
unset($useragentData['children'][$key]);
continue;
}
$useragentData['children'][$key] = $childData;
}
return $useragentData;
} | @param mixed[] $useragentData
@param mixed[][] $allPlatforms
@return mixed[]
@throws JsonException | rewriteUserAgents | php | browscap/browscap | src/Browscap/Command/RewriteDivisionsCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/RewriteDivisionsCommand.php | MIT |
private function rewriteChildren(
array $childData,
SplFileInfo $file,
LoggerInterface $logger,
array $allPlatforms,
): array {
if (! array_key_exists('match', $childData)) {
$logger->critical(
'File "{File}" is not valid! match property is missing',
[
'File' => $file->getPathname(),
],
);
return [];
}
if (array_key_exists('properties', $childData)) {
if (! is_array($childData['properties'])) {
unset($childData['properties']);
} else {
unset(
$childData['properties']['Browser'],
$childData['properties']['Browser_Type'],
$childData['properties']['Browser_Maker'],
$childData['properties']['isSyndicationReader'],
$childData['properties']['Crawler'],
$childData['properties']['Division'],
);
if (empty($childData['properties'])) {
unset($childData['properties']);
}
}
}
if (array_key_exists('devices', $childData)) {
if (is_array($childData['devices'])) {
//ksort($childData['devices']);
uksort($childData['devices'], 'strcasecmp');
} else {
unset($childData['devices']);
}
}
if (array_key_exists('device', $childData)) {
$logger->warning(
'File "{File}" is not valid! device property is used in section "{match}", try to use the devices property',
[
'File' => $file->getPathname(),
'match' => $childData['match'],
],
);
}
if (! array_key_exists('platforms', $childData)) {
return $childData;
}
if (! is_array($childData['platforms'])) {
unset($childData['platforms']);
return $childData;
}
if (1 >= count($childData['platforms'])) {
foreach ($childData['platforms'] as $key => $platformkey) {
unset($childData['platforms'][$key]);
$childData['platforms'][] = [$key => json_encode($platformkey, JSON_THROW_ON_ERROR)];
}
return $childData;
}
$platforms = $this->sortPlatforms(array_unique($childData['platforms']), array_keys($allPlatforms));
$currentPlatform = ['name' => '', 'major-version' => 0, 'minor-version' => 0, 'key' => ''];
$currentChunk = -1;
$chunk = [];
foreach ($platforms as $platformkey) {
$platform = $allPlatforms[$platformkey];
assert(is_array($platform));
if (
(! isset($platform['properties']['Platform']) || ! isset($platform['properties']['Platform_Version']))
&& isset($platform['inherits'])
) {
if (isset($platform['properties'])) {
$platformProperties = $platform['properties'];
} else {
$platformProperties = [];
}
do {
$parentPlatform = $allPlatforms[$platform['inherits']];
assert(is_array($parentPlatform));
$platformProperties = array_merge($parentPlatform['properties'], $platformProperties);
unset($platform['inherits']);
if (! isset($parentPlatform['inherits'])) {
continue;
}
$platform['inherits'] = $parentPlatform['inherits'];
} while (isset($platform['inherits']));
} else {
$platformProperties = $platform['properties'];
}
$split = explode('.', $platformProperties['Platform_Version'], 2);
if (! isset($split[1])) {
$split[1] = 0;
}
if (in_array($platformkey, ['OSX', 'OSX_B', 'iOS_C', 'iOS_A', 'OSX_C', 'OSX_PPC', 'iOS_A_dynamic', 'iOS_A_dynamic_11+', 'iOS_C_dynamic', 'iOS_C_dynamic_11+', 'ipadOS_dynamic'])) {
++$currentChunk;
$chunk[$currentChunk] = [json_encode($platformkey, JSON_THROW_ON_ERROR)];
$currentPlatform = ['name' => $platformProperties['Platform'], 'major-version' => $split[0], 'minor-version' => $split[1], 'key' => $platformkey];
} elseif (mb_strpos($currentPlatform['key'], 'WinXPb') !== false && mb_strpos($platformkey, 'WinXPa') !== false) {
++$currentChunk;
$chunk[$currentChunk] = [json_encode($platformkey, JSON_THROW_ON_ERROR)];
$currentPlatform = ['name' => $platformProperties['Platform'], 'major-version' => $split[0], 'minor-version' => $split[1], 'key' => $platformkey];
} elseif (mb_strpos($currentPlatform['key'], 'WinXPa') !== false && mb_strpos($platformkey, 'WinXPb') !== false) {
++$currentChunk;
$chunk[$currentChunk] = [json_encode($platformkey, JSON_THROW_ON_ERROR)];
$currentPlatform = ['name' => $platformProperties['Platform'], 'major-version' => $split[0], 'minor-version' => $split[1], 'key' => $platformkey];
} elseif (
$platformProperties['Platform'] !== $currentPlatform['name']
|| $split[0] !== $currentPlatform['major-version']
) {
++$currentChunk;
$chunk[$currentChunk] = [json_encode($platformkey, JSON_THROW_ON_ERROR)];
$currentPlatform = ['name' => $platformProperties['Platform'], 'major-version' => $split[0], 'minor-version' => $split[1], 'key' => $platformkey];
} elseif (is_numeric($platformProperties['Platform_Version']) && $split[1] > $currentPlatform['minor-version']) {
++$currentChunk;
$chunk[$currentChunk] = [json_encode($platformkey, JSON_THROW_ON_ERROR)];
$currentPlatform = ['name' => $platformProperties['Platform'], 'major-version' => $split[0], 'minor-version' => $split[1], 'key' => $platformkey];
} else {
$chunk[$currentChunk][] = json_encode($platformkey, JSON_THROW_ON_ERROR);
}
}
$childData['platforms'] = $chunk;
return $childData;
} | @param mixed[] $childData
@param mixed[][] $allPlatforms
@return mixed[]
@throws JsonException | rewriteChildren | php | browscap/browscap | src/Browscap/Command/RewriteDivisionsCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/RewriteDivisionsCommand.php | MIT |
protected function execute(InputInterface $input, OutputInterface $output): int
{
$loggerHelper = $this->getHelper('logger');
assert($loggerHelper instanceof LoggerHelper);
$logger = $loggerHelper->create($output);
$resources = $input->getOption('resources');
assert(is_string($resources));
$enginesResourcePath = $resources . '/engines';
$logger->info(sprintf('Resource folder: %s', $resources));
$schema = 'file://' . realpath(__DIR__ . '/../../../schema/engines.json');
$rewriteHelper = $this->getHelper('rewrite');
assert($rewriteHelper instanceof RewriteHelper);
$rewriteHelper->rewrite($logger, $enginesResourcePath, $schema, true);
$output->writeln('Done');
return self::SUCCESS;
} | @return int 0 if everything went fine, or an error code
@throws InvalidArgumentException
@throws LogicException
@throws InvalidNewLineString
@throws InvalidIndentStyle
@throws InvalidIndentSize
@throws InvalidJsonEncodeOptions
@throws \InvalidArgumentException | execute | php | browscap/browscap | src/Browscap/Command/RewriteEnginesCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/RewriteEnginesCommand.php | MIT |
protected function execute(InputInterface $input, OutputInterface $output): int
{
$loggerHelper = $this->getHelper('logger');
assert($loggerHelper instanceof LoggerHelper);
$logger = $loggerHelper->create($output);
$resources = $input->getOption('resources');
assert(is_string($resources));
$platformsResourcePath = $resources . '/platforms';
$logger->info(sprintf('Resource folder: %s', $resources));
$schema = 'file://' . realpath(__DIR__ . '/../../../schema/platforms.json');
$rewriteHelper = $this->getHelper('rewrite');
assert($rewriteHelper instanceof RewriteHelper);
$rewriteHelper->rewrite($logger, $platformsResourcePath, $schema, true);
$output->writeln('Done');
return self::SUCCESS;
} | @return int 0 if everything went fine, or an error code
@throws InvalidArgumentException
@throws LogicException
@throws InvalidNewLineString
@throws InvalidIndentStyle
@throws InvalidIndentSize
@throws InvalidJsonEncodeOptions
@throws \InvalidArgumentException | execute | php | browscap/browscap | src/Browscap/Command/RewritePlatformsCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/RewritePlatformsCommand.php | MIT |
protected function execute(InputInterface $input, OutputInterface $output): int
{
$loggerHelper = $this->getHelper('logger');
assert($loggerHelper instanceof LoggerHelper);
$logger = $loggerHelper->create($output);
$resourcePath = __DIR__ . '/../../../tests/fixtures';
$normalizer = new Normalizer\WithFinalNewLineNormalizer();
$format = Normalizer\Format\Format::create(
Normalizer\Format\JsonEncodeOptions::fromInt(JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT),
Normalizer\Format\Indent::fromSizeAndStyle(2, 'space'),
Normalizer\Format\NewLine::fromString("\n"),
true,
);
$finder = new Finder();
$finder->files();
$finder->name('*.json');
$finder->ignoreDotFiles(true);
$finder->ignoreVCS(true);
$finder->sortByName();
$finder->ignoreUnreadableDirs();
$finder->in($resourcePath);
foreach ($finder as $file) {
$logger->info('read source file ' . $file->getPathname());
try {
$json = $file->getContents();
} catch (RuntimeException $e) {
$logger->critical(
'File "{File}" is not readable',
[
'File' => $file->getPathname(),
'Exception' => $e,
],
);
continue;
}
try {
$chainNormalizer = new Normalizer\ChainNormalizer(
$normalizer,
new Normalizer\FormatNormalizer(new Printer(), $format),
);
$normalized = $chainNormalizer->normalize(Json\Json::fromString($json));
} catch (Throwable $e) {
$logger->critical(
'File "{File}" is not valid',
[
'File' => $file->getPathname(),
'Exception' => $e,
],
);
continue;
}
file_put_contents($file->getPathname(), $normalized);
}
$output->writeln('Done');
return self::SUCCESS;
} | @return int 0 if everything went fine, or an error code
@throws DirectoryNotFoundException
@throws InvalidNewLineString
@throws InvalidIndentStyle
@throws InvalidIndentSize
@throws InvalidJsonEncodeOptions
@throws LogicException
@throws InvalidArgumentException
@throws \InvalidArgumentException | execute | php | browscap/browscap | src/Browscap/Command/RewriteTestFixturesCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/RewriteTestFixturesCommand.php | MIT |
protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->write('validate browser files ');
$loggerHelper = $this->getHelper('logger');
assert($loggerHelper instanceof LoggerHelper);
$logger = $loggerHelper->create($output);
$resources = $input->getOption('resources');
assert(is_string($resources));
$browserResourcePath = $resources . '/browsers';
$logger->info('Resource folder: ' . $resources);
$schema = 'file://' . realpath(__DIR__ . '/../../../schema/browsers.json');
$validateHelper = $this->getHelper('validate');
assert($validateHelper instanceof ValidateHelper);
$failed = $validateHelper->validate($logger, $browserResourcePath, $schema);
if ($failed) {
$output->writeln('<fg=red>invalid</>');
return Command::FAILURE;
}
$output->writeln('<fg=green>valid</>');
return Command::SUCCESS;
} | @return int 0 if everything went fine, or an error code
@throws InvalidArgumentException
@throws LogicException
@throws \InvalidArgumentException | execute | php | browscap/browscap | src/Browscap/Command/ValidateBrowsersCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/ValidateBrowsersCommand.php | MIT |
protected function execute(InputInterface $input, OutputInterface $output): int
{
$loggerHelper = $this->getHelper('logger');
assert($loggerHelper instanceof LoggerHelper);
$logger = $loggerHelper->create($output);
$application = $this->getApplication();
if ($application === null) {
$logger->error('Could not load Application instance');
return Command::FAILURE;
}
$resources = $input->getOption('resources');
assert(is_string($resources));
$failed = false;
$command = $application->find('validate-browsers');
$input = new ArrayInput(
[
'command' => 'validate-browsers',
'--resources' => $resources,
],
);
$returnCode = $command->run($input, $output);
if (0 < $returnCode) {
$logger->error('There was an error executing the "validate-browsers" command, cannot continue.');
return Command::FAILURE;
}
$command = $application->find('validate-devices');
$input = new ArrayInput(
[
'command' => 'validate-devices',
'--resources' => $resources,
],
);
$returnCode = $command->run($input, $output);
if (0 < $returnCode) {
$logger->error('There was an error executing the "validate-devices" command, cannot continue.');
return Command::FAILURE;
}
$command = $application->find('validate-engines');
$input = new ArrayInput(
[
'command' => 'validate-engines',
'--resources' => $resources,
],
);
$returnCode = $command->run($input, $output);
if (0 < $returnCode) {
$logger->error('There was an error executing the "validate-engines" command, cannot continue.');
return Command::FAILURE;
}
$command = $application->find('validate-platforms');
$input = new ArrayInput(
[
'command' => 'validate-platforms',
'--resources' => $resources,
],
);
$returnCode = $command->run($input, $output);
if (0 < $returnCode) {
$logger->error('There was an error executing the "validate-platforms" command, cannot continue.');
return Command::FAILURE;
}
$command = $application->find('validate-core-divisions');
$input = new ArrayInput(
[
'command' => 'validate-core-divisions',
'--resources' => $resources,
],
);
$returnCode = $command->run($input, $output);
if (0 < $returnCode) {
$logger->error('There was an error executing the "validate-core-divisions" command, cannot continue.');
return Command::FAILURE;
}
$command = $application->find('validate-divisions');
$input = new ArrayInput(
[
'command' => 'validate-divisions',
'--resources' => $resources,
],
);
$returnCode = $command->run($input, $output);
if (0 < $returnCode) {
$logger->error('There was an error executing the "validate-divisions" command, cannot continue.');
return Command::FAILURE;
}
$output->writeln('<fg=green>the files are valid</>');
return Command::SUCCESS;
} | @return int 0 if everything went fine, or an error code
@throws Exception
@throws ExceptionInterface
@throws \InvalidArgumentException | execute | php | browscap/browscap | src/Browscap/Command/ValidateCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/ValidateCommand.php | MIT |
protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->write('validate core division files ');
$loggerHelper = $this->getHelper('logger');
assert($loggerHelper instanceof LoggerHelper);
$logger = $loggerHelper->create($output);
$resources = $input->getOption('resources');
assert(is_string($resources));
$coreResourcePath = $resources . '/core';
$logger->info('Resource folder: ' . $resources);
$schema = 'file://' . realpath(__DIR__ . '/../../../schema/core-divisions.json');
$validateHelper = $this->getHelper('validate');
assert($validateHelper instanceof ValidateHelper);
$failed = $validateHelper->validate($logger, $coreResourcePath, $schema);
if ($failed) {
$output->writeln('<fg=red>invalid</>');
return Command::FAILURE;
}
$output->writeln('<fg=green>valid</>');
return Command::SUCCESS;
} | @return int 0 if everything went fine, or an error code
@throws InvalidArgumentException
@throws LogicException
@throws \InvalidArgumentException | execute | php | browscap/browscap | src/Browscap/Command/ValidateCoreDivisionsCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/ValidateCoreDivisionsCommand.php | MIT |
protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->write('validate device files ');
$loggerHelper = $this->getHelper('logger');
assert($loggerHelper instanceof LoggerHelper);
$logger = $loggerHelper->create($output);
$resources = $input->getOption('resources');
assert(is_string($resources));
$devicesResourcePath = $resources . '/devices';
$logger->info('Resource folder: ' . $resources);
$schema = 'file://' . realpath(__DIR__ . '/../../../schema/devices.json');
$validateHelper = $this->getHelper('validate');
assert($validateHelper instanceof ValidateHelper);
$failed = $validateHelper->validate($logger, $devicesResourcePath, $schema);
if ($failed) {
$output->writeln('<fg=red>invalid</>');
return Command::FAILURE;
}
$output->writeln('<fg=green>valid</>');
return Command::SUCCESS;
} | @return int 0 if everything went fine, or an error code
@throws InvalidArgumentException
@throws LogicException
@throws \InvalidArgumentException | execute | php | browscap/browscap | src/Browscap/Command/ValidateDevicesCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/ValidateDevicesCommand.php | MIT |
protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->write('validate division files ');
$loggerHelper = $this->getHelper('logger');
assert($loggerHelper instanceof LoggerHelper);
$logger = $loggerHelper->create($output);
$resources = $input->getOption('resources');
assert(is_string($resources));
$divisionsResourcePath = $resources . '/user-agents';
$logger->info('Resource folder: ' . $resources);
$schema = 'file://' . realpath(__DIR__ . '/../../../schema/divisions.json');
$validateHelper = $this->getHelper('validate');
assert($validateHelper instanceof ValidateHelper);
$failed = $validateHelper->validate($logger, $divisionsResourcePath, $schema);
if ($failed) {
$output->writeln('<fg=red>invalid</>');
return Command::FAILURE;
}
$output->writeln('<fg=green>valid</>');
return Command::SUCCESS;
} | @return int 0 if everything went fine, or an error code
@throws InvalidArgumentException
@throws LogicException
@throws \InvalidArgumentException | execute | php | browscap/browscap | src/Browscap/Command/ValidateDivisionsCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/ValidateDivisionsCommand.php | MIT |
protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->write('validate engine files ');
$loggerHelper = $this->getHelper('logger');
assert($loggerHelper instanceof LoggerHelper);
$logger = $loggerHelper->create($output);
$resources = $input->getOption('resources');
assert(is_string($resources));
$enginesResourcePath = $resources . '/engines';
$logger->info('Resource folder: ' . $resources);
$schema = 'file://' . realpath(__DIR__ . '/../../../schema/engines.json');
$validateHelper = $this->getHelper('validate');
assert($validateHelper instanceof ValidateHelper);
$failed = $validateHelper->validate($logger, $enginesResourcePath, $schema);
if ($failed) {
$output->writeln('<fg=red>invalid</>');
return Command::FAILURE;
}
$output->writeln('<fg=green>valid</>');
return Command::SUCCESS;
} | @return int 0 if everything went fine, or an error code
@throws InvalidArgumentException
@throws LogicException
@throws \InvalidArgumentException | execute | php | browscap/browscap | src/Browscap/Command/ValidateEnginesCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/ValidateEnginesCommand.php | MIT |
protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->write('validate platform files ');
$loggerHelper = $this->getHelper('logger');
assert($loggerHelper instanceof LoggerHelper);
$logger = $loggerHelper->create($output);
$resources = $input->getOption('resources');
assert(is_string($resources));
$platformsResourcePath = $resources . '/platforms';
$logger->info('Resource folder: ' . $resources);
$schema = 'file://' . realpath(__DIR__ . '/../../../schema/platforms.json');
$validateHelper = $this->getHelper('validate');
assert($validateHelper instanceof ValidateHelper);
$failed = $validateHelper->validate($logger, $platformsResourcePath, $schema);
if ($failed) {
$output->writeln('<fg=red>invalid</>');
return Command::FAILURE;
}
$output->writeln('<fg=green>valid</>');
return Command::SUCCESS;
} | @return int 0 if everything went fine, or an error code
@throws InvalidArgumentException
@throws LogicException
@throws \InvalidArgumentException | execute | php | browscap/browscap | src/Browscap/Command/ValidatePlatformsCommand.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/ValidatePlatformsCommand.php | MIT |
public function create(OutputInterface $output): LoggerInterface
{
$logger = new Logger('browscap');
$consoleLogger = new ConsoleLogger($output);
$psrHandler = new PsrHandler($consoleLogger);
try {
$psrHandler->setFormatter(new LineFormatter('%message%'));
} catch (RuntimeException $e) {
throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
$logger->pushProcessor(new PsrLogMessageProcessor());
$logger->pushHandler($psrHandler);
$logger->pushHandler(new ErrorLogHandler(ErrorLogHandler::OPERATING_SYSTEM, LogLevel::NOTICE));
ErrorHandler::register($logger);
return $logger;
} | creates an instance of a PSR-3 Logger
@throws InvalidArgumentException | create | php | browscap/browscap | src/Browscap/Command/Helper/LoggerHelper.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/Helper/LoggerHelper.php | MIT |
public function rewrite(LoggerInterface $logger, string $resources, string $schema, bool $sort = false): void
{
$logger->debug('initialize rewrite helper');
$normalizer = new Normalizer\SchemaNormalizer(
$schema,
new SchemaStorage(),
new SchemaValidator(),
Pointer\Specification::never(),
);
$format = Normalizer\Format\Format::create(
Normalizer\Format\JsonEncodeOptions::fromInt(JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR),
Normalizer\Format\Indent::fromSizeAndStyle(2, 'space'),
Normalizer\Format\NewLine::fromString("\n"),
true,
);
$logger->debug('initialize file finder');
$finder = new Finder();
$finder->files();
$finder->name('*.json');
$finder->ignoreDotFiles(true);
$finder->ignoreVCS(true);
$finder->sortByName();
$finder->ignoreUnreadableDirs();
try {
$finder->in($resources);
} catch (DirectoryNotFoundException $exception) {
$logger->critical(new Exception('the resource directory was not found', 0, $exception));
return;
}
foreach ($finder as $file) {
$logger->info(sprintf('source file %s: read', $file->getPathname()));
try {
$json = $file->getContents();
} catch (RuntimeException $e) {
$logger->critical(
sprintf('File "%s" is not readable', $file->getPathname()),
['Exception' => $e],
);
continue;
}
if ($sort) {
$logger->debug(sprintf('source file %s: sort content', $file->getPathname()));
$sorterHelper = $this->helperSet->get('sorter');
assert($sorterHelper instanceof Sorter);
try {
$json = $sorterHelper->sort($json);
} catch (JsonException $e) {
$logger->critical(
sprintf('sorting File "%s" failed, because it had invalid JSON.', $file->getPathname()),
['Exception' => $e],
);
continue;
}
}
$logger->debug(sprintf('source file %s: normalize content', $file->getPathname()));
try {
$chainNormalizer = new Normalizer\ChainNormalizer(
$normalizer,
new Normalizer\FormatNormalizer(new Printer(), $format),
);
$normalized = $chainNormalizer->normalize(Json\Json::fromString($json));
} catch (Throwable $e) {
$logger->critical(
sprintf('normalizing File "%s" failed, because it had invalid JSON.', $file->getPathname()),
['Exception' => $e],
);
continue;
}
$logger->debug(sprintf('source file %s: write content', $file->getPathname()));
file_put_contents($file->getPathname(), $normalized->toString());
}
} | @throws InvalidNewLineString
@throws InvalidIndentStyle
@throws InvalidIndentSize
@throws InvalidJsonEncodeOptions | rewrite | php | browscap/browscap | src/Browscap/Command/Helper/RewriteHelper.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/Helper/RewriteHelper.php | MIT |
public function validate(LoggerInterface $logger, string $resources, string $schemaUri, string|array|null $notPath = null): bool
{
$uriRetriever = new Uri\UriRetriever();
$schemaStorage = new SchemaStorage(
$uriRetriever,
new Uri\UriResolver(),
);
$validator = new Validator(new Constraints\Factory(
$schemaStorage,
$uriRetriever,
));
$schemaDecoded = $schemaStorage->getSchema($schemaUri);
assert($schemaDecoded instanceof stdClass || $schemaDecoded === null);
if ($schemaDecoded === null) {
$logger->critical('the given json schema is invalid');
return true;
}
$failed = false;
$jsonParser = new JsonParser();
$finder = new Finder();
$finder->files();
$finder->name('*.json');
$finder->ignoreDotFiles(true);
$finder->ignoreVCS(true);
$finder->sortByName();
$finder->ignoreUnreadableDirs();
if ($notPath !== null) {
$finder->notPath($notPath);
}
try {
$finder->in($resources);
} catch (DirectoryNotFoundException $exception) {
$logger->critical(new Exception('the resource directory was not found', 0, $exception));
return true;
}
foreach ($finder as $file) {
/** @var SplFileInfo $file */
$logger->info(sprintf('source file %s: read', $file->getPathname()));
try {
$json = $file->getContents();
} catch (RuntimeException $e) {
$logger->critical(
sprintf('File "%s" is not readable', $file->getPathname()),
['Exception' => $e],
);
$failed = true;
continue;
}
try {
$logger->debug(sprintf('source file %s: validate', $file->getPathname()));
$jsonDecoded = json_decode(
$json,
false,
512,
JSON_THROW_ON_ERROR,
);
$validator->validate(
$jsonDecoded,
$schemaDecoded,
);
/** @var array<int, array<mixed>> $errors */
$errors = $validator->getErrors();
if ($errors !== []) {
$logger->critical(
'File "{File}" is not valid',
[
'File' => $file->getPathname(),
'errors' => $errors,
],
);
$failed = true;
}
} catch (JsonException $e) {
$logger->critical(
sprintf('validating File "%s" failed, because it had invalid JSON.', $file->getPathname()),
['Exception' => $e],
);
$failed = true;
continue;
}
try {
$logger->debug(sprintf('source file %s: parse with json parser', $file->getPathname()));
$jsonParser->parse($json, JsonParser::DETECT_KEY_CONFLICTS);
} catch (ParsingException $e) {
$logger->critical(
sprintf('parsing File "%s" failed, because it had invalid JSON.', $file->getPathname()),
['Exception' => $e],
);
$failed = true;
}
}
return $failed;
} | @param string|array<string>|null $notPath
@throws void | validate | php | browscap/browscap | src/Browscap/Command/Helper/ValidateHelper.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Command/Helper/ValidateHelper.php | MIT |
public function process(array $coveredIds): void
{
$this->setCoveredPatternIds($coveredIds);
$finder = new Finder();
$finder->files();
$finder->name('*.json');
$finder->ignoreDotFiles(true);
$finder->ignoreVCS(true);
$finder->sortByName();
$finder->ignoreUnreadableDirs();
$finder->in($this->resourceDir);
foreach ($finder as $file) {
assert($file instanceof SplFileInfo);
$patternFileName = mb_substr($file->getPathname(), (int) mb_strpos($file->getPathname(), 'resources/'));
assert(is_string($patternFileName));
if (! isset($this->coveredIds[$patternFileName])) {
$this->coveredIds[$patternFileName] = [];
}
$this->coverage[$patternFileName] = $this->processFile(
$patternFileName,
$file->getContents(),
$this->coveredIds[$patternFileName],
);
}
} | Process the directory of JSON files using the collected pattern ids
@param array<string> $coveredIds
@throws RuntimeException
@throws DirectoryNotFoundException | process | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
public function write(string $fileName): void
{
$content = json_encode($this->coverage, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
file_put_contents(
$fileName,
// str_replace here is to convert empty arrays into empty JS objects, which is expected by
// codecov.io. Owner of the service said he was going to patch it, haven't tested since
// Note: Can't use JSON_FORCE_OBJECT here as we **do** want arrays for the 'b' structure
// which FORCE_OBJECT turns into objects, breaking at least the Istanbul coverage reporter
str_replace('[]', '{}', $content),
);
} | Write the coverage data in JSON format to specified filename
@throws JsonException | write | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
public function setCoveredPatternIds(array $coveredIds): void
{
$this->coveredIds = $this->groupIdsByFile($coveredIds);
} | Stores passed in pattern ids, grouping them by file first
@param array<string> $coveredIds
@throws void | setCoveredPatternIds | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
public function getCoveredPatternIds(): array
{
return $this->coveredIds;
} | Returns the grouped pattern ids previously set
@return array<array<string>>
@throws void | getCoveredPatternIds | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
public function processFile(string $file, string $contents, array $coveredIds): array
{
$this->functionCoverage = [
// location information for the functions that should be covered
'fnMap' => [],
// coverage counts for the functions from fnMap
'f' => [],
];
$this->statementCoverage = [
// location information for the statements that should be covered
'statementMap' => [],
// coverage counts for the statements from statementMap
's' => [],
];
$this->branchCoverage = [
// location information for the different branch structures that should be covered
'branchMap' => [],
// coverage counts for the branches from branchMap (in array form)
'b' => [],
];
$this->fileLines = explode("\n", $contents);
$this->fileCoveredIds = $coveredIds;
$lexer = new Lexer();
$lexer->setInput($contents);
$this->handleJsonRoot($lexer);
// This re-indexes the arrays to be 1 based instead of 0, which will make them be JSON objects rather
// than arrays, which is how they're expected to be in the coverage JSON file
$this->functionCoverage['fnMap'] = array_filter(array_merge([0], $this->functionCoverage['fnMap']));
$this->statementCoverage['statementMap'] = array_filter(array_merge([0], $this->statementCoverage['statementMap']));
$this->branchCoverage['branchMap'] = array_filter(array_merge([0], $this->branchCoverage['branchMap']));
// Can't use the same method for the b/s/f sections since they can (and should) contain a 0 value, which
// array_filter would remove
array_unshift($this->branchCoverage['b'], []);
unset($this->branchCoverage['b'][0]);
array_unshift($this->functionCoverage['f'], 0);
unset($this->functionCoverage['f'][0]);
array_unshift($this->statementCoverage['s'], 0);
unset($this->statementCoverage['s'][0]);
// These keynames are expected by Istanbul compatible coverage reporters
// the format is outlined here: https://github.com/gotwarlost/istanbul/blob/master/coverage.json.md
return [
// path to file this coverage information is for (i.e. resources/user-agents/browsers/chrome/chrome.json)
'path' => $file,
// location information for the statements that should be covered
'statementMap' => $this->statementCoverage['statementMap'],
// location information for the functions that should be covered
'fnMap' => $this->functionCoverage['fnMap'],
// location information for the different branch structures that should be covered
'branchMap' => $this->branchCoverage['branchMap'],
// coverage counts for the statements from statementMap
's' => $this->statementCoverage['s'],
// coverage counts for the branches from branchMap (in array form)
'b' => $this->branchCoverage['b'],
// coverage counts for the functions from fnMap
'f' => $this->functionCoverage['f'],
];
} | Process an individual file for coverage data using covered ids
@param array<int|string, string> $coveredIds
@return array<string, array<int, string|int>|string>
@phpstan-return array{path: string, statementMap: array<int, array{start?: array{line?: int, column?: int|false}, end?: array{line?: int, column?: int|false}}>, fnMap: array<int, array{name: string, decl: array{start?: array{line: int, column: int|false}, end?: array{line: int, column: int|false}}, loc: array{start: array{line: int, column: int|false}, end: array{line: int, column: int|false}}}>, branchMap: array<int, array{type: 'switch', locations: array<int, array{start?: array{line: int, column: int|false}, end?: array{line: int, column: int|false}}>, loc:array{start: array{line: int, column: int|false}, end: array{line: int, column: int|false}}}>, s: array<int, int>, b: array<int, array<int, int>>, f: array<int, int>}
@throws void | processFile | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
private function getLocationCoordinates(Lexer $lexer, bool $end = false, string $content = ''): array
{
$lineNumber = $lexer->yylineno;
$lineContent = $this->fileLines[$lineNumber];
if ($content === '') {
$content = $lexer->yytext;
}
$position = mb_strpos($lineContent, $content);
if ($end === true) {
$position += mb_strlen($content);
}
return ['line' => $lineNumber + 1, 'column' => $position];
} | Builds the location object for the current position in the JSON file
@return array<string, float|int|false>
@phpstan-return array{line: int, column: int|false}
@throws void | getLocationCoordinates | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
private function handleJsonRoot(Lexer $lexer): void
{
do {
$code = $lexer->lex();
if ($code !== self::JSON_OBJECT_START) {
continue;
}
$code = $this->handleJsonDivision($lexer);
} while ($code !== self::JSON_EOF);
} | JSON file processing entry point
Hands execution off to applicable method when certain tokens are encountered
(in this case, Division is the only one), returns to caller when EOF is reached
@throws void | handleJsonRoot | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
private function handleJsonDivision(Lexer $lexer): int
{
$enterUaGroup = false;
do {
$code = $lexer->lex();
if ($code === self::JSON_STRING && $lexer->yytext === 'userAgents') {
$enterUaGroup = true;
} elseif ($code === self::JSON_ARRAY_START && $enterUaGroup === true) {
$code = $this->handleUseragentGroup($lexer);
$enterUaGroup = false;
} elseif ($code === self::JSON_OBJECT_START) {
$code = $this->ignoreObjectBlock($lexer);
}
} while ($code !== self::JSON_OBJECT_END);
return $lexer->lex();
} | Processes the Division block (which is the root JSON object essentially)
Lexes the main division object and hands execution off to relevant methods for further
processing. Returns the next token code returned from the lexer.
@throws void | handleJsonDivision | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
private function handleUseragentGroup(Lexer $lexer): int
{
$useragentPosition = 0;
do {
$code = $lexer->lex();
if ($code !== self::JSON_OBJECT_START) {
continue;
}
$code = $this->handleUseragentBlock($lexer, $useragentPosition);
++$useragentPosition;
} while ($code !== self::JSON_ARRAY_END);
return $lexer->lex();
} | Processes the userAgents array
@throws void | handleUseragentGroup | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
private function handleUseragentBlock(Lexer $lexer, int $useragentPosition): int
{
$enterChildGroup = false;
do {
$code = $lexer->lex();
if ($code === self::JSON_STRING && $lexer->yytext === 'children') {
$enterChildGroup = true;
} elseif ($code === self::JSON_ARRAY_START && $enterChildGroup === true) {
$code = $this->handleChildrenGroup($lexer, $useragentPosition);
$enterChildGroup = false;
} elseif ($code === self::JSON_OBJECT_START) {
$code = $this->ignoreObjectBlock($lexer);
}
} while ($code !== self::JSON_OBJECT_END);
return $lexer->lex();
} | Processes each userAgent object in the userAgents array
@throws void | handleUseragentBlock | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
private function handleChildrenGroup(Lexer $lexer, int $useragentPosition): int
{
$childPosition = 0;
do {
$code = $lexer->lex();
if ($code !== self::JSON_OBJECT_START) {
continue;
}
$code = $this->handleChildBlock($lexer, $useragentPosition, $childPosition);
++$childPosition;
} while ($code !== self::JSON_ARRAY_END);
return $lexer->lex();
} | Processes the children array of a userAgent object
@throws void | handleChildrenGroup | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
private function handleChildBlock(Lexer $lexer, int $useragentPosition, int $childPosition): int
{
$enterPlatforms = false;
$enterDevices = false;
$collectMatch = false;
$functionStart = $this->getLocationCoordinates($lexer);
$functionDeclaration = [];
do {
$code = $lexer->lex();
switch ($code) {
case self::JSON_STRING:
if ($lexer->yytext === 'platforms') {
$enterPlatforms = true;
} elseif ($lexer->yytext === 'devices') {
$enterDevices = true;
} elseif ($lexer->yytext === 'match') {
$collectMatch = true;
} elseif ($collectMatch === true) {
$collectMatch = false;
$match = $lexer->yytext;
$functionDeclaration = [
'start' => $this->getLocationCoordinates($lexer, false, '"' . $match . '"'),
'end' => $this->getLocationCoordinates($lexer, true, '"' . $match . '"'),
];
}
break;
case self::JSON_OBJECT_START:
if ($enterDevices === true) {
$code = $this->handleDeviceBlock($lexer, $useragentPosition, $childPosition);
$enterDevices = false;
} else {
$code = $this->ignoreObjectBlock($lexer);
}
break;
case self::JSON_ARRAY_START:
if ($enterPlatforms === true) {
$code = $this->handlePlatformBlock($lexer, $useragentPosition, $childPosition);
$enterPlatforms = false;
}
break;
}
} while ($code !== self::JSON_OBJECT_END);
$functionEnd = $this->getLocationCoordinates($lexer, true);
$functionCoverage = $this->getCoverageCount(
sprintf('u%d::c%d::d::p', $useragentPosition, $childPosition),
$this->fileCoveredIds,
);
$this->collectFunction($functionStart, $functionEnd, $functionDeclaration, $functionCoverage);
return $lexer->lex();
} | Processes each child object in the children array
@throws void | handleChildBlock | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
private function handleDeviceBlock(Lexer $lexer, int $useragentPosition, int $childPosition): int
{
$capturedKey = false;
$sawColon = false;
$branchStart = $this->getLocationCoordinates($lexer);
$branchLocations = [];
$branchCoverage = [];
do {
$code = $lexer->lex();
if ($code === self::JSON_STRING && $capturedKey === false) {
$branchLocations[] = [
'start' => $this->getLocationCoordinates($lexer, false, '"' . $lexer->yytext . '"'),
'end' => $this->getLocationCoordinates($lexer, true, '"' . $lexer->yytext . '"'),
];
$branchCoverage[] = $this->getCoverageCount(
sprintf('u%d::c%d::d%s::p', $useragentPosition, $childPosition, $lexer->yytext),
$this->fileCoveredIds,
);
$capturedKey = true;
} elseif ($code === self::JSON_COLON) {
$sawColon = true;
} elseif ($code === self::JSON_STRING && $sawColon === true) {
$capturedKey = false;
}
} while ($code !== self::JSON_OBJECT_END);
$branchEnd = $this->getLocationCoordinates($lexer, true);
$this->collectBranch($branchStart, $branchEnd, $branchLocations, $branchCoverage);
return $lexer->lex();
} | Process the "devices" has in the child object
@throws void | handleDeviceBlock | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
private function handlePlatformBlock(Lexer $lexer, int $useragentPosition, int $childPosition): int
{
$branchStart = $this->getLocationCoordinates($lexer);
$branchLocations = [];
$branchCoverage = [];
do {
$code = $lexer->lex();
if ($code !== self::JSON_STRING) {
continue;
}
$branchLocations[] = [
'start' => $this->getLocationCoordinates($lexer, false, '"' . $lexer->yytext . '"'),
'end' => $this->getLocationCoordinates($lexer, true, '"' . $lexer->yytext . '"'),
];
$branchCoverage[] = $this->getCoverageCount(
sprintf('u%d::c%d::d::p%s', $useragentPosition, $childPosition, $lexer->yytext),
$this->fileCoveredIds,
);
} while ($code !== self::JSON_ARRAY_END);
$branchEnd = $this->getLocationCoordinates($lexer, true);
$this->collectBranch($branchStart, $branchEnd, $branchLocations, $branchCoverage);
return $lexer->lex();
} | Processes the "platforms" hash in the child object
@throws void | handlePlatformBlock | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
private function ignoreObjectBlock(Lexer $lexer): int
{
do {
$code = $lexer->lex();
// recursively ignore nested objects
if ($code !== self::JSON_OBJECT_START) {
continue;
}
$this->ignoreObjectBlock($lexer);
} while ($code !== self::JSON_OBJECT_END);
return $lexer->lex();
} | Processes JSON object block that isn't needed for coverage data
@throws void | ignoreObjectBlock | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
private function collectFunction(array $start, array $end, array $declaration, int $coverage = 0): void
{
$this->functionCoverage['fnMap'][] = [
'name' => '(anonymous_' . $this->funcCount . ')',
'decl' => $declaration,
'loc' => ['start' => $start, 'end' => $end],
];
$this->functionCoverage['f'][] = $coverage;
// Collect statements as well, one for entire function, one just for function declaration
$this->collectStatement($start, $end, $coverage);
$this->collectStatement($declaration['start'] ?? [], $declaration['end'] ?? [], $coverage);
++$this->funcCount;
} | Collects and stores a function's location information as well as any passed in coverage counts
@param mixed[] $start
@param mixed[] $end
@param mixed[][] $declaration
@phpstan-param array{line: int, column: int|false} $start
@phpstan-param array{line: int, column: int|false} $end
@phpstan-param array{start?: array{line: int, column: int|false}, end?: array{line: int, column: int|false}} $declaration
@throws void | collectFunction | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
private function collectBranch(array $start, array $end, array $locations, array $coverage = []): void
{
$this->branchCoverage['branchMap'][] = [
'type' => 'switch',
'locations' => $locations,
'loc' => ['start' => $start, 'end' => $end],
];
$this->branchCoverage['b'][] = $coverage;
// Collect statements as well (entire branch is a statement, each location is a statement)
$this->collectStatement($start, $end, (int) array_sum($coverage));
for ($i = 0, $count = count($locations); $i < $count; ++$i) {
$this->collectStatement($locations[$i]['start'] ?? [], $locations[$i]['end'] ?? [], $coverage[$i]);
}
} | Collects and stores a branch's location information as well as any coverage counts
@param mixed[] $start
@param mixed[] $end
@param mixed[][] $locations
@param array<int, int> $coverage
@phpstan-param array{line: int, column: int|false} $start
@phpstan-param array{line: int, column: int|false} $end
@phpstan-param array<int, array{start?: array{line: int, column: int|false}, end?: array{line: int, column: int|false}}> $locations
@throws void | collectBranch | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
private function collectStatement(array $start, array $end, int $coverage = 0): void
{
$this->statementCoverage['statementMap'][] = [
'start' => $start,
'end' => $end,
];
$this->statementCoverage['s'][] = $coverage;
} | Collects and stores a statement's location information as well as any coverage counts
@param mixed[] $start
@param mixed[] $end
@phpstan-param array{line?: int, column?: int|false} $start
@phpstan-param array{line?: int, column?: int|false} $end
@throws void | collectStatement | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
private function groupIdsByFile(array $ids): array
{
$covered = [];
foreach ($ids as $id) {
$pos = mb_strpos($id, '::');
if ($pos === false) {
continue;
}
$file = mb_substr($id, 0, $pos);
if (! isset($covered[$file])) {
$covered[$file] = [];
}
$covered[$file][] = mb_substr($id, mb_strpos($id, '::') + 2);
}
return $covered;
} | Groups pattern ids by their filename prefix
@param array<string> $ids
@return array<array<string>>
@throws void | groupIdsByFile | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
private function getCoverageCount(string $id, array $covered): int
{
$id = str_replace('\/', '/', $id);
[$u, $c, $d, $p] = explode('::', $id);
$u = preg_quote(mb_substr($u, 1), '/');
$c = preg_quote(mb_substr($c, 1), '/');
$p = preg_quote(mb_substr($p, 1), '/');
$d = preg_quote(mb_substr($d, 1), '/');
$count = 0;
if (mb_strlen($p) === 0) {
$p = '.*?';
}
if (mb_strlen($d) === 0) {
$d = '.*?';
}
$regex = sprintf('/^u%d::c%d::d%s::p%s$/', $u, $c, $d, $p);
foreach ($covered as $patternId) {
if (! preg_match($regex, $patternId)) {
continue;
}
++$count;
}
return $count;
} | Counts number of times given generated pattern id is covered by patterns ids collected during tests
@param array<string> $covered
@throws void | getCoverageCount | php | browscap/browscap | src/Browscap/Coverage/Processor.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php | MIT |
public function __construct(private readonly array $properties, private readonly string $type, bool $isLite, bool $standard)
{
$this->isLite = $isLite;
$this->isStandard = $standard;
} | @param array<string, string> $properties
@phpstan-param BrowserProperties $properties
@phpstan-param BrowserType $type
@throws void | __construct | php | browscap/browscap | src/Browscap/Data/Browser.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Browser.php | MIT |
public function getProperties(): array
{
return $this->properties;
} | @return array<string, string>
@phpstan-return BrowserProperties
@throws void | getProperties | php | browscap/browscap | src/Browscap/Data/Browser.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Browser.php | MIT |
public function addPlatform(string $platformName, Platform $platform): void
{
$this->platforms[$platformName] = $platform;
$this->divisionsHaveBeenSorted = false;
} | @param string $platformName Name of the platform | addPlatform | php | browscap/browscap | src/Browscap/Data/DataCollection.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/DataCollection.php | MIT |
public function addEngine(string $engineName, Engine $engine): void
{
$this->engines[$engineName] = $engine;
$this->divisionsHaveBeenSorted = false;
} | @param string $engineName Name of the engine | addEngine | php | browscap/browscap | src/Browscap/Data/DataCollection.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/DataCollection.php | MIT |
public function addBrowser(string $browserName, Browser $browser): void
{
if (array_key_exists($browserName, $this->browsers)) {
throw new DuplicateDataException(
sprintf('it was tried to add browser "%s", but this was already added before', $browserName),
);
}
$this->browsers[$browserName] = $browser;
$this->divisionsHaveBeenSorted = false;
} | @param string $browserName Name of the browser
@throws DuplicateDataException | addBrowser | php | browscap/browscap | src/Browscap/Data/DataCollection.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/DataCollection.php | MIT |
public function addDevice(string $deviceName, Device $device): void
{
if (array_key_exists($deviceName, $this->devices)) {
throw new DuplicateDataException(
sprintf('it was tried to add device "%s", but this was already added before', $deviceName),
);
}
$this->devices[$deviceName] = $device;
$this->divisionsHaveBeenSorted = false;
} | @param string $deviceName Name of the device
@throws DuplicateDataException | addDevice | php | browscap/browscap | src/Browscap/Data/DataCollection.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/DataCollection.php | MIT |
public function setDefaultProperties(Division $division): void
{
$this->defaultProperties = $division;
$this->divisionsHaveBeenSorted = false;
} | Load the file for the default properties | setDefaultProperties | php | browscap/browscap | src/Browscap/Data/DataCollection.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/DataCollection.php | MIT |
public function setDefaultBrowser(Division $division): void
{
$this->defaultBrowser = $division;
$this->divisionsHaveBeenSorted = false;
} | Load the file for the default browser | setDefaultBrowser | php | browscap/browscap | src/Browscap/Data/DataCollection.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/DataCollection.php | MIT |
public function getDivisions(): array
{
$this->sortDivisions();
return $this->divisions;
} | Get the divisions array containing UA data
@return Division[] | getDivisions | php | browscap/browscap | src/Browscap/Data/DataCollection.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/DataCollection.php | MIT |
private function sortDivisions(): void
{
if ($this->divisionsHaveBeenSorted) {
return;
}
$sortIndex = [];
$sortPosition = [];
foreach ($this->divisions as $key => $division) {
assert($division instanceof Division);
$sortIndex[$key] = $division->getSortIndex();
$sortPosition[$key] = $key;
}
array_multisort(
$sortIndex,
SORT_ASC,
SORT_NUMERIC,
$sortPosition,
SORT_DESC,
SORT_NUMERIC, // if the sortIndex is identical the later added file comes first
$this->divisions,
);
$this->divisionsHaveBeenSorted = true;
} | Sort the divisions (if they haven't already been sorted) | sortDivisions | php | browscap/browscap | src/Browscap/Data/DataCollection.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/DataCollection.php | MIT |
public function getDefaultProperties(): Division
{
return $this->defaultProperties;
} | Get the divisions array containing UA data | getDefaultProperties | php | browscap/browscap | src/Browscap/Data/DataCollection.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/DataCollection.php | MIT |
public function getDefaultBrowser(): Division
{
return $this->defaultBrowser;
} | Get the divisions array containing UA data | getDefaultBrowser | php | browscap/browscap | src/Browscap/Data/DataCollection.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/DataCollection.php | MIT |
public function getPlatform(string $platform): Platform
{
if (! array_key_exists($platform, $this->platforms)) {
throw new OutOfBoundsException(
'Platform "' . $platform . '" does not exist in data',
);
}
return $this->platforms[$platform];
} | Get a single platform data array
@throws OutOfBoundsException | getPlatform | php | browscap/browscap | src/Browscap/Data/DataCollection.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/DataCollection.php | MIT |
public function getEngine(string $engine): Engine
{
if (! array_key_exists($engine, $this->engines)) {
throw new OutOfBoundsException(
'Rendering Engine "' . $engine . '" does not exist in data',
);
}
return $this->engines[$engine];
} | Get a single engine data array
@throws OutOfBoundsException | getEngine | php | browscap/browscap | src/Browscap/Data/DataCollection.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/DataCollection.php | MIT |
public function getBrowser(string $browser): Browser
{
if (! array_key_exists($browser, $this->browsers)) {
throw new OutOfBoundsException(
'Browser "' . $browser . '" does not exist in data',
);
}
return $this->browsers[$browser];
} | Get a single browser data array
@throws OutOfBoundsException | getBrowser | php | browscap/browscap | src/Browscap/Data/DataCollection.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/DataCollection.php | MIT |
public function getDevice(string $device): Device
{
if (! array_key_exists($device, $this->devices)) {
throw new OutOfBoundsException(
'Device "' . $device . '" does not exist in data',
);
}
return $this->devices[$device];
} | Get a single engine data array
@throws OutOfBoundsException | getDevice | php | browscap/browscap | src/Browscap/Data/DataCollection.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/DataCollection.php | MIT |
public function __construct(array $properties, string $type, bool $standard)
{
$this->type = $type;
$this->properties = $properties;
$this->standard = $standard;
} | @param array<string, string> $properties
@throws void | __construct | php | browscap/browscap | src/Browscap/Data/Device.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Device.php | MIT |
public function getProperties(): array
{
return $this->properties;
} | @return array<string, string>
@throws void | getProperties | php | browscap/browscap | src/Browscap/Data/Device.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Device.php | MIT |
public function __construct(
string $name,
int $sortIndex,
array $userAgents,
bool $lite,
bool $standard,
array $versions,
string $fileName,
) {
$this->name = $name;
$this->sortIndex = $sortIndex;
$this->userAgents = $userAgents;
$this->lite = $lite;
$this->standard = $standard;
$this->versions = $versions;
$this->fileName = $fileName;
} | @param UserAgent[] $userAgents
@param array<int, int|string> $versions
@throws void | __construct | php | browscap/browscap | src/Browscap/Data/Division.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Division.php | MIT |
public function getVersions(): array
{
return $this->versions;
} | @return array<int, int|string>
@throws void | getVersions | php | browscap/browscap | src/Browscap/Data/Division.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Division.php | MIT |
public function getProperties(): array
{
return $this->properties;
} | @return array<string, string|bool|int>
@phpstan-return EngineProperties
@throws void | getProperties | php | browscap/browscap | src/Browscap/Data/Engine.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Engine.php | MIT |
public function __construct(private LoggerInterface $logger, private DataCollection $collection)
{
$this->trimProperty = new TrimProperty();
} | Create a new data expander
@throws void | __construct | php | browscap/browscap | src/Browscap/Data/Expander.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Expander.php | MIT |
public function expand(Division $division, string $divisionName): array
{
$defaultproperties = $this->collection->getDefaultProperties()->getUserAgents()[0];
$allInputDivisions = [$defaultproperties->getUserAgent() => $defaultproperties->getProperties()];
$allExpandedDivisions = [];
foreach ($this->parseDivision($division, $divisionName) as $ua => $properties) {
assert(is_string($ua));
if (array_key_exists($ua, $allInputDivisions)) {
throw new DuplicateDataException(
sprintf(
'tried to add section "%s" for division "%s" in file "%s", but this was already added before',
$ua,
$division->getName(),
(string) realpath((string) $division->getFileName()),
),
);
}
$allInputDivisions[$ua] = $properties;
$allExpandedDivisions[$ua] = $this->expandProperties(
$ua,
$properties,
$defaultproperties->getProperties(),
$allInputDivisions,
);
}
return $allExpandedDivisions;
} | @return mixed[][]
@throws UnexpectedValueException
@throws OutOfBoundsException
@throws DuplicateDataException
@throws ParentNotDefinedException
@throws InvalidParentException | expand | php | browscap/browscap | src/Browscap/Data/Expander.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Expander.php | MIT |
private function resetPatternId(): void
{
$this->patternId = [
'division' => '',
'useragent' => '',
'platform' => '',
'device' => '',
'child' => '',
];
} | Resets the pattern id
@throws void | resetPatternId | php | browscap/browscap | src/Browscap/Data/Expander.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Expander.php | MIT |
private function parseDivision(Division $division, string $divisionName): Generator
{
$i = 0;
foreach ($division->getUserAgents() as $uaData) {
$this->resetPatternId();
$this->patternId['division'] = $division->getFileName();
$this->patternId['useragent'] = $i;
yield from $this->parseUserAgent(
$uaData,
$division->isLite(),
$division->isStandard(),
$division->getSortIndex(),
$divisionName,
);
++$i;
}
} | parses and expands a single division
@return Generator<array<string>>
@throws OutOfBoundsException | parseDivision | php | browscap/browscap | src/Browscap/Data/Expander.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Expander.php | MIT |
private function parseUserAgent(UserAgent $uaData, bool $liteUa, bool $standardUa, int $sortIndex, string $divisionName): Generator
{
$uaProperties = $uaData->getProperties();
$lite = $liteUa;
$standard = $standardUa;
if ($uaData->getPlatform() !== null) {
$this->patternId['platform'] = $uaData->getPlatform();
$platform = $this->collection->getPlatform($uaData->getPlatform());
if (! $platform->isLite()) {
$lite = false;
}
if (! $platform->isStandard()) {
$standard = false;
}
$platformProperties = $platform->getProperties();
} else {
$this->patternId['platform'] = '';
$platformProperties = [];
}
if ($uaData->getEngine() !== null) {
$engine = $this->collection->getEngine($uaData->getEngine());
$engineProperties = $engine->getProperties();
} else {
$engineProperties = [];
}
if ($uaData->getDevice() !== null) {
[$deviceProperties, $deviceStandard] = $this->getDeviceProperties($uaData->getDevice(), $standard);
assert(is_array($deviceProperties));
$standard = $standard && $deviceStandard;
} else {
$deviceProperties = [];
}
if ($uaData->getBrowser() !== null) {
[$browserProperties, $browserLite, $browserStandard] = $this->getBrowserProperties($uaData->getBrowser(), $lite, $standard);
$lite = $lite && $browserLite;
$standard = $standard && $browserStandard;
assert(is_array($browserProperties));
} else {
$browserProperties = [];
}
$ua = $uaData->getUserAgent();
yield $ua => array_merge(
[
'lite' => $lite,
'standard' => $standard,
'sortIndex' => $sortIndex,
'division' => $divisionName,
],
$platformProperties,
$engineProperties,
$deviceProperties,
$browserProperties,
$uaProperties,
);
$i = 0;
foreach ($uaData->getChildren() as $child) {
$this->patternId['child'] = $i;
assert(is_array($child));
if (isset($child['devices']) && is_array($child['devices'])) {
// Replace our device array with a single device property with our #DEVICE# token replaced
foreach ($child['devices'] as $deviceMatch => $deviceName) {
/*
* There is a device replacement like -> "2014818": "Xiaomi 2014818"
* in our data. json_decode converts the string "2014818" to an int
*/
$deviceMatch = (string) $deviceMatch;
$this->patternId['device'] = $deviceMatch;
$subChild = $child;
$subChild['match'] = str_replace('#DEVICE#', $deviceMatch, $subChild['match']);
$subChild['device'] = $deviceName;
unset($subChild['devices']);
yield from $this->parseChildren($ua, $subChild, $lite, $standard);
}
} else {
$this->patternId['device'] = '';
yield from $this->parseChildren($ua, $child, $lite, $standard);
}
++$i;
}
} | parses and expands a single User Agent block
@return Generator<array<string>>
@throws OutOfBoundsException | parseUserAgent | php | browscap/browscap | src/Browscap/Data/Expander.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Expander.php | MIT |
private function parseChildren(string $ua, array $uaDataChild, bool $liteChild = true, bool $standardChild = true): Generator
{
if (isset($uaDataChild['platforms']) && is_array($uaDataChild['platforms'])) {
foreach ($uaDataChild['platforms'] as $platformName) {
$lite = $liteChild;
$standard = $standardChild;
$this->patternId['platform'] = $platformName;
$platform = $this->collection->getPlatform($platformName);
if (! $platform->isLite()) {
$lite = false;
}
if (! $platform->isStandard()) {
$standard = false;
}
$uaBase = str_replace('#PLATFORM#', $platform->getMatch(), $uaDataChild['match']);
if (array_key_exists('engine', $uaDataChild)) {
$engine = $this->collection->getEngine($uaDataChild['engine']);
$engineProperties = $engine->getProperties();
} else {
$engineProperties = [];
}
if (array_key_exists('device', $uaDataChild)) {
[$deviceProperties, $deviceStandard] = $this->getDeviceProperties($uaDataChild['device'], $standard);
$standard = $standard && $deviceStandard;
assert(is_array($deviceProperties));
} else {
$deviceProperties = [];
}
if (array_key_exists('browser', $uaDataChild)) {
[$browserProperties, $browserLite, $browserStandard] = $this->getBrowserProperties($uaDataChild['browser'], $lite, $standard);
$lite = $lite && $browserLite;
$standard = $standard && $browserStandard;
assert(is_array($browserProperties));
} else {
$browserProperties = [];
}
$properties = array_merge(
[
'Parent' => $ua,
'lite' => $lite,
'standard' => $standard,
],
$engineProperties,
$deviceProperties,
$browserProperties,
$platform->getProperties(),
);
if (
isset($uaDataChild['properties'])
&& is_array($uaDataChild['properties'])
) {
$childProperties = $uaDataChild['properties'];
$properties = array_merge($properties, $childProperties);
}
$properties['PatternId'] = $this->getPatternId();
yield $uaBase => $properties;
}
} else {
$lite = $liteChild;
$standard = $standardChild;
if (array_key_exists('engine', $uaDataChild)) {
$engine = $this->collection->getEngine($uaDataChild['engine']);
$engineProperties = $engine->getProperties();
} else {
$engineProperties = [];
}
if (array_key_exists('device', $uaDataChild)) {
[$deviceProperties, $deviceStandard] = $this->getDeviceProperties($uaDataChild['device'], $standard);
$standard = $standard && $deviceStandard;
assert(is_array($deviceProperties));
} else {
$deviceProperties = [];
}
if (array_key_exists('browser', $uaDataChild)) {
[$browserProperties, $browserLite, $browserStandard] = $this->getBrowserProperties($uaDataChild['browser'], $lite, $standard);
$lite = $lite && $browserLite;
$standard = $standard && $browserStandard;
assert(is_array($browserProperties));
} else {
$browserProperties = [];
}
$properties = array_merge(
[
'Parent' => $ua,
'lite' => $lite,
'standard' => $standard,
],
$engineProperties,
$deviceProperties,
$browserProperties,
);
if (
isset($uaDataChild['properties'])
&& is_array($uaDataChild['properties'])
) {
$properties = array_merge($properties, $uaDataChild['properties']);
}
$uaBase = str_replace('#PLATFORM#', '', $uaDataChild['match']);
$this->patternId['platform'] = '';
$properties['PatternId'] = $this->getPatternId();
yield $uaBase => $properties;
}
} | parses and expands the children section in a single User Agent block
@param mixed[] $uaDataChild
@return Generator<array<string>>
@throws OutOfBoundsException | parseChildren | php | browscap/browscap | src/Browscap/Data/Expander.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Expander.php | MIT |
private function getBrowserProperties(string $browserkey, bool $lite, bool $standard): array
{
$browser = $this->collection->getBrowser($browserkey);
$browserProperties = $browser->getProperties();
if (! $browser->isStandard()) {
$standard = false;
}
if (! $browser->isLite()) {
$lite = false;
}
$browserTypeLoader = new BrowserTypeLoader();
try {
$browserType = $browserTypeLoader->load($browser->getType());
$browserProperties['isSyndicationReader'] = $browserType->isSyndicationReader();
$browserProperties['Crawler'] = $browserType->isBot();
$browserProperties['Browser_Type'] = ($browserType->getName() ?? 'unknown');
} catch (BrowserNotFoundException $e) {
$this->logger->critical($e);
$browserProperties['isSyndicationReader'] = false;
$browserProperties['Crawler'] = false;
$browserProperties['Browser_Type'] = 'unknown';
}
return [$browserProperties, $lite, $standard];
} | @return array<int, array<bool|string>|bool>
@throws OutOfBoundsException | getBrowserProperties | php | browscap/browscap | src/Browscap/Data/Expander.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Expander.php | MIT |
private function getPatternId(): string
{
return sprintf(
'%s::u%d::c%d::d%s::p%s',
$this->patternId['division'],
$this->patternId['useragent'],
$this->patternId['child'],
$this->patternId['device'],
$this->patternId['platform'],
);
} | Builds and returns the string pattern id from the array components
@throws void | getPatternId | php | browscap/browscap | src/Browscap/Data/Expander.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Expander.php | MIT |
private function expandProperties(string $ua, array $properties, array $defaultproperties, array $allInputDivisions): array
{
$this->logger->debug('expand all properties for useragent "' . $ua . '"');
$userAgent = $ua;
$parents = [$userAgent];
while (isset($allInputDivisions[$userAgent]['Parent'])) {
if ($allInputDivisions[$userAgent]['Parent'] === $userAgent) {
throw new InvalidParentException(sprintf('useragent "%s" defines itself as parent', $ua));
}
$parents[] = $allInputDivisions[$userAgent]['Parent'];
$userAgent = $allInputDivisions[$userAgent]['Parent'];
}
unset($userAgent);
$parents = array_reverse($parents);
$browserData = $defaultproperties;
foreach ($parents as $parent) {
assert(is_string($parent));
if (! isset($allInputDivisions[$parent])) {
throw new ParentNotDefinedException(
sprintf('the parent "%s" for useragent "%s" is not defined', $parent, $ua),
);
}
if (! is_array($allInputDivisions[$parent])) {
throw new UnexpectedValueException(
'Parent "' . $parent . '" is not an array for useragent "' . $ua . '"',
);
}
if (
$ua !== $parent
&& isset($allInputDivisions[$parent]['sortIndex'], $properties['sortIndex'])
&& ($allInputDivisions[$parent]['division'] !== $properties['division'])
) {
if ($allInputDivisions[$parent]['sortIndex'] >= $properties['sortIndex']) {
throw new UnexpectedValueException(
'sorting not ready for useragent "'
. $ua . '"',
);
}
}
$browserData = array_merge($browserData, $allInputDivisions[$parent]);
}
array_pop($parents);
$browserData['Parents'] = implode(',', $parents);
unset($parents);
foreach (array_keys($browserData) as $propertyName) {
$properties[$propertyName] = $browserData[$propertyName];
if (! is_string($browserData[$propertyName])) {
continue;
}
$properties[$propertyName] = $this->trimProperty->trim($browserData[$propertyName]);
}
unset($browserData);
if (! isset($properties['Version'])) {
throw new UnexpectedValueException('Version property not found for useragent "' . $ua . '"');
}
$completeVersions = explode('.', $properties['Version'], 2);
$properties['MajorVer'] = $completeVersions[0];
$properties['MinorVer'] = $completeVersions[1] ?? '0';
return $properties;
} | expands all properties for one useragent to make sure all properties are set and make it possible to skip
incomplete properties and remove duplicate definitions
@param array<string> $properties
@param array<string> $defaultproperties
@param mixed[][] $allInputDivisions
@return mixed[]
@throws UnexpectedValueException
@throws ParentNotDefinedException
@throws InvalidParentException | expandProperties | php | browscap/browscap | src/Browscap/Data/Expander.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Expander.php | MIT |
public function __construct(string $match, private readonly array $properties, bool $isLite, bool $standard)
{
$this->match = $match;
$this->isLite = $isLite;
$this->isStandard = $standard;
} | @param array<string, string|int|bool> $properties
@phpstan-param PlatformProperties $properties
@throws void | __construct | php | browscap/browscap | src/Browscap/Data/Platform.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Platform.php | MIT |
public function getProperties(): array
{
return $this->properties;
} | @return array<string, string|int|bool>
@phpstan-return PlatformProperties
@throws void | getProperties | php | browscap/browscap | src/Browscap/Data/Platform.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Platform.php | MIT |
public function getPropertyType(string $propertyName): string
{
$stringProperties = [
'Comment' => 1,
'Browser' => 1,
'Browser_Maker' => 1,
'Browser_Modus' => 1,
'Browser_Type' => 1,
'Platform' => 1,
'Platform_Name' => 1,
'Platform_Description' => 1,
'Device_Name' => 1,
'Platform_Maker' => 1,
'Device_Code_Name' => 1,
'Device_Maker' => 1,
'Device_Brand_Name' => 1,
'Device_Type' => 1,
'RenderingEngine_Name' => 1,
'RenderingEngine_Description' => 1,
'RenderingEngine_Maker' => 1,
'Parent' => 1,
'PropertyName' => 1,
'PatternId' => 1,
];
if (isset($stringProperties[$propertyName])) {
return self::TYPE_STRING;
}
$arrayProperties = [
'Device_Pointing_Method' => 1,
'Browser_Bits' => 1,
'Platform_Bits' => 1,
];
if (isset($arrayProperties[$propertyName])) {
return self::TYPE_IN_ARRAY;
}
$genericProperties = [
'Platform_Version' => 1,
'RenderingEngine_Version' => 1,
];
if (isset($genericProperties[$propertyName])) {
return self::TYPE_GENERIC;
}
$numericProperties = [
'Version' => 1,
'CssVersion' => 1,
'AolVersion' => 1,
'MajorVer' => 1,
'MinorVer' => 1,
];
if (isset($numericProperties[$propertyName])) {
return self::TYPE_NUMBER;
}
$booleanProperties = [
'Alpha' => 1,
'Beta' => 1,
'Win16' => 1,
'Win32' => 1,
'Win64' => 1,
'Frames' => 1,
'IFrames' => 1,
'Tables' => 1,
'Cookies' => 1,
'BackgroundSounds' => 1,
'JavaScript' => 1,
'VBScript' => 1,
'JavaApplets' => 1,
'ActiveXControls' => 1,
'isMobileDevice' => 1,
'isTablet' => 1,
'isSyndicationReader' => 1,
'Crawler' => 1,
'MasterParent' => 1,
'LiteMode' => 1,
'isFake' => 1,
'isAnonymized' => 1,
'isModified' => 1,
];
if (isset($booleanProperties[$propertyName])) {
return self::TYPE_BOOLEAN;
}
throw new InvalidArgumentException(sprintf('Property %s did not have a defined property type', $propertyName));
} | Get the type of a property
@throws InvalidArgumentException | getPropertyType | php | browscap/browscap | src/Browscap/Data/PropertyHolder.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/PropertyHolder.php | MIT |
public function isLiteModeProperty(string $propertyName, WriterInterface $writer): bool
{
$outputProperties = [
'Parent' => 1,
'Comment' => 1,
'Browser' => 1,
'Platform' => 1,
'Version' => 1,
'isMobileDevice' => 1,
'isTablet' => 1,
'Device_Type' => 1,
];
if (isset($outputProperties[$propertyName])) {
return true;
}
if ($writer->getType() === WriterInterface::TYPE_INI) {
$additionalProperties = ['PatternId'];
if (in_array($propertyName, $additionalProperties)) {
return true;
}
}
return false;
} | Determine if the specified property is an property that should
be included in the all versions of the files
@throws void | isLiteModeProperty | php | browscap/browscap | src/Browscap/Data/PropertyHolder.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/PropertyHolder.php | MIT |
public function isStandardModeProperty(string $propertyName, WriterInterface $writer): bool
{
$outputProperties = [
'MajorVer' => 1,
'MinorVer' => 1,
'Crawler' => 1,
'Browser_Maker' => 1,
'Device_Pointing_Method' => 1,
];
if (isset($outputProperties[$propertyName])) {
return true;
}
if (in_array($writer->getType(), [WriterInterface::TYPE_CSV, WriterInterface::TYPE_XML])) {
$additionalProperties = ['PropertyName', 'MasterParent', 'LiteMode'];
if (in_array($propertyName, $additionalProperties)) {
return true;
}
}
return false;
} | Determine if the specified property is an property that should
be included in the "standard" or "full" versions of the files only
@throws void | isStandardModeProperty | php | browscap/browscap | src/Browscap/Data/PropertyHolder.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/PropertyHolder.php | MIT |
public function isOutputProperty(string $propertyName, WriterInterface $writer): bool
{
$outputProperties = [
'Comment' => 1,
'Browser' => 1,
'Browser_Maker' => 1,
'Browser_Modus' => 1,
'Platform' => 1,
'Platform_Name' => 1,
'Platform_Description' => 1,
'Device_Name' => 1,
'Platform_Maker' => 1,
'Device_Code_Name' => 1,
'Device_Maker' => 1,
'Device_Brand_Name' => 1,
'RenderingEngine_Name' => 1,
'RenderingEngine_Description' => 1,
'RenderingEngine_Maker' => 1,
'Parent' => 1,
'Browser_Type' => 1,
'Device_Type' => 1,
'Device_Pointing_Method' => 1,
'Browser_Bits' => 1,
'Platform_Bits' => 1,
'Platform_Version' => 1,
'RenderingEngine_Version' => 1,
'Version' => 1,
'CssVersion' => 1,
'AolVersion' => 1,
'MajorVer' => 1,
'MinorVer' => 1,
'Alpha' => 1,
'Beta' => 1,
'Win16' => 1,
'Win32' => 1,
'Win64' => 1,
'Frames' => 1,
'IFrames' => 1,
'Tables' => 1,
'Cookies' => 1,
'BackgroundSounds' => 1,
'JavaScript' => 1,
'VBScript' => 1,
'JavaApplets' => 1,
'ActiveXControls' => 1,
'isMobileDevice' => 1,
'isTablet' => 1,
'isSyndicationReader' => 1,
'Crawler' => 1,
'isFake' => 1,
'isAnonymized' => 1,
'isModified' => 1,
];
if (isset($outputProperties[$propertyName])) {
return true;
}
if (in_array($writer->getType(), [WriterInterface::TYPE_CSV, WriterInterface::TYPE_XML])) {
$additionalProperties = ['PropertyName', 'MasterParent', 'LiteMode'];
if (in_array($propertyName, $additionalProperties)) {
return true;
}
}
if ($writer->getType() === WriterInterface::TYPE_INI) {
if ($propertyName === 'PatternId') {
return true;
}
}
return false;
} | Determine if the specified property is an "extra" property (that should
be included in any version of the files)
@throws void | isOutputProperty | php | browscap/browscap | src/Browscap/Data/PropertyHolder.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/PropertyHolder.php | MIT |
public function isDeprecatedProperty(string $propertyName): bool
{
$deprecatedProperties = [
'Win16' => 1,
'Win32' => 1,
'Win64' => 1,
'isMobileDevice' => 1,
'isTablet' => 1,
'Crawler' => 1,
'AolVersion' => 1,
'MajorVer' => 1,
'MinorVer' => 1,
];
return isset($deprecatedProperties[$propertyName]);
} | Determine if the specified property is marked as "deprecated"
@throws void | isDeprecatedProperty | php | browscap/browscap | src/Browscap/Data/PropertyHolder.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/PropertyHolder.php | MIT |
public function __construct(
string $userAgent,
private readonly array $properties,
array $children = [],
string|null $platform = null,
string|null $engine = null,
string|null $device = null,
string|null $browser = null,
) {
$this->userAgent = $userAgent;
$this->children = $children;
$this->platform = $platform;
$this->engine = $engine;
$this->device = $device;
$this->browser = $browser;
} | @param array<string> $properties
@param array<mixed> $children
@phpstan-param UserAgentProperties $properties
@phpstan-param array<UserAgentChild> $children
@throws void | __construct | php | browscap/browscap | src/Browscap/Data/UserAgent.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/UserAgent.php | MIT |
public function getProperties(): array
{
return $this->properties;
} | @return array<string>
@phpstan-return UserAgentProperties
@throws void | getProperties | php | browscap/browscap | src/Browscap/Data/UserAgent.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/UserAgent.php | MIT |
public function getChildren(): array
{
return $this->children;
} | @return array<mixed>
@phpstan-return array<UserAgentChild>
@throws void | getChildren | php | browscap/browscap | src/Browscap/Data/UserAgent.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/UserAgent.php | MIT |
public function build(array $browserData, string $browserName): Browser
{
if (! isset($browserData['properties']) || ! is_array($browserData['properties'])) {
$browserData['properties'] = [];
}
Assertion::keyExists($browserData, 'standard', 'the value for "standard" key is missing for browser "' . $browserName . '"');
Assertion::boolean($browserData['standard']);
Assertion::keyExists($browserData, 'lite', 'the value for "lite" key is missing for browser "' . $browserName . '"');
Assertion::boolean($browserData['lite']);
Assertion::keyExists($browserData, 'type', 'the value for "type" key is missing for browser "' . $browserName . '"');
Assertion::string($browserData['type']);
// check for available values in external library
if (! (new TypeLoader())->has($browserData['type'])) {
throw new UnexpectedValueException('unsupported browser type given for browser "' . $browserName . '"');
}
// check for supported values (browscap-php) @todo remove asap
Assertion::inArray($browserData['type'], ['application', 'bot', 'bot-syndication-reader', 'bot-trancoder', 'browser', 'email-client', 'feed-reader', 'library', 'multimedia-player', 'offline-browser', 'tool', 'transcoder', 'useragent-anonymizer', 'unknown']);
return new Browser($browserData['properties'], $browserData['type'], $browserData['lite'], $browserData['standard']);
} | validates the $browserData array and creates Browser objects from it
@param mixed[] $browserData
@phpstan-param BrowserData $browserData
@throws RuntimeException if the file does not exist or has invalid JSON.
@throws AssertionFailedException | build | php | browscap/browscap | src/Browscap/Data/Factory/BrowserFactory.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Factory/BrowserFactory.php | MIT |
public function createDataCollection(string $resourceFolder): DataCollection
{
$iterator = static function (string $directory, LoggerInterface $logger, callable $function): void {
if (! file_exists($directory)) {
throw new RuntimeException('Directory "' . $directory . '" does not exist.');
}
$addedFiles = 0;
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
assert($file instanceof SplFileInfo);
if (! $file->isFile() || $file->getExtension() !== 'json') {
continue;
}
$logger->debug('add file ' . $file->getPathname());
$function($file->getPathname());
++$addedFiles;
}
if (! $addedFiles) {
throw new RuntimeException('Directory "' . $directory . '" was empty.');
}
};
$this->logger->debug('add platform file');
$iterator(
$resourceFolder . '/platforms',
$this->logger,
function (string $file): void {
$this->addPlatformsFile($file);
},
);
$this->logger->debug('add engine file');
$iterator(
$resourceFolder . '/engines',
$this->logger,
function (string $file): void {
$this->addEnginesFile($file);
},
);
$this->logger->debug('add file for default properties');
$this->setDefaultProperties($resourceFolder . '/core/default-properties.json');
$this->logger->debug('add file for default browser');
$this->setDefaultBrowser($resourceFolder . '/core/default-browser.json');
$iterator(
$resourceFolder . '/devices',
$this->logger,
function (string $file): void {
$this->addDevicesFile($file);
},
);
$iterator(
$resourceFolder . '/browsers',
$this->logger,
function (string $file): void {
$this->addBrowserFile($file);
},
);
$iterator(
$resourceFolder . '/user-agents',
$this->logger,
function (string $file): void {
$this->addSourceFile($file);
},
);
return $this->collection;
} | Create and populate a data collection object from a resource folder
@throws AssertionFailedException
@throws RuntimeException
@throws UnexpectedValueException
@throws LogicException | createDataCollection | php | browscap/browscap | src/Browscap/Data/Factory/DataCollectionFactory.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Factory/DataCollectionFactory.php | MIT |
public function addPlatformsFile(string $filename): void
{
/** @var mixed[][] $decodedFileContent */
/** @phpstan-var array<PlatformData> $decodedFileContent */
$decodedFileContent = $this->loadFile($filename);
$platformFactory = new PlatformFactory();
foreach (array_keys($decodedFileContent) as $platformName) {
$platformName = (string) $platformName;
/** @phpstan-var PlatformData $platformData */
$platformData = $decodedFileContent[$platformName];
$this->collection->addPlatform(
$platformName,
$platformFactory->build($platformData, $decodedFileContent, $platformName),
);
}
} | Load a platforms.json file and parse it into the platforms data array, validates these data and creates a
collection of Platform objects
@param string $filename Name of the file
@throws RuntimeException if the file does not exist or has invalid JSON.
@throws UnexpectedValueException
@throws AssertionFailedException | addPlatformsFile | php | browscap/browscap | src/Browscap/Data/Factory/DataCollectionFactory.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Factory/DataCollectionFactory.php | MIT |
public function addEnginesFile(string $filename): void
{
/** @var mixed[][] $decodedFileContent */
/** @phpstan-var array<EngineData> $decodedFileContent */
$decodedFileContent = $this->loadFile($filename);
$engineFactory = new EngineFactory();
foreach (array_keys($decodedFileContent) as $engineName) {
$engineName = (string) $engineName;
/** @phpstan-var EngineData $engineData */
$engineData = $decodedFileContent[$engineName];
$this->collection->addEngine(
$engineName,
$engineFactory->build($engineData, $decodedFileContent, $engineName),
);
}
} | Load a engines.json file and parse it into the platforms data array, validates these data and creates a
collection of Engine objects
@param string $filename Name of the file
@throws RuntimeException if the file does not exist or has invalid JSON.
@throws AssertionFailedException | addEnginesFile | php | browscap/browscap | src/Browscap/Data/Factory/DataCollectionFactory.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Factory/DataCollectionFactory.php | MIT |
public function addBrowserFile(string $filename): void
{
/** @var mixed[][] $decodedFileContent */
/** @phpstan-var array<BrowserData> $decodedFileContent */
$decodedFileContent = $this->loadFile($filename);
Assertion::isArray($decodedFileContent, 'required "browsers" structure has to be an array');
$browserFactory = new BrowserFactory();
foreach (array_keys($decodedFileContent) as $browserName) {
/** @phpstan-var BrowserData $browserData */
$browserData = $decodedFileContent[$browserName];
$browserName = (string) $browserName;
$this->collection->addBrowser($browserName, $browserFactory->build($browserData, $browserName));
}
} | Load a browsers.json file and parse it into the browsers data array, validates these data and creates a
collection of Browser objects
@param string $filename Name of the file
@throws RuntimeException if the file does not exist or has invalid JSON.
@throws AssertionFailedException
@throws DuplicateDataException | addBrowserFile | php | browscap/browscap | src/Browscap/Data/Factory/DataCollectionFactory.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Factory/DataCollectionFactory.php | MIT |
public function addDevicesFile(string $filename): void
{
/** @var mixed[][] $decodedFileContent */
/** @phpstan-var array<DeviceData> $decodedFileContent */
$decodedFileContent = $this->loadFile($filename);
foreach ($decodedFileContent as $deviceName => $deviceData) {
/** @phpstan-var DeviceData $deviceData */
assert(is_array($deviceData));
$this->collection->addDevice($deviceName, $this->deviceFactory->build($deviceData, $deviceName));
}
} | Load a devices.json file and parse it into the platforms data array, validates these data and creates a
collection of Device objects
@param string $filename Name of the file
@throws AssertionFailedException
@throws RuntimeException if the file does not exist or has invalid JSON.
@throws DuplicateDataException | addDevicesFile | php | browscap/browscap | src/Browscap/Data/Factory/DataCollectionFactory.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Factory/DataCollectionFactory.php | MIT |
public function addSourceFile(string $filename): void
{
/** @phpstan-var DivisionData $divisionData */
$divisionData = $this->loadFile($filename);
$this->allDivisions = $this->divisionDataValidator->validate($divisionData, $filename, $this->allDivisions, false);
$this->collection->addDivision(
$this->divisionFactory->build(
$divisionData,
$filename,
false,
),
);
} | Load a JSON file, parse it's JSON to arrays, validates these data and creates a
collection of Division objects
@param string $filename Name of the file
@throws AssertionFailedException
@throws RuntimeException If the file does not exist or has invalid JSON.
@throws LogicException | addSourceFile | php | browscap/browscap | src/Browscap/Data/Factory/DataCollectionFactory.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Factory/DataCollectionFactory.php | MIT |
public function setDefaultProperties(string $filename): void
{
/** @phpstan-var DivisionData $divisionData */
$divisionData = $this->loadFile($filename);
$this->divisionDataValidator->validate($divisionData, $filename, $this->allDivisions, true);
$this->collection->setDefaultProperties(
$this->divisionFactory->build(
$divisionData,
$filename,
true,
),
);
} | Load the file for the default properties
@param string $filename Name of the file
@throws AssertionFailedException
@throws RuntimeException if the file does not exist or has invalid JSON.
@throws LogicException | setDefaultProperties | php | browscap/browscap | src/Browscap/Data/Factory/DataCollectionFactory.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Factory/DataCollectionFactory.php | MIT |
public function setDefaultBrowser(string $filename): void
{
/** @phpstan-var DivisionData $divisionData */
$divisionData = $this->loadFile($filename);
$this->divisionDataValidator->validate($divisionData, $filename, $this->allDivisions, true);
$this->collection->setDefaultBrowser(
$this->divisionFactory->build(
$divisionData,
$filename,
true,
),
);
} | Load the file for the default browser
@param string $filename Name of the file
@throws AssertionFailedException
@throws RuntimeException if the file does not exist or has invalid JSON.
@throws LogicException | setDefaultBrowser | php | browscap/browscap | src/Browscap/Data/Factory/DataCollectionFactory.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Factory/DataCollectionFactory.php | MIT |
private function loadFile(string $filename): array
{
Assertion::file($filename, 'File "' . $filename . '" does not exist.');
Assertion::readable($filename, 'File "' . $filename . '" is not readable.');
$fileContent = file_get_contents($filename);
assert(is_string($fileContent));
Assertion::string($fileContent);
Assertion::notRegex($fileContent, '/[^ -~\s]/', 'File "' . $filename . '" contains Non-ASCII-Characters.');
try {
$parsedContent = json_decode($fileContent, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
throw new RuntimeException(
'File "' . $filename . '" had invalid JSON.',
0,
$e,
);
}
assert(is_array($parsedContent));
return $parsedContent;
} | @return mixed[][]
@throws RuntimeException
@throws AssertionFailedException | loadFile | php | browscap/browscap | src/Browscap/Data/Factory/DataCollectionFactory.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Factory/DataCollectionFactory.php | MIT |
public function build(array $deviceData, string $deviceName): Device
{
Assertion::keyExists($deviceData, 'standard', 'the value for "standard" key is missing for device "' . $deviceName . '"');
Assertion::boolean($deviceData['standard'], 'the value for "standard" key has to be a boolean value for device "' . $deviceName . '"');
Assertion::keyExists($deviceData, 'properties', 'required attibute "properties" is missing for device "' . $deviceName . '"');
Assertion::isArray($deviceData['properties'], 'the value for "properties" key has to be an array for device "' . $deviceName . '"');
Assertion::keyExists($deviceData, 'type', 'the value for "type" key is missing for device "' . $deviceName . '"');
Assertion::string($deviceData['type']);
// check for available values in external library
if (! (new TypeLoader())->has($deviceData['type'])) {
throw new UnexpectedValueException('unsupported device type given for device "' . $deviceName . '"');
}
// check for supported values (browscap-php) @todo remove asap
Assertion::inArray($deviceData['type'], ['car-entertainment-system', 'console', 'desktop', 'digital-camera', 'ebook-reader', 'feature-phone', 'fone-pad', 'mobile-console', 'mobile-device', 'mobile-phone', 'smartphone', 'tablet', 'tv', 'tv-console', 'unknown']);
return new Device($deviceData['properties'], $deviceData['type'], $deviceData['standard']);
} | validates the $deviceData array and creates Device objects from it
@param mixed[] $deviceData The Device data for the current object
@param string $deviceName The name for the current device
@phpstan-param DeviceData $deviceData
@throws RuntimeException if the file does not exist or has invalid JSON.
@throws AssertionFailedException | build | php | browscap/browscap | src/Browscap/Data/Factory/DeviceFactory.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Factory/DeviceFactory.php | MIT |
public function build(
array $divisionData,
string $filename,
bool $isCore,
): Division {
if (isset($divisionData['versions']) && is_array($divisionData['versions'])) {
$versions = $divisionData['versions'];
} else {
$versions = ['0.0'];
}
return new Division(
$divisionData['division'],
(int) $divisionData['sortIndex'],
$this->useragentFactory->build($divisionData['userAgents'], $isCore),
(bool) $divisionData['lite'],
(bool) $divisionData['standard'],
$versions,
mb_substr($filename, (int) mb_strpos($filename, 'resources/')),
);
} | validates the $divisionData array and creates Division objects from it
@param mixed[] $divisionData
@phpstan-param DivisionData $divisionData | build | php | browscap/browscap | src/Browscap/Data/Factory/DivisionFactory.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Factory/DivisionFactory.php | MIT |
public function build(array $engineData, array $dataAllEngines, string $engineName): Engine
{
Assertion::isArray($engineData, 'each entry inside the "engines" structure has to be an array');
if (! array_key_exists('properties', $engineData) && ! array_key_exists('inherits', $engineData)) {
throw new UnexpectedValueException('required attibute "properties" is missing');
}
if (! array_key_exists('properties', $engineData) || ! is_array($engineData['properties'])) {
$engineData['properties'] = [];
}
if (array_key_exists('inherits', $engineData)) {
Assertion::string($engineData['inherits'], 'parent Engine key has to be a string for engine "' . $engineName . '"');
$parentName = $engineData['inherits'];
Assertion::keyExists($dataAllEngines, $parentName, 'parent Engine "' . $parentName . '" is missing for engine "' . $engineName . '"');
$parentEngine = $this->build($dataAllEngines[$parentName], $dataAllEngines, $parentName);
$parentEngineData = $parentEngine->getProperties();
$engineProperties = $engineData['properties'];
foreach ($engineProperties as $name => $value) {
if (
array_key_exists($name, $parentEngineData)
&& $parentEngineData[$name] === $value
) {
throw new UnexpectedValueException(
'the value for property "' . $name . '" has the same value in the keys "' . $engineName
. '" and its parent "' . $parentName . '"',
);
}
}
$engineData['properties'] = array_merge(
$parentEngineData,
$engineProperties,
);
}
return new Engine($engineData['properties']);
} | validates the $engineData array and creates Engine objects from it
@param mixed[] $engineData The Engine data for the current object
@param mixed[][] $dataAllEngines The Engine data for all engines
@param string $engineName The name for the current engine
@phpstan-param EngineData $engineData
@phpstan-param array<string, EngineData> $dataAllEngines
@throws RuntimeException if the file does not exist or has invalid JSON.
@throws AssertionFailedException | build | php | browscap/browscap | src/Browscap/Data/Factory/EngineFactory.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Factory/EngineFactory.php | MIT |
public function build(array $platformData, array $dataAllPlatforms, string $platformName): Platform
{
Assertion::isArray($platformData, 'each entry has to be an array');
Assertion::keyExists($platformData, 'lite', 'the value for "lite" key is missing for the platform with the key "' . $platformName . '"');
Assertion::keyExists($platformData, 'standard', 'the value for "standard" key is missing for the platform with the key "' . $platformName . '"');
Assertion::keyExists($platformData, 'match', 'the value for the "match" key is missing for the platform with the key "' . $platformName . '"');
if (! array_key_exists('properties', $platformData) && ! array_key_exists('inherits', $platformData)) {
throw new UnexpectedValueException('required attibute "properties" is missing');
}
if (! array_key_exists('properties', $platformData)) {
$platformData['properties'] = [];
}
if (array_key_exists('inherits', $platformData)) {
Assertion::string($platformData['inherits'], 'parent Platform key has to be a string for platform "' . $platformName . '"');
$parentName = $platformData['inherits'];
Assertion::keyExists($dataAllPlatforms, $parentName, 'parent Platform "' . $parentName . '" is missing for platform "' . $platformName . '"');
$parentPlatform = $this->build($dataAllPlatforms[$parentName], $dataAllPlatforms, $parentName);
$parentPlatformData = $parentPlatform->getProperties();
/** @phpstan-var PlatformProperties $platformProperties */
$platformProperties = $platformData['properties'];
foreach ($platformProperties as $name => $value) {
assert(is_string($name));
if (array_key_exists($name, $parentPlatformData) && $parentPlatformData[$name] === $value) {
throw new UnexpectedValueException(
'the value for property "' . $name . '" has the same value in the keys "' . $platformName
. '" and its parent "' . $parentName . '"',
);
}
}
$platformData['properties'] = array_merge(
$parentPlatformData,
$platformProperties,
);
if (! $parentPlatform->isLite()) {
$platformData['lite'] = false;
}
if (! $parentPlatform->isStandard()) {
$platformData['standard'] = false;
}
}
return new Platform(
$platformData['match'],
$platformData['properties'],
$platformData['lite'],
$platformData['standard'],
);
} | validates the $platformData array and creates Platform objects from it
@param mixed[] $platformData The Platform data for the current object
@param mixed[][] $dataAllPlatforms The Platform data for all platforms
@param string $platformName The name for the current platform
@phpstan-param PlatformData $platformData
@phpstan-param array<string, PlatformData> $dataAllPlatforms
@throws RuntimeException if the file does not exist or has invalid JSON.
@throws UnexpectedValueException
@throws AssertionFailedException | build | php | browscap/browscap | src/Browscap/Data/Factory/PlatformFactory.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Factory/PlatformFactory.php | MIT |
public function build(array $userAgentsData, bool $isCore): array
{
$useragents = [];
foreach ($userAgentsData as $useragent) {
$children = [];
if (! $isCore) {
$children = $useragent['children'] ?? [];
}
$useragents[] = new UserAgent(
$useragent['userAgent'],
$useragent['properties'],
$children,
$useragent['platform'] ?? null,
$useragent['engine'] ?? null,
$useragent['device'] ?? null,
$useragent['browser'] ?? null,
);
}
return $useragents;
} | validates the $userAgentsData array and creates at least one Useragent object from it
@param mixed[][] $userAgentsData
@phpstan-param array<UserAgentData> $userAgentsData
@return UserAgent[] | build | php | browscap/browscap | src/Browscap/Data/Factory/UserAgentFactory.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Factory/UserAgentFactory.php | MIT |
public function getVersionParts(string $version): array
{
$dots = explode('.', $version, 2);
$majorVer = $dots[0];
$minorVer = ($dots[1] ?? '0');
return [$majorVer, $minorVer];
} | splits a version into the major and the minor version
@return array<string> | getVersionParts | php | browscap/browscap | src/Browscap/Data/Helper/SplitVersion.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Helper/SplitVersion.php | MIT |
public function trim(string $propertyValue): bool|string
{
switch ($propertyValue) {
case 'true':
$propertyValue = true;
break;
case 'false':
$propertyValue = false;
break;
default:
$propertyValue = trim($propertyValue);
break;
}
return $propertyValue;
} | trims the value of a property and converts the string values "true" and "false" to boolean | trim | php | browscap/browscap | src/Browscap/Data/Helper/TrimProperty.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Helper/TrimProperty.php | MIT |
public function replace(string $value, string $majorVer, string $minorVer): string
{
return str_replace(
['#MAJORVER#', '#MINORVER#'],
[$majorVer, $minorVer],
$value,
);
} | Render the property of a single User Agent and replaces version placeholders | replace | php | browscap/browscap | src/Browscap/Data/Helper/VersionNumber.php | https://github.com/browscap/browscap/blob/master/src/Browscap/Data/Helper/VersionNumber.php | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.