
Shuu12121/CodeModernBERT-Owl-4.1
Fill-Mask
•
0.2B
•
Updated
•
100
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 |
---|---|---|---|---|---|---|---|
private function enableFilters(DocumentManager $documentManager): void
{
if (empty($this->enabledFilters)) {
return;
}
$filterCollection = $documentManager->getFilterCollection();
foreach ($this->enabledFilters as $filter) {
$filterCollection->enable($filter);
}
} | Enable filters for an given document manager | enableFilters | php | doctrine/DoctrineMongoDBBundle | src/ManagerConfigurator.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/ManagerConfigurator.php | MIT |
public function getAliasNamespace(string $alias): string
{
foreach (array_keys($this->getManagers()) as $name) {
$objectManager = $this->getManager($name);
if (! $objectManager instanceof DocumentManager) {
continue;
}
try {
return $objectManager->getConfiguration()->getDocumentNamespace($alias);
} catch (MongoDBException) {
}
}
throw MongoDBException::unknownDocumentNamespace($alias);
} | Resolves a registered namespace alias to the full namespace.
@throws MongoDBException | getAliasNamespace | php | doctrine/DoctrineMongoDBBundle | src/ManagerRegistry.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/ManagerRegistry.php | MIT |
public function isOptional(): bool
{
return false;
} | This cache warmer is not optional, without hydrators fatal error occurs!
@return false | isOptional | php | doctrine/DoctrineMongoDBBundle | src/CacheWarmer/HydratorCacheWarmer.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/CacheWarmer/HydratorCacheWarmer.php | MIT |
public function isOptional(): bool
{
return false;
} | This cache warmer is not optional, without persistent collections fatal error occurs!
@return false | isOptional | php | doctrine/DoctrineMongoDBBundle | src/CacheWarmer/PersistentCollectionCacheWarmer.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/CacheWarmer/PersistentCollectionCacheWarmer.php | MIT |
public function isOptional(): bool
{
return false;
} | This cache warmer is not optional, without proxies fatal error occurs!
@return false | isOptional | php | doctrine/DoctrineMongoDBBundle | src/CacheWarmer/ProxyCacheWarmer.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/CacheWarmer/ProxyCacheWarmer.php | MIT |
public function getCommands(): array
{
return $this->data['commands'];
} | @return array<array{database: string, command: stdClass, durationMicros: int}> | getCommands | php | doctrine/DoctrineMongoDBBundle | src/DataCollector/CommandDataCollector.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/DataCollector/CommandDataCollector.php | MIT |
protected function overrideParameters(array $options, ContainerBuilder $container): array
{
$overrides = [
'proxy_namespace',
'proxy_dir',
'auto_generate_proxy_classes',
'hydrator_namespace',
'hydrator_dir',
'auto_generate_hydrator_classes',
'default_commit_options',
'persistent_collection_dir',
'persistent_collection_namespace',
'auto_generate_persistent_collection_classes',
];
foreach ($overrides as $key) {
if (isset($options[$key])) {
$container->setParameter('doctrine_mongodb.odm.' . $key, $options[$key]);
// the option should not be used, the parameter should be referenced
unset($options[$key]);
}
}
return $options;
} | Uses some of the extension options to override DI extension parameters.
@param array $options The available configuration options
@param ContainerBuilder $container A ContainerBuilder instance
@return array<string, mixed> | overrideParameters | php | doctrine/DoctrineMongoDBBundle | src/DependencyInjection/DoctrineMongoDBExtension.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/DependencyInjection/DoctrineMongoDBExtension.php | MIT |
protected function loadDocumentManagers(array $dmConfigs, string|null $defaultDM, string $defaultDB, ContainerBuilder $container, bool $useLazyGhostObject = false): void
{
$dms = [];
foreach ($dmConfigs as $name => $documentManager) {
$documentManager['name'] = $name;
$this->loadDocumentManager(
$documentManager,
$defaultDM,
$defaultDB,
$container,
$useLazyGhostObject,
);
$dms[$name] = sprintf('doctrine_mongodb.odm.%s_document_manager', $name);
}
$container->setParameter('doctrine_mongodb.odm.document_managers', $dms);
} | Loads the document managers configuration.
@param array $dmConfigs An array of document manager configs
@param string|null $defaultDM The default document manager name
@param string $defaultDB The default db name
@param ContainerBuilder $container A ContainerBuilder instance | loadDocumentManagers | php | doctrine/DoctrineMongoDBBundle | src/DependencyInjection/DoctrineMongoDBExtension.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/DependencyInjection/DoctrineMongoDBExtension.php | MIT |
protected function loadDocumentManager(array $documentManager, string|null $defaultDM, string $defaultDB, ContainerBuilder $container, bool $useLazyGhostObject = false): void
{
$connectionName = $documentManager['connection'] ?? $documentManager['name'];
$configurationId = sprintf('doctrine_mongodb.odm.%s_configuration', $documentManager['name']);
$defaultDatabase = $documentManager['database'] ?? $defaultDB;
$odmConfigDef = new Definition(ODMConfiguration::class);
$odmConfigDef->addTag(self::CONFIGURATION_TAG);
$container->setDefinition(
$configurationId,
$odmConfigDef,
);
$this->loadDocumentManagerBundlesMappingInformation($documentManager, $odmConfigDef, $container);
$this->loadObjectManagerCacheDriver($documentManager, $container, 'metadata_cache');
$methods = [
'setMetadataCache' => new Reference(sprintf('doctrine_mongodb.odm.%s_metadata_cache', $documentManager['name'])),
'setMetadataDriverImpl' => new Reference(sprintf('doctrine_mongodb.odm.%s_metadata_driver', $documentManager['name'])),
'setProxyDir' => '%doctrine_mongodb.odm.proxy_dir%',
'setProxyNamespace' => '%doctrine_mongodb.odm.proxy_namespace%',
'setAutoGenerateProxyClasses' => '%doctrine_mongodb.odm.auto_generate_proxy_classes%',
'setHydratorDir' => '%doctrine_mongodb.odm.hydrator_dir%',
'setHydratorNamespace' => '%doctrine_mongodb.odm.hydrator_namespace%',
'setAutoGenerateHydratorClasses' => '%doctrine_mongodb.odm.auto_generate_hydrator_classes%',
'setDefaultDB' => $defaultDatabase,
'setDefaultCommitOptions' => '%doctrine_mongodb.odm.default_commit_options%',
'setDefaultDocumentRepositoryClassName' => $documentManager['default_document_repository_class'],
'setDefaultGridFSRepositoryClassName' => $documentManager['default_gridfs_repository_class'],
'setPersistentCollectionDir' => '%doctrine_mongodb.odm.persistent_collection_dir%',
'setPersistentCollectionNamespace' => '%doctrine_mongodb.odm.persistent_collection_namespace%',
'setAutoGeneratePersistentCollectionClasses' => '%doctrine_mongodb.odm.auto_generate_persistent_collection_classes%',
];
if ($useLazyGhostObject) {
$methods['setUseLazyGhostObject'] = $useLazyGhostObject;
}
if (method_exists(ODMConfiguration::class, 'setUseTransactionalFlush')) {
$methods['setUseTransactionalFlush'] = $documentManager['use_transactional_flush'];
}
if ($documentManager['repository_factory']) {
$methods['setRepositoryFactory'] = new Reference($documentManager['repository_factory']);
}
if ($documentManager['persistent_collection_factory']) {
$methods['setPersistentCollectionFactory'] = new Reference($documentManager['persistent_collection_factory']);
}
// logging
if ($container->getParameterBag()->resolveValue($documentManager['logging'])) {
$container->getDefinition('doctrine_mongodb.odm.psr_command_logger')
->addTag('doctrine_mongodb.odm.command_logger');
}
// profiler
if ($container->getParameterBag()->resolveValue($documentManager['profiler']['enabled'])) {
$container->getDefinition('doctrine_mongodb.odm.data_collector.command_logger')
->addTag('doctrine_mongodb.odm.command_logger');
$container->getDefinition('doctrine_mongodb.odm.stopwatch_command_logger')
->addTag('doctrine_mongodb.odm.command_logger');
$container
->getDefinition('doctrine_mongodb.odm.data_collector')
->addTag('data_collector', ['id' => 'mongodb', 'template' => '@DoctrineMongoDB/Collector/mongodb.html.twig']);
}
$enabledFilters = [];
foreach ($documentManager['filters'] as $name => $filter) {
$parameters = $filter['parameters'] ?? [];
$odmConfigDef->addMethodCall('addFilter', [$name, $filter['class'], $parameters]);
if ($filter['enabled']) {
$enabledFilters[] = $name;
}
}
$managerConfiguratorName = sprintf('doctrine_mongodb.odm.%s_manager_configurator', $documentManager['name']);
$container
->setDefinition(
$managerConfiguratorName,
new ChildDefinition('doctrine_mongodb.odm.manager_configurator.abstract'),
)
->replaceArgument(0, $enabledFilters);
foreach ($methods as $method => $arg) {
if ($odmConfigDef->hasMethodCall($method)) {
$odmConfigDef->removeMethodCall($method);
}
$odmConfigDef->addMethodCall($method, [$arg]);
}
$odmDmArgs = [
new Reference(sprintf('doctrine_mongodb.odm.%s_connection', $connectionName)),
new Reference($configurationId),
// Document managers will share their connection's event manager
new Reference(sprintf('doctrine_mongodb.odm.%s_connection.event_manager', $connectionName)),
];
$odmDmDef = new Definition(DocumentManager::class, $odmDmArgs);
$odmDmDef->setFactory([DocumentManager::class, 'create']);
$odmDmDef->addTag('doctrine_mongodb.odm.document_manager');
$odmDmDef->setPublic(true);
$container
->setDefinition(sprintf('doctrine_mongodb.odm.%s_document_manager', $documentManager['name']), $odmDmDef)
->setConfigurator([new Reference($managerConfiguratorName), 'configure']);
if ($documentManager['name'] !== $defaultDM) {
return;
}
$container->setAlias(
'doctrine_mongodb.odm.document_manager',
new Alias(sprintf('doctrine_mongodb.odm.%s_document_manager', $documentManager['name'])),
);
$container->getAlias('doctrine_mongodb.odm.document_manager')->setPublic(true);
$container->setAlias(
'doctrine_mongodb.odm.event_manager',
new Alias(sprintf('doctrine_mongodb.odm.%s_connection.event_manager', $connectionName)),
);
} | Loads a document manager configuration.
@param array $documentManager A document manager configuration array
@param string|null $defaultDM The default document manager name
@param string $defaultDB The default db name
@param ContainerBuilder $container A ContainerBuilder instance | loadDocumentManager | php | doctrine/DoctrineMongoDBBundle | src/DependencyInjection/DoctrineMongoDBExtension.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/DependencyInjection/DoctrineMongoDBExtension.php | MIT |
protected function loadConnections(array $connections, ContainerBuilder $container): void
{
$cons = [];
foreach ($connections as $name => $connection) {
// Define an event manager for this connection
$eventManagerId = sprintf('doctrine_mongodb.odm.%s_connection.event_manager', $name);
$container->setDefinition(
$eventManagerId,
new ChildDefinition('doctrine_mongodb.odm.connection.event_manager'),
);
$configurationId = sprintf('doctrine_mongodb.odm.%s_configuration', $name);
$container->setDefinition(
$configurationId,
new Definition(ODMConfiguration::class),
);
$odmConnArgs = [
$connection['server'] ?? null,
/* phpcs:ignore Squiz.Arrays.ArrayDeclaration.ValueNoNewline */
$connection['options'] ?? [],
$this->normalizeDriverOptions($connection),
];
$odmConnDef = new Definition(Client::class, $odmConnArgs);
$odmConnDef->setPublic(true);
$id = sprintf('doctrine_mongodb.odm.%s_connection', $name);
$container->setDefinition($id, $odmConnDef);
$cons[$name] = $id;
}
$container->setParameter('doctrine_mongodb.odm.connections', $cons);
} | Loads the configured connections.
@param array $config An array of connections configurations
@param ContainerBuilder $container A ContainerBuilder instance | loadConnections | php | doctrine/DoctrineMongoDBBundle | src/DependencyInjection/DoctrineMongoDBExtension.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/DependencyInjection/DoctrineMongoDBExtension.php | MIT |
private function normalizeDriverOptions(array $connection): array
{
$driverOptions = $connection['driver_options'] ?? [];
$driverOptions['typeMap'] = DocumentManager::CLIENT_TYPEMAP;
if (isset($driverOptions['context'])) {
$driverOptions['context'] = new Reference($driverOptions['context']);
}
$driverOptions['driver'] = [
'name' => 'symfony-mongodb',
'version' => self::getODMVersion(),
];
return $driverOptions;
} | Normalizes the driver options array
@param array<string, mixed> $connection
@return array<string, mixed> | normalizeDriverOptions | php | doctrine/DoctrineMongoDBBundle | src/DependencyInjection/DoctrineMongoDBExtension.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/DependencyInjection/DoctrineMongoDBExtension.php | MIT |
protected function loadDocumentManagerBundlesMappingInformation(array $documentManager, Definition $odmConfigDef, ContainerBuilder $container): void
{
// reset state of drivers and alias map. They are only used by this methods and children.
$this->drivers = [];
$this->aliasMap = [];
$this->loadMappingInformation($documentManager, $container);
$this->registerMappingDrivers($documentManager, $container);
if ($odmConfigDef->hasMethodCall('setDocumentNamespaces')) {
// TODO: Can we make a method out of it on Definition? replaceMethodArguments() or something.
$calls = $odmConfigDef->getMethodCalls();
foreach ($calls as $call) {
if ($call[0] === 'setDocumentNamespaces') {
$this->aliasMap = array_merge($call[1][0], $this->aliasMap);
}
}
$method = $odmConfigDef->removeMethodCall('setDocumentNamespaces');
}
$odmConfigDef->addMethodCall('setDocumentNamespaces', [$this->aliasMap]);
} | Loads an ODM document managers bundle mapping information.
There are two distinct configuration possibilities for mapping information:
1. Specify a bundle and optionally details where the entity and mapping information reside.
2. Specify an arbitrary mapping location.
@param array $documentManager A configured ODM entity manager.
@param Definition $odmConfigDef A Definition instance
@param ContainerBuilder $container A ContainerBuilder instance
@example
doctrine_mongodb:
mappings:
App1: ~
App2: xml
App3: { type: attribute }
App4: { type: xml, dir: config/doctrine/mapping }
App5:
type: xml
dir: [app-mappings1/, app-mappings2/]
alias: AppAlias
arbitrary_key:
type: xml
dir: %kernel.dir%/../src/vendor/DoctrineExtensions/lib/DoctrineExtensions/Documents
prefix: DoctrineExtensions\Documents\
alias: DExt
In the case of bundles everything is really optional (which leads to autodetection for this bundle) but
in the mappings key everything except alias is a required argument. | loadDocumentManagerBundlesMappingInformation | php | doctrine/DoctrineMongoDBBundle | src/DependencyInjection/DoctrineMongoDBExtension.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/DependencyInjection/DoctrineMongoDBExtension.php | MIT |
public function getNamespace(): string
{
return 'http://symfony.com/schema/dic/doctrine/odm/mongodb';
} | Returns the namespace to be used for this extension (XML namespace).
@return string The XML namespace | getNamespace | php | doctrine/DoctrineMongoDBBundle | src/DependencyInjection/DoctrineMongoDBExtension.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/DependencyInjection/DoctrineMongoDBExtension.php | MIT |
public function __construct(Definition|Reference $driver, array $namespaces, array $managerParameters, string|false $enabledParameter = false, array $aliasMap = [])
{
$managerParameters[] = 'doctrine_mongodb.odm.default_document_manager';
parent::__construct(
$driver,
$namespaces,
$managerParameters,
'doctrine_mongodb.odm.%s_metadata_driver',
$enabledParameter,
'doctrine_mongodb.odm.%s_configuration',
'addDocumentNamespace',
$aliasMap,
);
} | You should not directly instantiate this class but use one of the
factory methods.
@param Definition|Reference $driver the driver to use
@param array $namespaces list of namespaces this driver should handle
@param string[] $managerParameters list of parameters that could tell the manager name to use
@param string|false $enabledParameter if specified, the compiler pass only
executes if this parameter exists in the service container.
@param string[] $aliasMap Map of alias to namespace. | __construct | php | doctrine/DoctrineMongoDBBundle | src/DependencyInjection/Compiler/DoctrineMongoDBMappingsPass.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/DependencyInjection/Compiler/DoctrineMongoDBMappingsPass.php | MIT |
public static function createXmlMappingDriver(array $mappings, array $managerParameters, string|false $enabledParameter = false, array $aliasMap = []): DoctrineMongoDBMappingsPass
{
$arguments = [$mappings, '.mongodb.xml'];
$locator = new Definition(SymfonyFileLocator::class, $arguments);
$driver = new Definition(XmlDriver::class, [$locator]);
return new DoctrineMongoDBMappingsPass($driver, $mappings, $managerParameters, $enabledParameter, $aliasMap);
} | @param array $mappings Hashmap of directory path to namespace
@param string[] $managerParameters List of parameters that could which object manager name
your bundle uses. This compiler pass will automatically
append the parameter name for the default entity manager
to this list.
@param string|false $enabledParameter Service container parameter that must be present to
enable the mapping. Set to false to not do any check,
optional.
@param string[] $aliasMap Map of alias to namespace. | createXmlMappingDriver | php | doctrine/DoctrineMongoDBBundle | src/DependencyInjection/Compiler/DoctrineMongoDBMappingsPass.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/DependencyInjection/Compiler/DoctrineMongoDBMappingsPass.php | MIT |
public static function createPhpMappingDriver(array $mappings, array $managerParameters = [], string|false $enabledParameter = false, array $aliasMap = []): DoctrineMongoDBMappingsPass
{
$arguments = [$mappings, '.php'];
$locator = new Definition(SymfonyFileLocator::class, $arguments);
$driver = new Definition(PHPDriver::class, [$locator]);
return new DoctrineMongoDBMappingsPass($driver, $mappings, $managerParameters, $enabledParameter, $aliasMap);
} | @param array $mappings Hashmap of directory path to namespace
@param string[] $managerParameters List of parameters that could which object manager name
your bundle uses. This compiler pass will automatically
append the parameter name for the default entity manager
to this list.
@param string|false $enabledParameter Service container parameter that must be present to
enable the mapping. Set to false to not do any check,
optional.
@param string[] $aliasMap Map of alias to namespace. | createPhpMappingDriver | php | doctrine/DoctrineMongoDBBundle | src/DependencyInjection/Compiler/DoctrineMongoDBMappingsPass.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/DependencyInjection/Compiler/DoctrineMongoDBMappingsPass.php | MIT |
public static function createAttributeMappingDriver(array $namespaces, array $directories, array $managerParameters, string|false $enabledParameter = false, array $aliasMap = []): DoctrineMongoDBMappingsPass
{
$driver = new Definition(AttributeDriver::class, [$directories]);
return new DoctrineMongoDBMappingsPass($driver, $namespaces, $managerParameters, $enabledParameter, $aliasMap);
} | @param array $namespaces List of namespaces that are handled with attribute mapping
@param array $directories List of directories to look for attribute mapping files
@param string[] $managerParameters List of parameters that could which object manager name
your bundle uses. This compiler pass will automatically
append the parameter name for the default entity manager
to this list.
@param string|false $enabledParameter Service container parameter that must be present to
enable the mapping. Set to false to not do any check,
optional.
@param string[] $aliasMap Map of alias to namespace. | createAttributeMappingDriver | php | doctrine/DoctrineMongoDBBundle | src/DependencyInjection/Compiler/DoctrineMongoDBMappingsPass.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/DependencyInjection/Compiler/DoctrineMongoDBMappingsPass.php | MIT |
public static function createStaticPhpMappingDriver(array $namespaces, array $directories, array $managerParameters = [], string|false $enabledParameter = false, array $aliasMap = []): DoctrineMongoDBMappingsPass
{
$driver = new Definition(StaticPHPDriver::class, [$directories]);
return new DoctrineMongoDBMappingsPass($driver, $namespaces, $managerParameters, $enabledParameter, $aliasMap);
} | @param array $namespaces List of namespaces that are handled with static php mapping
@param array $directories List of directories to look for static php mapping files
@param string[] $managerParameters List of parameters that could which object manager name
your bundle uses. This compiler pass will automatically
append the parameter name for the default entity manager
to this list.
@param string|false $enabledParameter Service container parameter that must be present to
enable the mapping. Set to false to not do any check,
optional.
@param string[] $aliasMap Map of alias to namespace. | createStaticPhpMappingDriver | php | doctrine/DoctrineMongoDBBundle | src/DependencyInjection/Compiler/DoctrineMongoDBMappingsPass.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/DependencyInjection/Compiler/DoctrineMongoDBMappingsPass.php | MIT |
public function __construct(Builder|Closure $queryBuilder, ?ObjectManager $manager = null, ?string $class = null)
{
if ($queryBuilder instanceof Closure) {
$queryBuilder = $queryBuilder($manager->getRepository($class));
if (! $queryBuilder instanceof Builder) {
throw new UnexpectedTypeException($queryBuilder, Builder::class);
}
}
$this->queryBuilder = $queryBuilder;
} | Construct an ORM Query Builder Loader | __construct | php | doctrine/DoctrineMongoDBBundle | src/Form/ChoiceList/MongoDBQueryBuilderLoader.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/Form/ChoiceList/MongoDBQueryBuilderLoader.php | MIT |
protected function createFixture($class): FixtureInterface
{
/*
* We don't actually need to create the fixture. We just
* return the one that already exists.
*/
if (! isset($this->loadedFixtures[$class])) {
throw new LogicException(sprintf(
'The "%s" fixture class is trying to be loaded, but is not available. Make sure this class is defined as a service and tagged with "%s".',
$class,
FixturesCompilerPass::FIXTURE_TAG,
));
}
return $this->loadedFixtures[$class];
} | Overridden to not allow new fixture classes to be instantiated.
@phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingAnyTypeHint | createFixture | php | doctrine/DoctrineMongoDBBundle | src/Loader/SymfonyFixturesLoader.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/Loader/SymfonyFixturesLoader.php | MIT |
public function getFixtures(array $groups = []): array
{
$fixtures = parent::getFixtures();
if (empty($groups)) {
return $fixtures;
}
$filteredFixtures = [];
foreach ($fixtures as $fixture) {
foreach ($groups as $group) {
$fixtureClass = $fixture::class;
if (isset($this->groupsFixtureMapping[$group][$fixtureClass])) {
$filteredFixtures[$fixtureClass] = $fixture;
continue 2;
}
}
}
foreach ($filteredFixtures as $fixture) {
$this->validateDependencies($filteredFixtures, $fixture);
}
return array_values($filteredFixtures);
} | Returns the array of data fixtures to execute.
@param string[] $groups
@return FixtureInterface[] | getFixtures | php | doctrine/DoctrineMongoDBBundle | src/Loader/SymfonyFixturesLoader.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/Loader/SymfonyFixturesLoader.php | MIT |
private function addGroupsFixtureMapping(string $className, array $groups): void
{
foreach ($groups as $group) {
$this->groupsFixtureMapping[$group][$className] = true;
}
} | Generates an array of the groups and their fixtures
@param string[] $groups | addGroupsFixtureMapping | php | doctrine/DoctrineMongoDBBundle | src/Loader/SymfonyFixturesLoader.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/Loader/SymfonyFixturesLoader.php | MIT |
private function validateDependencies(array $fixtures, FixtureInterface $fixture): void
{
if (! $fixture instanceof DependentFixtureInterface) {
return;
}
$dependenciesClasses = $fixture->getDependencies();
foreach ($dependenciesClasses as $class) {
if (! array_key_exists($class, $fixtures)) {
throw new RuntimeException(sprintf('Fixture "%s" was declared as a dependency for fixture "%s", but it was not included in any of the loaded fixture groups.', $class, $fixture::class));
}
}
} | @param array<class-string<FixtureInterface>, FixtureInterface> $fixtures An array of fixtures with class names as keys | validateDependencies | php | doctrine/DoctrineMongoDBBundle | src/Loader/SymfonyFixturesLoader.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/Loader/SymfonyFixturesLoader.php | MIT |
public function getRepository(DocumentManager $documentManager, string $documentName): ObjectRepository
{
$metadata = $documentManager->getClassMetadata($documentName);
$customRepositoryName = $metadata->customRepositoryClassName;
if ($customRepositoryName !== null) {
// fetch from the container
if ($this->container->has($customRepositoryName)) {
/** @var ObjectRepository<T> $repository */
$repository = $this->container->get($customRepositoryName);
if (! $repository instanceof DocumentRepository) {
throw new RuntimeException(sprintf('The service "%s" must extend DocumentRepository (or a base class, like ServiceDocumentRepository).', $customRepositoryName));
}
return $repository;
}
// if not in the container but the class/id implements the interface, throw an error
if (is_a($customRepositoryName, ServiceDocumentRepositoryInterface::class, true)) {
throw new RuntimeException(sprintf('The "%s" document repository implements "%s", but its service could not be found. Make sure the service exists and is tagged with "%s".', $customRepositoryName, ServiceDocumentRepositoryInterface::class, ServiceRepositoryCompilerPass::REPOSITORY_SERVICE_TAG));
}
if (! class_exists($customRepositoryName)) {
throw new RuntimeException(sprintf('The "%s" document has a repositoryClass set to "%s", but this is not a valid class. Check your class naming. If this is meant to be a service id, make sure this service exists and is tagged with "%s".', $metadata->name, $customRepositoryName, ServiceRepositoryCompilerPass::REPOSITORY_SERVICE_TAG));
}
// allow the repository to be created below
}
return $this->getOrCreateRepository($documentManager, $metadata);
} | @phpstan-param class-string<T> $documentName
@phpstan-return ObjectRepository<T>
@template T of object | getRepository | php | doctrine/DoctrineMongoDBBundle | src/Repository/ContainerRepositoryFactory.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/Repository/ContainerRepositoryFactory.php | MIT |
private function getOrCreateRepository(DocumentManager $documentManager, ClassMetadata $metadata): ObjectRepository
{
$repositoryHash = $metadata->getName() . spl_object_hash($documentManager);
if (isset($this->managedRepositories[$repositoryHash])) {
/** @phpstan-var ObjectRepository<T> */
return $this->managedRepositories[$repositoryHash];
}
if ($metadata->customRepositoryClassName) {
$repositoryClassName = $metadata->customRepositoryClassName;
} elseif ($metadata->isFile) {
/** @phpstan-var class-string<GridFSRepository<T>> $repositoryClassName */
$repositoryClassName = $documentManager->getConfiguration()->getDefaultGridFSRepositoryClassName();
} else {
/** @phpstan-var class-string<ObjectRepository<T>> $repositoryClassName */
$repositoryClassName = $documentManager->getConfiguration()->getDefaultDocumentRepositoryClassName();
}
return $this->managedRepositories[$repositoryHash] = new $repositoryClassName($documentManager, $documentManager->getUnitOfWork(), $metadata);
} | @phpstan-param ClassMetadata<T> $metadata
@phpstan-return ObjectRepository<T>
@template T of object | getOrCreateRepository | php | doctrine/DoctrineMongoDBBundle | src/Repository/ContainerRepositoryFactory.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/Repository/ContainerRepositoryFactory.php | MIT |
public function __construct(
array|string $fields,
?string $message = null,
string $service = 'doctrine_odm.mongodb.unique',
?string $em = null,
?string $entityClass = null,
?string $repositoryMethod = null,
?string $errorPath = null,
bool|array|string|null $ignoreNull = null,
?array $groups = null,
mixed $payload = null,
array $options = [],
) {
parent::__construct(
$fields,
$message,
$service,
$em,
$entityClass,
$repositoryMethod,
$errorPath,
$ignoreNull,
$groups,
$payload,
$options,
);
} | @param string[]|string $fields The combination of fields that must contain unique values or a set of options
@param bool|string[]|string $ignoreNull The combination of fields that ignore null values | __construct | php | doctrine/DoctrineMongoDBBundle | src/Validator/Constraints/Unique.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/src/Validator/Constraints/Unique.php | MIT |
public static function provideLoggerConfigs(): array
{
$config = ['connections' => ['default' => []]];
return [
'Debug mode enabled' => [
// Logging is always enabled in debug mode
'expected' => true,
'config' => [
'document_managers' => ['default' => []],
] + $config,
'debug' => true,
],
'Debug mode disabled' => [
// Logging is disabled by default when not in debug mode
'expected' => false,
'config' => [
'document_managers' => ['default' => []],
] + $config,
'debug' => false,
],
'Logging enabled by config' => [
// Logging can be enabled by config
'expected' => true,
'config' => [
'document_managers' => ['default' => ['logging' => true]],
] + $config,
'debug' => false,
],
];
} | @return array<string, array{expected: bool, config: array, debug: bool}> | provideLoggerConfigs | php | doctrine/DoctrineMongoDBBundle | tests/ContainerTest.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/tests/ContainerTest.php | MIT |
public static function provideDataCollectorConfigs(): array
{
$config = ['connections' => ['default' => []]];
return [
'Debug mode enabled' => [
// Profiling is always enabled in debug mode
'expected' => true,
'config' => [
'document_managers' => ['default' => []],
] + $config,
'debug' => true,
],
'Debug mode disabled' => [
// Profiling is disabled by default when not in debug mode
'expected' => false,
'config' => [
'document_managers' => ['default' => []],
] + $config,
'debug' => false,
],
'Profiling enabled by config' => [
// Profiling can be enabled by config
'expected' => true,
'config' => [
'document_managers' => ['default' => ['profiler' => true]],
] + $config,
'debug' => false,
],
];
} | @return array<string, array{expected: bool, config: array, debug: bool}> | provideDataCollectorConfigs | php | doctrine/DoctrineMongoDBBundle | tests/ContainerTest.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/tests/ContainerTest.php | MIT |
private function assertDefinitionMethodCallAny(Definition $definition, string $methodName, array $params): void
{
$calls = $definition->getMethodCalls();
$called = false;
$lastError = null;
foreach ($calls as $call) {
if ($call[0] !== $methodName) {
continue;
}
$called = true;
try {
$this->assertSame($params, $call[1], "Expected parameters to method '" . $methodName . "' did not match the actual parameters.");
return;
} catch (AssertionFailedError $e) {
$lastError = $e;
}
}
if (! $called) {
$this->fail("Method '" . $methodName . "' is expected to be called, but it was never called.");
}
if ($lastError) {
throw $lastError;
}
} | Asserts that the given definition contains a call to the method that uses
the specified parameters.
@param mixed[] $params | assertDefinitionMethodCallAny | php | doctrine/DoctrineMongoDBBundle | tests/DependencyInjection/AbstractMongoDBExtensionTestCase.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/tests/DependencyInjection/AbstractMongoDBExtensionTestCase.php | MIT |
private function assertDefinitionMethodCallOnce(Definition $definition, string $methodName, array $params): void
{
$calls = $definition->getMethodCalls();
$called = false;
foreach ($calls as $call) {
if ($call[0] !== $methodName) {
continue;
}
if ($called) {
$this->fail("Method '" . $methodName . "' is expected to be called only once, but it was called multiple times.");
}
$called = true;
$this->assertEquals($params, $call[1], "Expected parameters to method '" . $methodName . "' did not match the actual parameters.");
}
if ($called) {
return;
}
$this->fail("Method '" . $methodName . "' is expected to be called once, but it was never called.");
} | Asserts that the given definition contains exactly one call to the method
and that it uses the specified parameters.
@param mixed[] $params | assertDefinitionMethodCallOnce | php | doctrine/DoctrineMongoDBBundle | tests/DependencyInjection/AbstractMongoDBExtensionTestCase.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/tests/DependencyInjection/AbstractMongoDBExtensionTestCase.php | MIT |
public function testMergeOptions(array $configs, array $expected): void
{
$processor = new Processor();
$configuration = new Configuration();
$options = $processor->processConfiguration($configuration, $configs);
foreach ($expected as $key => $value) {
$this->assertEquals($value, $options[$key]);
}
} | @param array $configs An array of configuration arrays to process
@param array $expected Array of key/value options expected in the processed configuration
@dataProvider provideMergeOptions | testMergeOptions | php | doctrine/DoctrineMongoDBBundle | tests/DependencyInjection/ConfigurationTest.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/tests/DependencyInjection/ConfigurationTest.php | MIT |
public function testNormalizeOptions(array $config, array $expected): void
{
$processor = new Processor();
$configuration = new Configuration();
$options = $processor->processConfiguration($configuration, [$config]);
foreach ($expected as $key => $value) {
$this->assertEquals($value, $options[$key]);
}
} | @param array $configs A configuration array to process
@param array $expected Array of key/value options expected in the processed configuration
@dataProvider provideNormalizeOptions | testNormalizeOptions | php | doctrine/DoctrineMongoDBBundle | tests/DependencyInjection/ConfigurationTest.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/tests/DependencyInjection/ConfigurationTest.php | MIT |
public function testControllerResolver(): void
{
$container = $this->getContainer();
$extension = new DoctrineMongoDBExtension();
$extension->load(self::buildConfiguration(), $container);
$controllerResolver = $container->getDefinition('doctrine_mongodb.odm.entity_value_resolver');
$this->assertEquals([
new Reference('doctrine_mongodb'),
new Reference('doctrine_mongodb.odm.document_value_resolver.expression_language', $container::IGNORE_ON_INVALID_REFERENCE),
], $controllerResolver->getArguments());
$container = $this->getContainer();
$extension->load(self::buildConfiguration([
'controller_resolver' => [
'enabled' => false,
'auto_mapping' => false,
],
]), $container);
$container->setDefinition('controller_resolver_defaults', $container->getDefinition('doctrine_mongodb.odm.entity_value_resolver')->getArgument(2))->setPublic(true);
$container->compile();
$this->assertEquals(new MapDocument(null, null, null, [], null, null, null, true), $container->get('controller_resolver_defaults'));
} | @requires function \Symfony\Bridge\Doctrine\ArgumentResolver\EntityValueResolver::__construct | testControllerResolver | php | doctrine/DoctrineMongoDBBundle | tests/DependencyInjection/DoctrineMongoDBExtensionTest.php | https://github.com/doctrine/DoctrineMongoDBBundle/blob/master/tests/DependencyInjection/DoctrineMongoDBExtensionTest.php | MIT |
protected function getFilterValue(mixed $value): mixed
{
if (empty($value)) {
return $value;
}
if (is_array($value)) {
return collect($value)->map(function ($valueValue) {
return $this->getFilterValue($valueValue);
})->all();
}
if (Str::contains($value, static::getFilterArrayValueDelimiter())) {
return explode(static::getFilterArrayValueDelimiter(), $value);
}
if ($value === 'true') {
return true;
}
if ($value === 'false') {
return false;
}
return $value;
} | @return array|float|int|string|bool|null | getFilterValue | php | spatie/laravel-query-builder | src/QueryBuilderRequest.php | https://github.com/spatie/laravel-query-builder/blob/master/src/QueryBuilderRequest.php | MIT |
protected static function maybeSpecifyEscapeChar(string $driver): string
{
if (! in_array($driver, ['sqlite','sqlsrv'])) {
return '';
}
return " ESCAPE '\'";
} | @param 'sqlite'|'pgsql'|'sqlsrc'|'mysql'|'mariadb' $driver
@return string | maybeSpecifyEscapeChar | php | spatie/laravel-query-builder | src/Filters/FiltersPartial.php | https://github.com/spatie/laravel-query-builder/blob/master/src/Filters/FiltersPartial.php | MIT |
function go_home()
{
global $sitewide;
header("Location: " . $sitewide['root']);
die();
} | go_home
Sets header to redirect home
@return {Void} | go_home | php | elementary/website | api/download.php | https://github.com/elementary/website/blob/master/api/download.php | MIT |
function os_payment_encode(string $text)
{
return urlencode(str_replace([' ', '.'], '_', $text));
} | os_payment_encode
Encodes text to be used in cookie storage
@param {String} $text - String to encode for use in cookie
@return {String} - Text to use in cookie | os_payment_encode | php | elementary/website | _backend/os-payment.php | https://github.com/elementary/website/blob/master/_backend/os-payment.php | MIT |
function os_payment_setcookie(string $version, int $amount)
{
$string = os_payment_encode('os_payment_' . $version);
$expires = time() + 60 * 60 * 24 * 365; // One year in the future
return setcookie($string, $amount, $expires, '/', '', false, true);
} | os_payment_setcookie
Sets the payment cookie for a given release version
@param {String} $version - Version of release to set cookie for
@param {Number} $amount - Amount paid for release
@return {Boolean} - True if cookie was set | os_payment_setcookie | php | elementary/website | _backend/os-payment.php | https://github.com/elementary/website/blob/master/_backend/os-payment.php | MIT |
function os_payment_getcookie(string $version)
{
// DEPRECATED: this is the old version of cookie naming
if (!isset($version) || $version === '') {
$string = os_payment_encode('has_paid_' . $config['release_title'] . '_' . $config['release_version']);
if (isset($_COOKIE[$string])) {
return intval($_COOKIE[$string]);
}
}
// DEPRECATED: all deprecated variables can be removed next version release
$string = os_payment_encode('os_payment_' . $version);
$deprecated_string = os_payment_encode('has_paid_Loki_' . $version);
if (isset($_COOKIE[$string])) {
return intval($_COOKIE[$string]);
}
if (isset($_COOKIE[$deprecated_string])) {
return intval($_COOKIE[$deprecated_string]);
}
return 0;
} | os_payment_getcookie
Returns the amount paid for a release version
@param {String} $version - Version of release to get cookie for
@return {Number} - Amount paid for release, 0 for not paid | os_payment_getcookie | php | elementary/website | _backend/os-payment.php | https://github.com/elementary/website/blob/master/_backend/os-payment.php | MIT |
function captureTranslations($id, $domain, $string)
{
global $currentTranslations, $currentUrl;
if ($domain !== $currentUrl) {
return;
}
if (empty($id)) {
return;
}
if (is_numeric($id) || ctype_punct($id)) {
return;
}
if (isset($currentTranslations[$id])) {
return;
}
$currentTranslations[$id] = $string;
} | captureTranslations
L10n translation callback
@param string $id The source string
@param string $domain The translation domain
@param string $string The translation string
@return Void | captureTranslations | php | elementary/website | _backend/Console/Extract.php | https://github.com/elementary/website/blob/master/_backend/Console/Extract.php | MIT |
function translatePHP($path, $domain)
{
global $l10n, $root;
chdir($root);
$_SERVER['DOCUMENT_ROOT'] = dirname(__DIR__);
$_GET['page'] = $domain;
$page['name'] = $domain;
// Do not start output buffering twice
if (defined('HTML_I18N') === false) {
define('HTML_I18N', 1);
} elseif (HTML_I18N === 1) {
return;
}
$l10n->setDomain($domain);
ob_start(function ($input) use ($l10n) {
$l10n->translateHtml($input, '\App\Console\captureTranslations');
return '';
});
include $path;
if (ob_get_level()) {
ob_end_flush();
}
// Add page title to translations
if (isset($page['title']) !== false) {
captureTranslations($page['title'], $domain, $page['title']);
}
} | translatePHP
Translates a wall of PHP HTML code
@param string $path Path to PHP file
@param string $domain Page URL without extension
@return void All translations kept in $currentTranslations array | translatePHP | php | elementary/website | _backend/Console/Extract.php | https://github.com/elementary/website/blob/master/_backend/Console/Extract.php | MIT |
public static function languageFolders()
{
$languages = array();
foreach (glob(static::$directory . '/*/', GLOB_ONLYDIR) as $path) {
$languages[] = basename($path);
}
return $languages;
} | language_folders
Returns a list of all languages the website currently has.
NOTE: this does not return a list of enabled languages.
@return array A list of languages we currently have | languageFolders | php | elementary/website | _backend/Lib/L10n.php | https://github.com/elementary/website/blob/master/_backend/Lib/L10n.php | MIT |
public static function pages()
{
$rootDirectory = static::$directory . '/..';
$files = array_merge(
glob($rootDirectory . '/*.{php,md}', GLOB_BRACE),
glob($rootDirectory . '/docs/*.md'),
glob($rootDirectory . '/docs/code/*.md'),
glob($rootDirectory . '/store/*.php'),
glob($rootDirectory . '/_templates/*.php')
);
$pages = array();
foreach ($files as $file) {
$blacklisted = false;
foreach (static::$blacklistedPages as $reg) {
if (preg_match($reg, $file)) {
$blacklisted = true;
}
}
if ($blacklisted === false) {
$pages[] = $file;
}
}
return $pages;
} | pages
Returns a list of pages that we can translate.
@return array A list of pages we can translate | pages | php | elementary/website | _backend/Lib/L10n.php | https://github.com/elementary/website/blob/master/_backend/Lib/L10n.php | MIT |
public static function languageDirectory($lang)
{
return realpath(static::$directory . '/' . $lang);
} | languageDirectory
Returns the directory for a language
@param string $lang The language code
@return string Directory the language files are in | languageDirectory | php | elementary/website | _backend/Lib/L10n.php | https://github.com/elementary/website/blob/master/_backend/Lib/L10n.php | MIT |
public function translate($id, $domain = null, $string = null)
{
if (empty($domain)) {
$domain = $this->domain;
}
if (empty($string)) {
$string = $id;
}
if (!isset($this->translations[$domain])) {
$this->loadDomain($domain);
}
// Remove newlines and normalize spaces for matching
$processedId = str_replace(["\r\n", "\n"], " ", $id);
$processedId = preg_replace('/\s+/', ' ', $processedId);
if (isset($this->translations[$domain][$processedId]) &&
is_string($this->translations[$domain][$processedId]) &&
($this->translations[$domain][$processedId] !== "")) {
return $this->translations[$domain][$processedId];
} else {
return $string;
}
} | Translate a string. Returns the original string if no translation was found. | translate | php | elementary/website | _backend/Lib/L10n.php | https://github.com/elementary/website/blob/master/_backend/Lib/L10n.php | MIT |
public function translateHtml($input, $translate = null)
{
if (empty($translate)) {
$translate = array($this, 'translate');
}
$output = ''; // Output HTML string
// Tags that doesn't contain translatable text
$tagsBlacklist = array('script', 'style', 'kbd', 'code');
// Attributes that can be translated
$attrsWhitelist = array(
'input' => array('placeholder', 'value', 'title'),
'a' => array('title'),
'img' => array('alt')
);
// Tags included in translation strings when used in <p>, <hX> or <li>
$ignoredTags = array('a', 'kbd', 'strong', 'em', 'code', 'sup', 'sub');
// Begin parsing input HTML
$i = 0;
$tagName = '';
$l10nId = '';
$l10nDisabled = false;
while ($i < strlen($input)) {
$char = $input[$i]; // Current char
if ($char == '<') { // Tag node (<HERE>)
$next = strpos($input, '>', $i);
$tag = substr($input, $i + 1, $next - $i - 1);
// Parse <tag>
$attrsStart = strpos($tag, ' ');
if ($attrsStart !== false) { // There are attributes specified
$tagName = substr($tag, 0, $attrsStart);
$attrs = substr($tag, $attrsStart + 1);
// Parse attributes only if it's interesting
// (translatable attributes or data-l10n-* attributes)
if (isset($attrsWhitelist[$tagName]) || strpos($attrs, 'data-l10n-') !== false) {
// Attributes that can be translated in this tag
if (isset($attrsWhitelist[$tagName])) {
$allowedAttrs = $attrsWhitelist[$tagName];
} else {
$allowedAttrs = array();
}
$tag = substr($tag, 0, $attrsStart + 1);
// Parse attributes
$j = 0;
while ($j < strlen($attrs)) {
$char = $attrs[$j];
if ($j == 0 || $char == ' ') {
if ($char == ' ') {
$j++;
}
// Extract attribute name and value
$nameEnd = strpos($attrs, '=', $j);
if ($nameEnd === false) {
// In case the last attribute is a boolean one (without value, e.g. <input disabled>)
$boolAttrName = substr($attrs, $j);
if (preg_match('#^[a-zA-Z0-9-]+$#', $boolAttrName)) {
$valueEnd = $j + strlen($boolAttrName);
$name = $boolAttrName;
$value = true;
} else {
break;
}
} else {
$valueEnd = strpos($attrs, '"', $nameEnd + 2);
if ($valueEnd === false) {
break;
}
$name = substr($attrs, $j, $nameEnd - $j);
$value = substr($attrs, $nameEnd + 2, $valueEnd - ($nameEnd + 2));
}
if ($name == 'data-l10n-id') { // Set translation ID for this tag
$l10nId = $value;
}
if ($name == 'data-l10n-off') { // Disable translation for this tag
$l10nDisabled = true;
}
if ($name == 'type' && $value == 'hidden') {
$l10nDisabled = true;
}
if (in_array($name, $allowedAttrs) && !$l10nDisabled) { // Translate attribute
$tag .= ' '.$name.'="'.$translate($value, $this->domain, $value).'"';
} else {
$tag .= ' '.substr($attrs, $j, $valueEnd - $j + 1);
}
$j = $valueEnd + 1;
} else {
break;
}
}
if ($j < strlen($attrs)) { // Broke inside the loop, append the remaining chars
$tag .= substr($attrs, $j);
}
}
} elseif (rtrim($tag, '/ ') != 'br') {
// No attributes in this tag
// Set current tag, if not a line break
$tagName = $tag;
}
$output .= '<'.$tag.'>';
} else { // Text node (<tag>HERE</tag>)
$next = strpos($input, '<', $i);
if ($next === false) { // End Of File
$next = strlen($input);
} elseif ($tagName == 'p' || $tagName == 'li' || preg_match('#^h[1-6]$#', $tagName)) {
// Do not process ignored tags in <p>, <hX> and <li>
$originalNext = $next;
$ignoredCount = 0;
do {
$found = false;
foreach ($ignoredTags as $ignoredTag) {
if (substr($input, $next + 1, strlen($ignoredTag)) == $ignoredTag) {
$nextChar = $input[$next + strlen($ignoredTag) + 1];
if ($nextChar == '>' || $nextChar == ' ') {
$tagEnd = strpos($input, '</'.$ignoredTag.'>', $next);
$next = strpos($input, '<', $tagEnd + 1);
$ignoredCount++;
$found = true;
break;
}
}
}
} while ($found);
// Just one link in the <p> ? Don't ignore it.
if ($ignoredCount == 1 && substr($input, $originalNext, 3) == '<a ' && substr($input, $next - 4, 4) == '</a>') {
$next = $originalNext;
}
} elseif (in_array($tagName, $tagsBlacklist)) {
// Avoid some bugs when < and > are present in script/style tags
$closeTag = '</'.$tagName.'>';
while (substr($input, $next, strlen($closeTag)) != $closeTag) {
$next = strpos($input, '<', $next + 1);
}
}
// Extract text to translate
$text = substr($input, $i + 1, $next - $i - 1);
if ((!in_array($tagName, $tagsBlacklist) || !empty($l10nId)) && !$l10nDisabled) {
$cleanedText = trim($text);
if (!empty($cleanedText) || !empty($l10nId)) {
if (empty($l10nId)) { // data-l10n-id attribute not set, use text as ID
$l10nId = $cleanedText;
}
// Properly re-inject whitespaces
$text = substr($text, 0, strpos($text, $cleanedText[0])) .
$translate($l10nId, $this->domain, $cleanedText) .
substr($text, strrpos($text, substr($cleanedText, -1)) + 1);
}
}
$output .= $text; // Append text to output
// Reset per-tag vars
$l10nId = '';
$l10nDisabled = false;
}
$i = $next; // Jump to next interesting char
}
return $output;
} | Translate a HTML string. This includes a minimalist XML parser.
Can be provided a $translate callback to override default behaviour.
(Useful to extract strings from a file for instance.) | translateHtml | php | elementary/website | _backend/Lib/L10n.php | https://github.com/elementary/website/blob/master/_backend/Lib/L10n.php | MIT |
public function __construct(StoreInterface $store)
{
$this->store = $store;
} | Creates a new cache using the given storage interface.
@param StoreInterface | __construct | php | elementary/website | _backend/Lib/Cache/Cache.php | https://github.com/elementary/website/blob/master/_backend/Lib/Cache/Cache.php | MIT |
public function get($key, $default = null)
{
$value = $this->store->get($key);
if ($value != null) {
return $value;
}
return $default;
} | Gets a value from the cache.
@param string $key
@param mixed $default
@return mixed | get | php | elementary/website | _backend/Lib/Cache/Cache.php | https://github.com/elementary/website/blob/master/_backend/Lib/Cache/Cache.php | MIT |
public function remember($key, $minutes, Closure $closure)
{
$value = $this->get($key);
if ($value != null) {
return $value;
}
$newValue = $closure();
$this->put($key, $newValue, $minutes);
return $newValue;
} | Remembers a value in the cache. Runs closure to generate new cache.
@param string $key
@param int $minutes
@param closure $closure
@return mixed | remember | php | elementary/website | _backend/Lib/Cache/Cache.php | https://github.com/elementary/website/blob/master/_backend/Lib/Cache/Cache.php | MIT |
public function __call($method, $parameters)
{
return $this->store->$method(...$parameters);
} | Redirect any none-cache method to the storage.
NOTE: This is a PHP magic function. Try not to break it.
@param string $method
@param array $parameters
@return mixed | __call | php | elementary/website | _backend/Lib/Cache/Cache.php | https://github.com/elementary/website/blob/master/_backend/Lib/Cache/Cache.php | MIT |
protected function getTime($minutes = 0)
{
// Consider 0 minutes as an infinite time
if ($minutes === 0) {
return 9999999999;
}
return time() + ($minutes * 60);
} | Returns the current time plus minutes.
@param int $minutes
@return int | getTime | php | elementary/website | _backend/Lib/Cache/Store/BaseStore.php | https://github.com/elementary/website/blob/master/_backend/Lib/Cache/Store/BaseStore.php | MIT |
public function getMany(array $keys)
{
return array_map(function ($key) {
return $this->get($key);
}, $keys);
} | Returns many values from the file.
@param string[] $keys
@return mixed|null[] | getMany | php | elementary/website | _backend/Lib/Cache/Store/BaseStore.php | https://github.com/elementary/website/blob/master/_backend/Lib/Cache/Store/BaseStore.php | MIT |
public function putMany(array $items, $minutes = 0)
{
array_walk(function ($value, $key) {
$this->put($key, $value, $minutes);
}, $items);
} | Puts many values into the file.
@param array $items $key
@param int $minutes | putMany | php | elementary/website | _backend/Lib/Cache/Store/BaseStore.php | https://github.com/elementary/website/blob/master/_backend/Lib/Cache/Store/BaseStore.php | MIT |
protected function cacheDirectory()
{
$path = sys_get_temp_dir();
if (substr($path, strlen($path) - 1) !== '/') {
$path .= '/';
}
return $path.'elementary/website';
} | Returns the directory we use to store cache files.
@return string | cacheDirectory | php | elementary/website | _backend/Lib/Cache/Store/FileStore.php | https://github.com/elementary/website/blob/master/_backend/Lib/Cache/Store/FileStore.php | MIT |
protected function cachePath($key)
{
return $this->cacheDirectory().'/'.base64_encode($key);
} | Returns the full path to the cache file.
@param string $key
@return string | cachePath | php | elementary/website | _backend/Lib/Cache/Store/FileStore.php | https://github.com/elementary/website/blob/master/_backend/Lib/Cache/Store/FileStore.php | MIT |
protected function readCache($key)
{
$path = $this->cachePath($key);
if (file_exists($path) === false) {
return;
}
return unserialize(file_get_contents($path));
} | Reads the cache file.
@param string $key
@return mixed|null; | readCache | php | elementary/website | _backend/Lib/Cache/Store/FileStore.php | https://github.com/elementary/website/blob/master/_backend/Lib/Cache/Store/FileStore.php | MIT |
protected function writeCache($key, $contents)
{
$filePath = $this->cachePath($key);
if (file_exists($filePath) === false) {
$fileDirectory = $this->cacheDirectory();
if (file_exists($fileDirectory) === false) {
mkdir($fileDirectory, 0744, true);
}
}
file_put_contents($filePath, serialize($contents));
} | Writes the cache to file.
@param string $key
@param mixed $contents | writeCache | php | elementary/website | _backend/Lib/Cache/Store/FileStore.php | https://github.com/elementary/website/blob/master/_backend/Lib/Cache/Store/FileStore.php | MIT |
public function get($key)
{
$content = $this->readCache($key);
if ($content == null) {
return;
}
$time = $content['time'];
if ($time <= time()) {
$this->forget($key);
return;
}
return $content['data'];
} | Returns a key from the file.
@param string $key
@return mixed|null | get | php | elementary/website | _backend/Lib/Cache/Store/FileStore.php | https://github.com/elementary/website/blob/master/_backend/Lib/Cache/Store/FileStore.php | MIT |
public function put($key, $value, $minutes = 0)
{
$this->writeCache($key, array(
'data' => $value,
'time' => $this->getTime($minutes),
));
} | Puts a value into the file.
@param string $key
@param mixed $value
@param int $minutes | put | php | elementary/website | _backend/Lib/Cache/Store/FileStore.php | https://github.com/elementary/website/blob/master/_backend/Lib/Cache/Store/FileStore.php | MIT |
public function forever($key, $value)
{
$content = $this->readCache($key);
if ($content == null) {
return;
}
$content['time'] = $this->getTime(0);
$this->writeCache($key, $content);
} | Sets a cache value to be cached forever.
@param string $key
@param int $value | forever | php | elementary/website | _backend/Lib/Cache/Store/FileStore.php | https://github.com/elementary/website/blob/master/_backend/Lib/Cache/Store/FileStore.php | MIT |
public function forget($key)
{
$filePath = $this->cachePath($key);
if (file_exists($filePath) === true) {
unlink($filePath);
}
} | Removes a value from the cache.
@param string $key | forget | php | elementary/website | _backend/Lib/Cache/Store/FileStore.php | https://github.com/elementary/website/blob/master/_backend/Lib/Cache/Store/FileStore.php | MIT |
public function flush()
{
$fileDirectory = $this->cacheDirectory();
$files = array_diff(scandir($fileDirectory, array('..', '.')));
foreach ($files as $file) {
unlink($fileDirectory.'/'.$file);
}
rmdir($fileDirectory);
} | Removes all values from the cache. | flush | php | elementary/website | _backend/Lib/Cache/Store/FileStore.php | https://github.com/elementary/website/blob/master/_backend/Lib/Cache/Store/FileStore.php | MIT |
public function setCache($cache, $expires = 900)
{
$this->cache = $cache;
$this->expires = $expires;
} | Enable caching of results
@param object $cache An PSR-6 cache pool (an object that implements Psr\Cache\CacheItemPoolInterface)
@param int $expires Optional the number of seconds after which a cached item expires, default is 15 minutes | setCache | php | WhichBrowser/Parser-PHP | src/Cache.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Cache.php | MIT |
private function applyCachedData($data)
{
foreach ($data as $key => $value) {
$this->$key = $value;
}
$this->cached = true;
} | Apply cached data to the main Parser object
@internal
@param array $data An array with a key for every property it needs to apply | applyCachedData | php | WhichBrowser/Parser-PHP | src/Cache.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Cache.php | MIT |
private function retrieveCachedData()
{
return [
'browser' => $this->browser,
'engine' => $this->engine,
'os' => $this->os,
'device' => $this->device,
'camouflage' => $this->camouflage,
'features' => $this->features
];
} | Retrieve the data that can be cached from the main Parser object
@internal
@return array An array with a key for every property that will be cached | retrieveCachedData | php | WhichBrowser/Parser-PHP | src/Cache.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Cache.php | MIT |
private function analyseWithCache($headers, $options = [])
{
if (isset($options['cache'])) {
if (isset($options['cacheExpires'])) {
$this->setCache($options['cache'], $options['cacheExpires']);
} else {
$this->setCache($options['cache']);
}
}
if ($this->cache instanceof CacheItemPoolInterface) {
$item = $this->cache->getItem('whichbrowser_' . md5(serialize($headers)));
if ($item->isHit()) {
$this->applyCachedData($item->get());
} else {
$analyser = new Analyser($headers, $options);
$analyser->setdata($this);
$analyser->analyse();
$item->set($this->retrieveCachedData());
$item->expiresAfter($this->expires);
$this->cache->save($item);
}
return true;
}
} | Retrieve the result from the cache, or analyse and store in the cache
@internal
@param array|string $headers An array with all of the headers or a string with just the User-Agent header
@return boolean did we actually retrieve or analyse results | analyseWithCache | php | WhichBrowser/Parser-PHP | src/Cache.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Cache.php | MIT |
public function __construct($headers = null, $options = [])
{
parent::__construct();
if (!is_null($headers)) {
$this->analyse($headers, $options);
}
} | Create a new object that contains all the detected information
@param array|string $headers Optional, an array with all of the headers or a string with just the User-Agent header
@param array $options Optional, an array with configuration options | __construct | php | WhichBrowser/Parser-PHP | src/Parser.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Parser.php | MIT |
public function analyse($headers, $options = [])
{
$o = $options;
if (is_string($headers)) {
$h = [ 'User-Agent' => $headers ];
} else {
if (isset($headers['headers'])) {
$h = $headers['headers'];
unset($headers['headers']);
$o = array_merge($headers, $options);
} else {
$h = $headers;
}
}
if ($this->analyseWithCache($h, $o)) {
return;
}
$analyser = new Analyser($h, $o);
$analyser->setdata($this);
$analyser->analyse();
} | Analyse the provided headers or User-Agent string
@param array|string $headers An array with all of the headers or a string with just the User-Agent header | analyse | php | WhichBrowser/Parser-PHP | src/Parser.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Parser.php | MIT |
public function reset($properties = null)
{
parent::reset();
unset($this->channel);
unset($this->using);
unset($this->family);
$this->stock = true;
$this->hidden = false;
$this->mode = '';
$this->type = '';
if (is_array($properties)) {
$this->set($properties);
}
} | Set the properties to the default values
@param array|null $properties An optional array of properties to set after setting it to the default values
@internal | reset | php | WhichBrowser/Parser-PHP | src/Model/Browser.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Browser.php | MIT |
public function getName()
{
$name = !empty($this->alias) ? $this->alias : (!empty($this->name) ? $this->name : '');
return $name ? $name . (!empty($this->channel) ? ' ' . $this->channel : '') : '';
} | Get the name in a human readable format
@return string | getName | php | WhichBrowser/Parser-PHP | src/Model/Browser.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Browser.php | MIT |
public function isFamily($name)
{
if ($this->getName() == $name) {
return true;
}
if (isset($this->family)) {
if ($this->family->getName() == $name) {
return true;
}
}
return false;
} | Is the browser from the specified family
@param string $name The name of the family
@return boolean | isFamily | php | WhichBrowser/Parser-PHP | src/Model/Browser.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Browser.php | MIT |
public function isUsing($name)
{
if (isset($this->using)) {
if ($this->using->getName() == $name) {
return true;
}
}
return false;
} | Is the browser using the specified webview
@param string $name The name of the webview
@return boolean | isUsing | php | WhichBrowser/Parser-PHP | src/Model/Browser.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Browser.php | MIT |
public function toString()
{
if ($this->hidden) {
return '';
}
$result = trim($this->getName() . ' ' . (!empty($this->version) && !$this->version->hidden ? $this->getVersion() : ''));
if (empty($result) && isset($this->using)) {
return $this->using->toString();
}
return $result;
} | Get a combined name and version number in a human readable format
@return string | toString | php | WhichBrowser/Parser-PHP | src/Model/Browser.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Browser.php | MIT |
public function toArray()
{
$result = [];
if (!empty($this->name)) {
$result['name'] = $this->name;
}
if (!empty($this->alias)) {
$result['alias'] = $this->alias;
}
if (!empty($this->using)) {
$result['using'] = $this->using->toArray();
}
if (!empty($this->family)) {
$result['family'] = $this->family->toArray();
}
if (!empty($this->version)) {
$result['version'] = $this->version->toArray();
}
if (!empty($this->type)) {
$result['type'] = $this->type;
}
if (isset($result['version']) && empty($result['version'])) {
unset($result['version']);
}
return $result;
} | Get an array of all defined properties
@internal
@return array | toArray | php | WhichBrowser/Parser-PHP | src/Model/Browser.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Browser.php | MIT |
public function reset($properties = null)
{
unset($this->manufacturer);
unset($this->model);
unset($this->series);
unset($this->carrier);
unset($this->identifier);
$this->type = '';
$this->subtype = '';
$this->identified = Constants\Id::NONE;
$this->generic = true;
$this->hidden = false;
if (is_array($properties)) {
$this->set($properties);
}
} | Set the properties to the default values
@param array|null $properties An optional array of properties to set after setting it to the default values
@internal | reset | php | WhichBrowser/Parser-PHP | src/Model/Device.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Device.php | MIT |
public function identifyModel($pattern, $subject, $defaults = [])
{
if (preg_match($pattern, $subject, $match)) {
$this->manufacturer = !empty($defaults['manufacturer']) ? $defaults['manufacturer'] : null;
$this->model = Data\DeviceModels::cleanup($match[1]);
$this->identifier = preg_replace('/ (Mozilla|Opera|Obigo|AU.Browser|UP.Browser|Build|Java|PPC|AU-MIC.*)$/iu', '', $match[0]);
$this->identifier = preg_replace('/_(TD|GPRS|LTE|BLEU|CMCC|CUCC)$/iu', '', $match[0]);
if (isset($defaults['model'])) {
if (is_callable($defaults['model'])) {
$this->model = call_user_func($defaults['model'], $this->model);
} else {
$this->model = $defaults['model'];
}
}
$this->generic = false;
$this->identified |= Constants\Id::PATTERN;
if (!empty($defaults['carrier'])) {
$this->carrier = $defaults['carrier'];
}
if (!empty($defaults['type'])) {
$this->type = $defaults['type'];
}
}
} | Identify the manufacturer and model based on a pattern
@param string $pattern The regular expression that defines the group that matches the model
@param string $subject The string the regular expression is matched with
@param array|null $defaults An optional array of properties to set together
@return string | identifyModel | php | WhichBrowser/Parser-PHP | src/Model/Device.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Device.php | MIT |
public function setIdentification($properties)
{
$this->reset($properties);
if (!empty($this->model)) {
$this->generic = false;
}
$this->identified |= Constants\Id::MATCH_UA;
} | Declare an positive identification
@param array $properties An array, the key of an element determines the name of the property
@return string | setIdentification | php | WhichBrowser/Parser-PHP | src/Model/Device.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Device.php | MIT |
public function getCarrier()
{
return $this->identified && !empty($this->carrier) ? $this->carrier : '';
} | Get the name of the carrier in a human readable format
@return string | getCarrier | php | WhichBrowser/Parser-PHP | src/Model/Device.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Device.php | MIT |
public function getManufacturer()
{
return $this->identified && !empty($this->manufacturer) ? $this->manufacturer : '';
} | Get the name of the manufacturer in a human readable format
@return string | getManufacturer | php | WhichBrowser/Parser-PHP | src/Model/Device.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Device.php | MIT |
public function getModel()
{
if ($this->identified) {
return trim((!empty($this->model) ? $this->model . ' ' : '') . (!empty($this->series) ? $this->series : ''));
}
return !empty($this->model) ? $this->model : '';
} | Get the name of the model in a human readable format
@return string | getModel | php | WhichBrowser/Parser-PHP | src/Model/Device.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Device.php | MIT |
public function toString()
{
if ($this->hidden) {
return '';
}
if ($this->identified) {
$model = $this->getModel();
$manufacturer = $this->getManufacturer();
if ($manufacturer != '' && strpos($model, $manufacturer) === 0) {
$manufacturer = '';
}
return trim($manufacturer . ' ' . $model);
}
return !empty($this->model) ? 'unrecognized device (' . $this->model . ')' : '';
} | Get the combined name of the manufacturer and model in a human readable format
@return string | toString | php | WhichBrowser/Parser-PHP | src/Model/Device.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Device.php | MIT |
public function isDetected()
{
return !empty($this->type) || !empty($this->model) || !empty($this->manufacturer);
} | Check if device information is detected
@return boolean | isDetected | php | WhichBrowser/Parser-PHP | src/Model/Device.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Device.php | MIT |
public function toArray()
{
$result = [];
if (!empty($this->type)) {
$result['type'] = $this->type;
}
if (!empty($this->subtype)) {
$result['subtype'] = $this->subtype;
}
if (!empty($this->manufacturer)) {
$result['manufacturer'] = $this->manufacturer;
}
if (!empty($this->model)) {
$result['model'] = $this->model;
}
if (!empty($this->series)) {
$result['series'] = $this->series;
}
if (!empty($this->carrier)) {
$result['carrier'] = $this->carrier;
}
return $result;
} | Get an array of all defined properties
@internal
@return array | toArray | php | WhichBrowser/Parser-PHP | src/Model/Device.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Device.php | MIT |
public function toArray()
{
$result = [];
if (!empty($this->name)) {
$result['name'] = $this->name;
}
if (!empty($this->version)) {
$result['version'] = $this->version->toArray();
}
if (isset($result['version']) && empty($result['version'])) {
unset($result['version']);
}
return $result;
} | Get an array of all defined properties
@internal
@return array | toArray | php | WhichBrowser/Parser-PHP | src/Model/Engine.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Engine.php | MIT |
public function toArray()
{
$result = [];
if (!empty($this->name) && empty($this->version)) {
return $this->name;
}
if (!empty($this->name)) {
$result['name'] = $this->name;
}
if (!empty($this->version)) {
$result['version'] = $this->version->toArray();
}
return $result;
} | Get an array of all defined properties
@internal
@return array | toArray | php | WhichBrowser/Parser-PHP | src/Model/Family.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Family.php | MIT |
private function isX()
{
$arguments = func_get_args();
$x = $arguments[0];
if (count($arguments) < 2) {
return false;
}
if (empty($this->$x->name)) {
return false;
}
if ($this->$x->name != $arguments[1]) {
return false;
}
if (count($arguments) >= 4) {
if (empty($this->$x->version)) {
return false;
}
if (!$this->$x->version->is($arguments[2], $arguments[3])) {
return false;
}
}
return true;
} | Check the name of a property and optionally is a specific version
@internal
@param string The name of the property, such as 'browser', 'engine' or 'os'
@param string The name of the browser that is checked
@param string Optional, the operator, must be <, <=, =, >= or >
@param mixed Optional, the value, can be an integer, float or string with a version number
@return boolean | isX | php | WhichBrowser/Parser-PHP | src/Model/Main.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Main.php | MIT |
public function isBrowser()
{
$arguments = func_get_args();
array_unshift($arguments, 'browser');
return call_user_func_array([ $this, 'isX' ], $arguments);
} | Check the name of the browser and optionally is a specific version
@param string The name of the browser that is checked
@param string Optional, the operator, must be <, <=, =, >= or >
@param mixed Optional, the value, can be an integer, float or string with a version number
@return boolean | isBrowser | php | WhichBrowser/Parser-PHP | src/Model/Main.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Main.php | MIT |
public function isEngine()
{
$arguments = func_get_args();
array_unshift($arguments, 'engine');
return call_user_func_array([ $this, 'isX' ], $arguments);
} | Check the name of the rendering engine and optionally is a specific version
@param string The name of the rendering engine that is checked
@param string Optional, the operator, must be <, <=, =, >= or >
@param mixed Optional, the value, can be an integer, float or string with a version number
@return boolean | isEngine | php | WhichBrowser/Parser-PHP | src/Model/Main.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Main.php | MIT |
public function isOs()
{
$arguments = func_get_args();
array_unshift($arguments, 'os');
return call_user_func_array([ $this, 'isX' ], $arguments);
} | Check the name of the operating system and optionally is a specific version
@param string The name of the operating system that is checked
@param string Optional, the operator, must be <, <=, =, >= or >
@param mixed Optional, the value, can be an integer, float or string with a version number
@return boolean | isOs | php | WhichBrowser/Parser-PHP | src/Model/Main.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Main.php | MIT |
public function isDevice($model)
{
return (!empty($this->device->series) && $this->device->series == $model) || (!empty($this->device->model) && $this->device->model == $model);
} | Check if the detected browser is of the specified type
@param string $model The type, or a combination of type and subtime joined with a semicolon.
@return boolean | isDevice | php | WhichBrowser/Parser-PHP | src/Model/Main.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Main.php | MIT |
public function getType()
{
return $this->device->type . (!empty($this->device->subtype) ? ':' . $this->device->subtype : '');
} | Get the type and subtype, separated by a semicolon (if applicable)
@return string | getType | php | WhichBrowser/Parser-PHP | src/Model/Main.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Main.php | MIT |
public function isMobile()
{
return $this->isType('mobile', 'tablet', 'ereader', 'media', 'watch', 'camera', 'gaming:portable');
} | Check if the detected browser is a mobile device
@return boolean | isMobile | php | WhichBrowser/Parser-PHP | src/Model/Main.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Main.php | MIT |
public function isDetected()
{
return $this->browser->isDetected() || $this->os->isDetected() || $this->engine->isDetected() || $this->device->isDetected();
} | Check if a browser was detected
@return boolean | isDetected | php | WhichBrowser/Parser-PHP | src/Model/Main.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Main.php | MIT |
private function a($s)
{
return (preg_match("/^[aeiou]/i", $s) ? 'an ' : 'a ') . $s;
} | Return the input string prefixed with 'a' or 'an' depending on the first letter of the string
@internal
@param string $s The string that will be prefixed
@return string | a | php | WhichBrowser/Parser-PHP | src/Model/Main.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Main.php | MIT |
public function toString()
{
$prefix = $this->camouflage ? 'an unknown browser that imitates ' : '';
$browser = $this->browser->toString();
$os = $this->os->toString();
$engine = $this->engine->toString();
$device = $this->device->toString();
if (empty($device) && empty($os) && $this->device->type == 'television') {
$device = 'television';
}
if (empty($device) && $this->device->type == 'emulator') {
$device = 'emulator';
}
if (!empty($browser) && !empty($os) && !empty($device)) {
return $prefix . $browser . ' on ' . $this->a($device) . ' running ' . $os;
}
if (!empty($browser) && empty($os) && !empty($device)) {
return $prefix . $browser . ' on ' . $this->a($device);
}
if (!empty($browser) && !empty($os) && empty($device)) {
return $prefix . $browser . ' on ' . $os;
}
if (empty($browser) && !empty($os) && !empty($device)) {
return $prefix . $this->a($device) . ' running ' . $os;
}
if (!empty($browser) && empty($os) && empty($device)) {
return $prefix . $browser;
}
if (empty($browser) && empty($os) && !empty($device)) {
return $prefix . $this->a($device);
}
if ($this->device->type == 'desktop' && !empty($os) && !empty($engine) && empty($device)) {
return 'an unknown browser based on ' . $engine . ' running on ' . $os;
}
if ($this->browser->stock && !empty($os) && empty($device)) {
return $os;
}
if ($this->browser->stock && !empty($engine) && empty($device)) {
return 'an unknown browser based on ' . $engine;
}
if ($this->device->type == 'bot') {
return 'an unknown bot';
}
return 'an unknown browser';
} | Get a human readable string of the whole browser identification
@return string | toString | php | WhichBrowser/Parser-PHP | src/Model/Main.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Main.php | MIT |
public function toJavaScript()
{
return "this.browser = new Browser({ " . $this->browser->toJavaScript() . " });\n" .
"this.engine = new Engine({ " . $this->engine->toJavaScript() . " });\n" .
"this.os = new Os({ " . $this->os->toJavaScript() . " });\n" .
"this.device = new Device({ " . $this->device->toJavaScript() . " });\n" .
"this.camouflage = " . ($this->camouflage ? 'true' : 'false') . ";\n" .
"this.features = " . json_encode($this->features) . ";\n";
} | Get a string containing a JavaScript representation of the object
@return string | toJavaScript | php | WhichBrowser/Parser-PHP | src/Model/Main.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Main.php | MIT |
public function toArray()
{
$result = [
'browser' => $this->browser->toArray(),
'engine' => $this->engine->toArray(),
'os' => $this->os->toArray(),
'device' => $this->device->toArray()
];
if (empty($result['browser'])) {
unset($result['browser']);
}
if (empty($result['engine'])) {
unset($result['engine']);
}
if (empty($result['os'])) {
unset($result['os']);
}
if (empty($result['device'])) {
unset($result['device']);
}
if ($this->camouflage) {
$result['camouflage'] = true;
}
return $result;
} | Get an array of all defined properties
@return array | toArray | php | WhichBrowser/Parser-PHP | src/Model/Main.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Main.php | MIT |
public function reset($properties = null)
{
parent::reset();
unset($this->family);
unset($this->edition);
$this->hidden = false;
if (is_array($properties)) {
$this->set($properties);
}
} | Set the properties to the default values
@param array|null $properties An optional array of properties to set after setting it to the default values
@internal | reset | php | WhichBrowser/Parser-PHP | src/Model/Os.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Os.php | MIT |
public function getFamily()
{
if (isset($this->family)) {
return $this->family->getName();
}
return $this->getName();
} | Return the name of the operating system family
@return string | getFamily | php | WhichBrowser/Parser-PHP | src/Model/Os.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Os.php | MIT |
public function isFamily($name)
{
if ($this->getName() == $name) {
return true;
}
if (isset($this->family)) {
if ($this->family->getName() == $name) {
return true;
}
}
return false;
} | Is the operating from the specified family
@param string $name The name of the family
@return boolean | isFamily | php | WhichBrowser/Parser-PHP | src/Model/Os.php | https://github.com/WhichBrowser/Parser-PHP/blob/master/src/Model/Os.php | MIT |
This dataset contains PHP functions and methods paired with their PHPDoc comments, extracted from open-source PHP repositories on GitHub. It is formatted similarly to the CodeSearchNet challenge dataset.
Each entry includes:
code
: The source code of a php function or method.docstring
: The docstring or Javadoc associated with the function/method.func_name
: The name of the function/method.language
: The programming language (always "php").repo
: The GitHub repository from which the code was sourced (e.g., "owner/repo").path
: The file path within the repository where the function/method is located.url
: A direct URL to the function/method's source file on GitHub (approximated to master/main branch).license
: The SPDX identifier of the license governing the source repository (e.g., "MIT", "Apache-2.0").
Additional metrics if available (from Lizard tool):ccn
: Cyclomatic Complexity Number.params
: Number of parameters of the function/method.nloc
: Non-commenting lines of code.token_count
: Number of tokens in the function/method.The dataset is divided into the following splits:
train
: 905,197 examplesvalidation
: 99,769 examplestest
: 7,619 examplesThe data was collected by:
.php
) using tree-sitter to extract functions/methods and their docstrings/Javadoc.lizard
tool to calculate code metrics (CCN, NLOC, params).This dataset can be used for tasks such as:
The code examples within this dataset are sourced from repositories with permissive licenses (typically MIT, Apache-2.0, BSD).
Each sample includes its original license information in the license
field.
The dataset compilation itself is provided under a permissive license (e.g., MIT or CC-BY-SA-4.0),
but users should respect the original licenses of the underlying code.
from datasets import load_dataset
# Load the dataset
dataset = load_dataset("Shuu12121/php-treesitter-filtered-datasetsV2")
# Access a split (e.g., train)
train_data = dataset["train"]
# Print the first example
print(train_data[0])