_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q255100 | AdminControllerTrait.findBy | test | protected function findBy($entityClass, $searchQuery, array $searchableFields, $page = 1, $maxPerPage = 15, $sortField = null, $sortDirection = null, $dqlFilter = null)
{
if (empty($sortDirection) || !\in_array(\strtoupper($sortDirection), ['ASC', 'DESC'])) {
$sortDirection = 'DESC';
}
$queryBuilder = $this->executeDynamicMethod('create<EntityName>SearchQueryBuilder', [$entityClass, $searchQuery, $searchableFields, $sortField, $sortDirection, $dqlFilter]);
$this->dispatch(EasyAdminEvents::POST_SEARCH_QUERY_BUILDER, [
'query_builder' => $queryBuilder,
'search_query' => $searchQuery,
'searchable_fields' => $searchableFields,
]);
return $this->get('easyadmin.paginator')->createOrmPaginator($queryBuilder, $page, $maxPerPage);
} | php | {
"resource": ""
} |
q255101 | AdminControllerTrait.createSearchQueryBuilder | test | protected function createSearchQueryBuilder($entityClass, $searchQuery, array $searchableFields, $sortField = null, $sortDirection = null, $dqlFilter = null)
{
return $this->get('easyadmin.query_builder')->createSearchQueryBuilder($this->entity, $searchQuery, $sortField, $sortDirection, $dqlFilter);
} | php | {
"resource": ""
} |
q255102 | AdminControllerTrait.createEntityFormBuilder | test | protected function createEntityFormBuilder($entity, $view)
{
$formOptions = $this->executeDynamicMethod('get<EntityName>EntityFormOptions', [$entity, $view]);
return $this->get('form.factory')->createNamedBuilder(\mb_strtolower($this->entity['name']), EasyAdminFormType::class, $entity, $formOptions);
} | php | {
"resource": ""
} |
q255103 | AdminControllerTrait.getEntityFormOptions | test | protected function getEntityFormOptions($entity, $view)
{
$formOptions = $this->entity[$view]['form_options'];
$formOptions['entity'] = $this->entity['name'];
$formOptions['view'] = $view;
return $formOptions;
} | php | {
"resource": ""
} |
q255104 | AdminControllerTrait.createEntityForm | test | protected function createEntityForm($entity, array $entityProperties, $view)
{
if (\method_exists($this, $customMethodName = 'create'.$this->entity['name'].'EntityForm')) {
$form = $this->{$customMethodName}($entity, $entityProperties, $view);
if (!$form instanceof FormInterface) {
throw new \UnexpectedValueException(\sprintf(
'The "%s" method must return a FormInterface, "%s" given.',
$customMethodName, \is_object($form) ? \get_class($form) : \gettype($form)
));
}
return $form;
}
$formBuilder = $this->executeDynamicMethod('create<EntityName>EntityFormBuilder', [$entity, $view]);
if (!$formBuilder instanceof FormBuilderInterface) {
throw new \UnexpectedValueException(\sprintf(
'The "%s" method must return a FormBuilderInterface, "%s" given.',
'createEntityForm', \is_object($formBuilder) ? \get_class($formBuilder) : \gettype($formBuilder)
));
}
return $formBuilder->getForm();
} | php | {
"resource": ""
} |
q255105 | AdminControllerTrait.createDeleteForm | test | protected function createDeleteForm($entityName, $entityId)
{
/** @var FormBuilder $formBuilder */
$formBuilder = $this->get('form.factory')->createNamedBuilder('delete_form')
->setAction($this->generateUrl('easyadmin', ['action' => 'delete', 'entity' => $entityName, 'id' => $entityId]))
->setMethod('DELETE')
;
$formBuilder->add('submit', SubmitType::class, ['label' => 'delete_modal.action', 'translation_domain' => 'EasyAdminBundle']);
// needed to avoid submitting empty delete forms (see issue #1409)
$formBuilder->add('_easyadmin_delete_flag', HiddenType::class, ['data' => '1']);
return $formBuilder->getForm();
} | php | {
"resource": ""
} |
q255106 | AdminControllerTrait.redirectToBackendHomepage | test | protected function redirectToBackendHomepage()
{
$homepageConfig = $this->config['homepage'];
$url = $homepageConfig['url'] ?? $this->get('router')->generate($homepageConfig['route'], $homepageConfig['params']);
return $this->redirect($url);
} | php | {
"resource": ""
} |
q255107 | ControllerListener.onKernelController | test | public function onKernelController(FilterControllerEvent $event)
{
$request = $event->getRequest();
if ('easyadmin' !== $request->attributes->get('_route')) {
return;
}
$currentController = $event->getController();
// if the controller is defined in a class, $currentController is an array
// otherwise do nothing because it's a Closure (rare but possible in Symfony)
if (!\is_array($currentController)) {
return;
}
// this condition happens when accessing the backend homepage, which
// then redirects to the 'list' action of the first configured entity.
if (null === $entityName = $request->query->get('entity')) {
return;
}
$entity = $this->configManager->getEntityConfig($entityName);
// if the entity doesn't define a custom controller, do nothing
if (!isset($entity['controller'])) {
return;
}
// build the full controller name using the 'class::method' syntax
$controllerMethod = $currentController[1];
$customController = $entity['controller'].'::'.$controllerMethod;
$request->attributes->set('_controller', $customController);
$newController = $this->resolver->getController($request);
if (false === $newController) {
throw new NotFoundHttpException(\sprintf('Unable to find the controller for path "%s". Check the "controller" configuration of the "%s" entity in your EasyAdmin backend.', $request->getPathInfo(), $entityName));
}
$event->setController($newController);
} | php | {
"resource": ""
} |
q255108 | MenuConfigPass.normalizeMenuConfig | test | private function normalizeMenuConfig(array $menuConfig, array $backendConfig, $parentItemIndex = -1)
{
// if the backend doesn't define the menu configuration: create a default
// menu configuration to display all its entities
if (empty($menuConfig)) {
foreach ($backendConfig['entities'] as $entityName => $entityConfig) {
$menuConfig[] = ['entity' => $entityName, 'label' => $entityConfig['label']];
}
}
// replaces the short config syntax:
// design.menu: ['Product', 'User']
// by the expanded config syntax:
// design.menu: [{ entity: 'Product' }, { entity: 'User' }]
foreach ($menuConfig as $i => $itemConfig) {
if (\is_string($itemConfig)) {
$itemConfig = ['entity' => $itemConfig];
}
$menuConfig[$i] = $itemConfig;
}
foreach ($menuConfig as $i => $itemConfig) {
// normalize icon configuration
if (!\array_key_exists('icon', $itemConfig)) {
$itemConfig['icon'] = ($parentItemIndex > -1) ? '' : 'fa-folder-open';
} elseif (empty($itemConfig['icon'])) {
$itemConfig['icon'] = null;
} else {
$itemConfig['icon'] = 'fa-'.$itemConfig['icon'];
}
// normalize css_class configuration
if (!\array_key_exists('css_class', $itemConfig)) {
$itemConfig['css_class'] = '';
}
// normalize submenu configuration (only for main menu items)
if (-1 === $parentItemIndex && !isset($itemConfig['children'])) {
$itemConfig['children'] = [];
}
// normalize 'default' option, which sets the menu item used as the backend index
if (!\array_key_exists('default', $itemConfig)) {
$itemConfig['default'] = false;
} else {
$itemConfig['default'] = (bool) $itemConfig['default'];
}
// normalize 'target' option, which allows to open menu items in different windows or tabs
if (!\array_key_exists('target', $itemConfig)) {
$itemConfig['target'] = false;
} else {
$itemConfig['target'] = (string) $itemConfig['target'];
}
// normalize 'rel' option, which adds html5 rel attribute (https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types)
if (!\array_key_exists('rel', $itemConfig)) {
$itemConfig['rel'] = \array_key_exists('url', $itemConfig) ? 'noreferrer' : false;
} else {
$itemConfig['rel'] = (string) $itemConfig['rel'];
}
$menuConfig[$i] = $itemConfig;
}
return $menuConfig;
} | php | {
"resource": ""
} |
q255109 | EasyAdminTwigExtension.getEntityConfiguration | test | public function getEntityConfiguration($entityName)
{
return null !== $this->getBackendConfiguration('entities.'.$entityName)
? $this->configManager->getEntityConfig($entityName)
: null;
} | php | {
"resource": ""
} |
q255110 | EasyAdminTwigExtension.isActionEnabled | test | public function isActionEnabled($view, $action, $entityName)
{
return $this->configManager->isActionEnabled($entityName, $view, $action);
} | php | {
"resource": ""
} |
q255111 | EasyAdminTwigExtension.getActionConfiguration | test | public function getActionConfiguration($view, $action, $entityName)
{
return $this->configManager->getActionConfig($entityName, $view, $action);
} | php | {
"resource": ""
} |
q255112 | EasyAdminTwigExtension.transchoice | test | public function transchoice($message, $count, array $arguments = [], $domain = null, $locale = null)
{
if (null === $this->translator) {
return strtr($message, $arguments);
}
return $this->translator->trans($message, array_merge(['%count%' => $count], $arguments), $domain, $locale);
} | php | {
"resource": ""
} |
q255113 | Paginator.createOrmPaginator | test | public function createOrmPaginator($queryBuilder, $page = 1, $maxPerPage = self::MAX_ITEMS)
{
$query = $queryBuilder->getQuery();
if (0 === \count($queryBuilder->getDQLPart('join'))) {
$query->setHint(CountWalker::HINT_DISTINCT, false);
}
// don't change the following line (you did that twice in the past and broke everything)
$paginator = new Pagerfanta(new DoctrineORMAdapter($query, true, false));
$paginator->setMaxPerPage($maxPerPage);
$paginator->setCurrentPage($page);
return $paginator;
} | php | {
"resource": ""
} |
q255114 | ConfigManager.doProcessConfig | test | private function doProcessConfig($backendConfig): array
{
foreach ($this->configPasses as $configPass) {
$backendConfig = $configPass->process($backendConfig);
}
return $backendConfig;
} | php | {
"resource": ""
} |
q255115 | RequestPostInitializeListener.initializeRequest | test | public function initializeRequest(GenericEvent $event)
{
$request = null;
if (null !== $this->requestStack) {
$request = $this->requestStack->getCurrentRequest();
}
if (null === $request) {
return;
}
$request->attributes->set('easyadmin', [
'entity' => $entity = $event->getArgument('entity'),
'view' => $request->query->get('action', 'list'),
'item' => ($id = $request->query->get('id')) ? $this->findCurrentItem($entity, $id) : null,
]);
} | php | {
"resource": ""
} |
q255116 | RequestPostInitializeListener.findCurrentItem | test | private function findCurrentItem(array $entityConfig, $itemId)
{
if (null === $manager = $this->doctrine->getManagerForClass($entityConfig['class'])) {
throw new \RuntimeException(\sprintf('There is no Doctrine Entity Manager defined for the "%s" class', $entityConfig['class']));
}
if (null === $entity = $manager->getRepository($entityConfig['class'])->find($itemId)) {
throw new EntityNotFoundException(['entity_name' => $entityConfig['name'], 'entity_id_name' => $entityConfig['primary_key_field_name'], 'entity_id_value' => $itemId]);
}
return $entity;
} | php | {
"resource": ""
} |
q255117 | EasyAdminFormType.getAttributesNormalizer | test | private function getAttributesNormalizer()
{
return function (Options $options, $value) {
return \array_replace([
'id' => \sprintf('%s-%s-form', $options['view'], \mb_strtolower($options['entity'])),
], $value);
};
} | php | {
"resource": ""
} |
q255118 | MetadataConfigPass.processEntityPropertiesMetadata | test | private function processEntityPropertiesMetadata(ClassMetadata $entityMetadata)
{
$entityPropertiesMetadata = [];
if ($entityMetadata->isIdentifierComposite) {
throw new \RuntimeException(\sprintf("The '%s' entity isn't valid because it contains a composite primary key.", $entityMetadata->name));
}
// introspect regular entity fields
foreach ($entityMetadata->fieldMappings as $fieldName => $fieldMetadata) {
$entityPropertiesMetadata[$fieldName] = $fieldMetadata;
}
// introspect fields for entity associations
foreach ($entityMetadata->associationMappings as $fieldName => $associationMetadata) {
$entityPropertiesMetadata[$fieldName] = \array_merge($associationMetadata, [
'type' => 'association',
'associationType' => $associationMetadata['type'],
]);
// associations different from *-to-one cannot be sorted
if ($associationMetadata['type'] & ClassMetadata::TO_MANY) {
$entityPropertiesMetadata[$fieldName]['sortable'] = false;
}
}
return $entityPropertiesMetadata;
} | php | {
"resource": ""
} |
q255119 | ActionConfigPass.getDefaultActions | test | private function getDefaultActions($view)
{
$defaultActions = [];
$defaultActionsConfig = $this->getDefaultActionsConfig($view);
// actions are displayed in the same order as defined in this array
$actionsEnabledByView = [
'edit' => ['delete', 'list'],
'list' => ['edit', 'delete', 'new', 'search'],
'new' => ['list'],
'show' => ['edit', 'delete', 'list'],
];
foreach ($actionsEnabledByView[$view] as $actionName) {
$defaultActions[$actionName] = $defaultActionsConfig[$actionName];
}
return $defaultActions;
} | php | {
"resource": ""
} |
q255120 | EasyAdminTabSubscriber.handleViolations | test | public function handleViolations(FormEvent $event)
{
$formTabs = $event->getForm()->getConfig()->getAttribute('easyadmin_form_tabs');
$firstTabWithErrors = null;
foreach ($event->getForm() as $child) {
$errors = $child->getErrors(true);
if (\count($errors) > 0) {
$formTab = $child->getConfig()->getAttribute('easyadmin_form_tab');
$formTabs[$formTab]['errors'] += \count($errors);
if (null === $firstTabWithErrors) {
$firstTabWithErrors = $formTab;
}
}
}
// ensure that the first tab with errors is displayed
$firstTab = \key($formTabs);
if ($firstTab !== $firstTabWithErrors) {
$formTabs[$firstTab]['active'] = false;
$formTabs[$firstTabWithErrors]['active'] = true;
}
} | php | {
"resource": ""
} |
q255121 | Autocomplete.find | test | public function find($entity, $query, $page = 1)
{
if (empty($entity) || empty($query)) {
return ['results' => []];
}
$backendConfig = $this->configManager->getBackendConfig();
if (!isset($backendConfig['entities'][$entity])) {
throw new \InvalidArgumentException(\sprintf('The "entity" argument must contain the name of an entity managed by EasyAdmin ("%s" given).', $entity));
}
$paginator = $this->finder->findByAllProperties($backendConfig['entities'][$entity], $query, $page, $backendConfig['show']['max_results']);
return [
'results' => $this->processResults($paginator->getCurrentPageResults(), $backendConfig['entities'][$entity]),
'has_next_page' => $paginator->hasNextPage(),
];
} | php | {
"resource": ""
} |
q255122 | EasyAdminExtension.processConfigFiles | test | private function processConfigFiles(array $configs)
{
$existingEntityNames = [];
foreach ($configs as $i => $config) {
if (\array_key_exists('entities', $config)) {
$processedConfig = [];
foreach ($config['entities'] as $key => $value) {
$entityConfig = $this->normalizeEntityConfig($key, $value);
$entityName = $this->getUniqueEntityName($key, $entityConfig, $existingEntityNames);
$entityConfig['name'] = $entityName;
$processedConfig[$entityName] = $entityConfig;
$existingEntityNames[] = $entityName;
}
$config['entities'] = $processedConfig;
}
$configs[$i] = $config;
}
return $configs;
} | php | {
"resource": ""
} |
q255123 | EasyAdminExtension.normalizeEntityConfig | test | private function normalizeEntityConfig($entityName, $entityConfig)
{
// normalize config formats #1 and #2 to use the 'class' option as config format #3
if (!\is_array($entityConfig)) {
$entityConfig = ['class' => $entityConfig];
}
// if config format #3 is used, ensure that it defines the 'class' option
if (!isset($entityConfig['class'])) {
throw new \RuntimeException(\sprintf('The "%s" entity must define its associated Doctrine entity class using the "class" option.', $entityName));
}
return $entityConfig;
} | php | {
"resource": ""
} |
q255124 | EasyAdminExtension.getUniqueEntityName | test | private function getUniqueEntityName($entityName, array $entityConfig, array $existingEntityNames)
{
// the shortcut config syntax doesn't require to give entities a name
if (\is_numeric($entityName)) {
$entityClassParts = \explode('\\', $entityConfig['class']);
$entityName = \end($entityClassParts);
}
$i = 2;
$uniqueName = $entityName;
while (\in_array($uniqueName, $existingEntityNames)) {
$uniqueName = $entityName.($i++);
}
$entityName = $uniqueName;
// make sure that the entity name is valid as a PHP method name
// (this is required to allow extending the backend with a custom controller)
if (!$this->isValidMethodName($entityName)) {
throw new \InvalidArgumentException(\sprintf('The name of the "%s" entity contains invalid characters (allowed: letters, numbers, underscores; the first character cannot be a number).', $entityName));
}
return $entityName;
} | php | {
"resource": ""
} |
q255125 | NormalizerConfigPass.normalizeViewConfig | test | private function normalizeViewConfig(array $backendConfig)
{
foreach ($backendConfig['entities'] as $entityName => $entityConfig) {
// if the original 'search' config doesn't define its own DQL filter, use the one form 'list'
if (!isset($entityConfig['search']) || !\array_key_exists('dql_filter', $entityConfig['search'])) {
$entityConfig['search']['dql_filter'] = $entityConfig['list']['dql_filter'] ?? null;
}
foreach (['edit', 'form', 'list', 'new', 'search', 'show'] as $view) {
$entityConfig[$view] = \array_replace_recursive(
$this->defaultViewConfig[$view],
$entityConfig[$view] ?? []
);
}
$backendConfig['entities'][$entityName] = $entityConfig;
}
return $backendConfig;
} | php | {
"resource": ""
} |
q255126 | NormalizerConfigPass.mergeFormConfig | test | private function mergeFormConfig(array $parentConfig, array $childConfig)
{
// save the fields config for later processing
$parentFields = $parentConfig['fields'] ?? [];
$childFields = $childConfig['fields'] ?? [];
$removedFieldNames = $this->getRemovedFieldNames($childFields);
// first, perform a recursive replace to merge both configs
$mergedConfig = \array_replace_recursive($parentConfig, $childConfig);
// merge the config of each field individually
$mergedFields = [];
foreach ($parentFields as $parentFieldName => $parentFieldConfig) {
if (isset($parentFieldConfig['property']) && \in_array($parentFieldConfig['property'], $removedFieldNames)) {
continue;
}
if (!isset($parentFieldConfig['property'])) {
// this isn't a regular form field but a special design element (group, section, divider); add it
$mergedFields[$parentFieldName] = $parentFieldConfig;
continue;
}
$childFieldConfig = $this->findFieldConfigByProperty($childFields, $parentFieldConfig['property']) ?: [];
$mergedFields[$parentFieldName] = \array_replace_recursive($parentFieldConfig, $childFieldConfig);
}
// add back the fields that are defined in child config but not in parent config
foreach ($childFields as $childFieldName => $childFieldConfig) {
$isFormDesignElement = !isset($childFieldConfig['property']);
$isNotRemovedField = isset($childFieldConfig['property']) && 0 !== \strpos($childFieldConfig['property'], '-');
$isNotAlreadyIncluded = isset($childFieldConfig['property']) && !\array_key_exists($childFieldConfig['property'], $mergedFields);
if ($isFormDesignElement || ($isNotRemovedField && $isNotAlreadyIncluded)) {
$mergedFields[$childFieldName] = $childFieldConfig;
}
}
// finally, copy the processed field config into the merged config
$mergedConfig['fields'] = $mergedFields;
return $mergedConfig;
} | php | {
"resource": ""
} |
q255127 | QueryBuilder.createListQueryBuilder | test | public function createListQueryBuilder(array $entityConfig, $sortField = null, $sortDirection = null, $dqlFilter = null)
{
/* @var EntityManager $em */
$em = $this->doctrine->getManagerForClass($entityConfig['class']);
/* @var ClassMetadata $classMetadata */
$classMetadata = $em->getClassMetadata($entityConfig['class']);
/* @var DoctrineQueryBuilder $queryBuilder */
$queryBuilder = $em->createQueryBuilder()
->select('entity')
->from($entityConfig['class'], 'entity')
;
$isSortedByDoctrineAssociation = $this->isDoctrineAssociation($classMetadata, $sortField);
if ($isSortedByDoctrineAssociation) {
$sortFieldParts = \explode('.', $sortField);
$queryBuilder->leftJoin('entity.'.$sortFieldParts[0], $sortFieldParts[0]);
}
if (!empty($dqlFilter)) {
$queryBuilder->andWhere($dqlFilter);
}
if (null !== $sortField) {
$queryBuilder->orderBy(\sprintf('%s%s', $isSortedByDoctrineAssociation ? '' : 'entity.', $sortField), $sortDirection);
}
return $queryBuilder;
} | php | {
"resource": ""
} |
q255128 | QueryBuilder.isDoctrineAssociation | test | protected function isDoctrineAssociation(ClassMetadata $classMetadata, $fieldName)
{
if (null === $fieldName) {
return false;
}
$fieldNameParts = \explode('.', $fieldName);
return false !== \strpos($fieldName, '.') && !\array_key_exists($fieldNameParts[0], $classMetadata->embeddedClasses);
} | php | {
"resource": ""
} |
q255129 | ViewConfigPass.processFieldConfig | test | private function processFieldConfig(array $backendConfig)
{
foreach ($backendConfig['entities'] as $entityName => $entityConfig) {
foreach (['edit', 'list', 'new', 'search', 'show'] as $view) {
foreach ($entityConfig[$view]['fields'] as $fieldName => $fieldConfig) {
if (!isset($fieldConfig['label']) && 'id' === $fieldConfig['property']) {
// if the field is called 'id' and doesn't define a custom label, use 'ID' as label to
// improve the readability of the label, which is usually related to a primary key
$fieldConfig['label'] = 'ID';
} elseif (isset($fieldConfig['label']) && false === $fieldConfig['label']) {
// if the label is the special value 'false', label must be hidden (use an empty string as the label)
$fieldConfig['label'] = '';
$fieldConfig['sortable'] = false;
} elseif (null === $fieldConfig['label'] && 0 !== strpos($fieldConfig['property'], '_easyadmin_form_design_element_')) {
// else, generate the label automatically from its name (except if it's a
// special element created to render complex forms)
$fieldConfig['label'] = $this->humanize($fieldConfig['property']);
}
$backendConfig['entities'][$entityName][$view]['fields'][$fieldName] = $fieldConfig;
}
}
}
return $backendConfig;
} | php | {
"resource": ""
} |
q255130 | ViewConfigPass.getExcludedFieldNames | test | private function getExcludedFieldNames($view, array $entityConfig)
{
$excludedFieldNames = [
'edit' => [$entityConfig['primary_key_field_name']],
'list' => ['password', 'salt', 'slug', 'updatedAt', 'uuid'],
'new' => [$entityConfig['primary_key_field_name']],
'search' => ['password', 'salt'],
'show' => [],
];
return isset($excludedFieldNames[$view]) ? $excludedFieldNames[$view] : [];
} | php | {
"resource": ""
} |
q255131 | ViewConfigPass.filterFieldList | test | private function filterFieldList(array $fields, array $excludedFieldNames, array $excludedFieldTypes, $maxNumFields)
{
$filteredFields = [];
foreach ($fields as $name => $metadata) {
if (!\in_array($name, $excludedFieldNames) && !\in_array($metadata['type'], $excludedFieldTypes)) {
$filteredFields[$name] = $fields[$name];
}
}
if (\count($filteredFields) > $maxNumFields) {
$filteredFields = \array_slice($filteredFields, 0, $maxNumFields, true);
}
return $filteredFields;
} | php | {
"resource": ""
} |
q255132 | ProcessHelper.run | test | public static function run(string $command, string $cwd = null): array
{
$descriptors = [
0 => ['pipe', 'r'], // stdin - read channel
1 => ['pipe', 'w'], // stdout - write channel
2 => ['pipe', 'w'], // stdout - error channel
3 => ['pipe', 'r'], // stdin - This is the pipe we can feed the password into
];
$process = proc_open($command, $descriptors, $pipes, $cwd);
if (!\is_resource($process)) {
throw new \RuntimeException('Can\'t open resource with proc_open.');
}
// Nothing to push to input.
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$error = stream_get_contents($pipes[2]);
fclose($pipes[2]);
fclose($pipes[3]);
// Close all pipes before proc_close! $code === 0 is success.
$code = proc_close($process);
return [trim($code), trim($output), trim($error)];
} | php | {
"resource": ""
} |
q255133 | ServerParse.deleteOrdCheck | test | public static function deleteOrdCheck(string $stmt, int $offset)
{
$sqlType = self::OTHER;
switch ($stmt[$offset + 1]) {
case 'E':
case 'e':
$sqlType = self::dCheck($stmt, $offset);
break;
case 'R':
case 'r':
$sqlType = self::dropCheck($stmt, $offset);
break;
default:
$sqlType = self::OTHER;
}
return $sqlType;
} | php | {
"resource": ""
} |
q255134 | ServerParse.dCheck | test | public static function dCheck(string $stmt, int $offset)
{
if (strlen($stmt) > $offset + 4) {
$res = self::describeCheck($stmt, $offset);
if ($res == self::DESCRIBE) {
return $res;
}
}
// continue check
if (strlen($stmt) > $offset + 6) {
$c1 = $stmt[++$offset];
$c2 = $stmt[++$offset];
$c3 = $stmt[++$offset];
$c4 = $stmt[++$offset];
$c5 = $stmt[++$offset];
$c6 = $stmt[++$offset];
if (($c1 == 'E' || $c1 == 'e') && ($c2 == 'L' || $c2 == 'l')
&& ($c3 == 'E' || $c3 == 'e') && ($c4 == 'T' || $c4 == 't')
&& ($c5 == 'E' || $c5 == 'e')
&& ($c6 == ' ' || $c6 == '\t' || $c6 == '\r' || $c6 == '\n')) {
return self::DELETE;
}
}
return self::OTHER;
} | php | {
"resource": ""
} |
q255135 | ServerParse.uCheck | test | public static function uCheck(string $stmt, int $offset, bool $has_Space = true)
{
if (strlen($stmt) > ++$offset) {
switch ($stmt[$offset]) {
case 'P':
case 'p':
if (strlen($stmt) > $offset + 5) {
$c1 = $stmt[++$offset];
$c2 = $stmt[++$offset];
$c3 = $stmt[++$offset];
$c4 = $stmt[++$offset];
$c5 = $stmt[++$offset];
if (($c1 == 'D' || $c1 == 'd')
&& ($c2 == 'A' || $c2 == 'a')
&& ($c3 == 'T' || $c3 == 't')
&& ($c4 == 'E' || $c4 == 'e')
&& ($has_Space ? (' ' == $c5 || '\t' == $c5 || '\r' == $c5 || '\n' == $c5) : true)) {
return self::UPDATE;
}
}
break;
case 'S':
case 's':
if (strlen($stmt) > $offset + 2) {
$c1 = $stmt[++$offset];
$c2 = $stmt[++$offset];
if (($c1 == 'E' || $c1 == 'e')
&& ($c2 == ' ' || $c2 == '\t' || $c2 == '\r' || $c2 == '\n')) {
return ($offset << 8) | self::USE;
}
}
break;
case 'N':
case 'n':
if (strlen($stmt) > $offset + 5) {
$c1 = $stmt[++$offset];
$c2 = $stmt[++$offset];
$c3 = $stmt[++$offset];
$c4 = $stmt[++$offset];
$c5 = $stmt[++$offset];
if (($c1 == 'L' || $c1 == 'l')
&& ($c2 == 'O' || $c2 == 'o')
&& ($c3 == 'C' || $c3 == 'c')
&& ($c4 == 'K' || $c4 == 'k')
&& ($c5 == ' ' || $c5 == '\t' || $c5 == '\r' || $c5 == '\n')) {
return self::UNLOCK;
}
}
break;
default:
return self::OTHER;
}
}
return self::OTHER;
} | php | {
"resource": ""
} |
q255136 | ByteUtil.readLength | test | public static function readLength(array $data)
{
$length = $data[0];
switch ($length) {
case 251:
return MySQLMessage::$NULL_LENGTH;
case 252:
return self::readUB2($data);
case 253:
return self::readUB3($data);
case 254:
return self::readLong($data);
default:
return $length;
}
} | php | {
"resource": ""
} |
q255137 | ProgressClosureBuilder.build | test | public static function build(OutputInterface $output, $action, $index, $type, $offset)
{
$progress = null;
return function ($increment, $totalObjects, $message = null) use (&$progress, $output, $action, $index, $type, $offset) {
if (null === $progress) {
$progress = new ProgressBar($output, $totalObjects);
$progress->start();
$progress->setProgress($offset);
}
if (null !== $message) {
$progress->clear();
$output->writeln(sprintf('<info>%s</info> <error>%s</error>', $action, $message));
$progress->display();
}
$progress->setMessage(sprintf('<info>%s</info> <comment>%s/%s</comment>', $action, $index, $type));
$progress->advance($increment);
};
} | php | {
"resource": ""
} |
q255138 | ObjectPersister.log | test | private function log(BulkException $e)
{
if (!$this->logger) {
throw $e;
}
$this->logger->error($e);
} | php | {
"resource": ""
} |
q255139 | TemplateContainerSource.getTypes | test | protected function getTypes($config)
{
$types = array();
if (isset($config['types'])) {
foreach ($config['types'] as $typeConfig) {
$types[$typeConfig['name']] = new TypeConfig(
$typeConfig['name'],
$typeConfig['mapping'],
$typeConfig['config']
);
}
}
return $types;
} | php | {
"resource": ""
} |
q255140 | ContainerSource.getConfiguration | test | public function getConfiguration()
{
$indexes = [];
foreach ($this->configArray as $config) {
$types = $this->getTypes($config);
$index = new IndexConfig($config['name'], $types, [
'elasticSearchName' => $config['elasticsearch_name'],
'settings' => $config['settings'],
'useAlias' => $config['use_alias'],
]);
$indexes[$config['name']] = $index;
}
return $indexes;
} | php | {
"resource": ""
} |
q255141 | PagerProviderRegistry.getAllProviders | test | public function getAllProviders()
{
$providers = [];
foreach ($this->providers as $index => $indexProviders) {
foreach ($indexProviders as $type => $providerId) {
$providers[sprintf('%s/%s', $index, $type)] = $this->container->get($providerId);
}
}
return $providers;
} | php | {
"resource": ""
} |
q255142 | PagerProviderRegistry.getIndexProviders | test | public function getIndexProviders($index)
{
if (!isset($this->providers[$index])) {
throw new \InvalidArgumentException(sprintf('No providers were registered for index "%s".', $index));
}
$providers = [];
foreach ($this->providers[$index] as $type => $providerId) {
$providers[$type] = $this->getProvider($index, $type);
}
return $providers;
} | php | {
"resource": ""
} |
q255143 | PagerProviderRegistry.getProvider | test | public function getProvider($index, $type)
{
if (!isset($this->providers[$index][$type])) {
throw new \InvalidArgumentException(sprintf('No provider was registered for index "%s" and type "%s".', $index, $type));
}
return $this->container->get($this->providers[$index][$type]);
} | php | {
"resource": ""
} |
q255144 | PaginateElasticaQuerySubscriber.setSorting | test | protected function setSorting(ItemsEvent $event)
{
$options = $event->options;
$sortField = $this->getRequest()->get($options['sortFieldParameterName']);
if (!$sortField && isset($options['defaultSortFieldName'])) {
$sortField = $options['defaultSortFieldName'];
}
if (!empty($sortField)) {
$event->target->getQuery()->setSort([
$sortField => $this->getSort($sortField, $options),
]);
}
} | php | {
"resource": ""
} |
q255145 | MappingBuilder.buildIndexMapping | test | public function buildIndexMapping(IndexConfigInterface $indexConfig)
{
$typeMappings = [];
foreach ($indexConfig->getTypes() as $typeConfig) {
$typeMappings[$typeConfig->getName()] = $this->buildTypeMapping($typeConfig);
}
$mapping = [];
if (!empty($typeMappings)) {
$mapping['mappings'] = $typeMappings;
}
// 'warmers' => $indexConfig->getWarmers(),
$settings = $indexConfig->getSettings();
if (!empty($settings)) {
$mapping['settings'] = $settings;
}
return $mapping;
} | php | {
"resource": ""
} |
q255146 | MappingBuilder.buildIndexTemplateMapping | test | public function buildIndexTemplateMapping(IndexTemplateConfig $indexTemplateConfig)
{
$mapping = $this->buildIndexMapping($indexTemplateConfig);
$mapping['template'] = $indexTemplateConfig->getTemplate();
return $mapping;
} | php | {
"resource": ""
} |
q255147 | MappingBuilder.buildTypeMapping | test | public function buildTypeMapping(TypeConfig $typeConfig)
{
$mapping = $typeConfig->getMapping();
if (null !== $typeConfig->getDynamicDateFormats()) {
$mapping['dynamic_date_formats'] = $typeConfig->getDynamicDateFormats();
}
if (null !== $typeConfig->getDateDetection()) {
$mapping['date_detection'] = $typeConfig->getDateDetection();
}
if (null !== $typeConfig->getNumericDetection()) {
$mapping['numeric_detection'] = $typeConfig->getNumericDetection();
}
if ($typeConfig->getAnalyzer()) {
$mapping['analyzer'] = $typeConfig->getAnalyzer();
}
if (null !== $typeConfig->getDynamic()) {
$mapping['dynamic'] = $typeConfig->getDynamic();
}
if (isset($mapping['dynamic_templates']) and empty($mapping['dynamic_templates'])) {
unset($mapping['dynamic_templates']);
}
$this->fixProperties($mapping['properties']);
if (!$mapping['properties']) {
unset($mapping['properties']);
}
if ($typeConfig->getModel()) {
$mapping['_meta']['model'] = $typeConfig->getModel();
}
unset($mapping['_parent']['identifier'], $mapping['_parent']['property']);
if (empty($mapping)) {
// Empty mapping, we want it encoded as a {} instead of a []
$mapping = new \ArrayObject();
}
return $mapping;
} | php | {
"resource": ""
} |
q255148 | MappingBuilder.fixProperties | test | private function fixProperties(&$properties)
{
foreach ($properties as $name => &$property) {
unset($property['property_path']);
if (!isset($property['type'])) {
$property['type'] = 'text';
}
if (isset($property['fields'])) {
$this->fixProperties($property['fields']);
}
if (isset($property['properties'])) {
$this->fixProperties($property['properties']);
}
}
} | php | {
"resource": ""
} |
q255149 | ElasticaLogger.logQuery | test | public function logQuery($path, $method, $data, $queryTime, $connection = [], $query = [], $engineTime = 0, $itemCount = 0)
{
$executionMS = $queryTime * 1000;
if ($this->debug) {
$e = new \Exception();
if (is_string($data)) {
$jsonStrings = explode("\n", $data);
$data = [];
foreach ($jsonStrings as $json) {
if ($json != '') {
$data[] = json_decode($json, true);
}
}
} else {
$data = [$data];
}
$this->queries[] = [
'path' => $path,
'method' => $method,
'data' => $data,
'executionMS' => $executionMS,
'engineMS' => $engineTime,
'connection' => $connection,
'queryString' => $query,
'itemCount' => $itemCount,
'backtrace' => $e->getTraceAsString(),
];
}
if (null !== $this->logger) {
$message = sprintf('%s (%s) %0.2f ms', $path, $method, $executionMS);
$this->logger->info($message, (array) $data);
}
} | php | {
"resource": ""
} |
q255150 | ObjectSerializerPersister.transformToElasticaDocument | test | public function transformToElasticaDocument($object)
{
$document = $this->transformer->transform($object, []);
$data = call_user_func($this->serializer, $object);
$document->setData($data);
return $document;
} | php | {
"resource": ""
} |
q255151 | RawPaginatorAdapter.getTotalHits | test | public function getTotalHits($genuineTotal = false)
{
if (!isset($this->totalHits)) {
$this->totalHits = $this->searchable->count($this->query);
}
return $this->query->hasParam('size') && !$genuineTotal
? min($this->totalHits, (int) $this->query->getParam('size'))
: $this->totalHits;
} | php | {
"resource": ""
} |
q255152 | RawPaginatorAdapter.getElasticaResults | test | protected function getElasticaResults($offset, $itemCountPerPage)
{
$offset = (int) $offset;
$itemCountPerPage = (int) $itemCountPerPage;
$size = $this->query->hasParam('size')
? (int) $this->query->getParam('size')
: null;
if (null !== $size && $size < $offset + $itemCountPerPage) {
$itemCountPerPage = $size - $offset;
}
if ($itemCountPerPage < 1) {
throw new InvalidArgumentException('$itemCountPerPage must be greater than zero');
}
$query = clone $this->query;
$query->setFrom($offset);
$query->setSize($itemCountPerPage);
$resultSet = $this->searchable->search($query, $this->options);
$this->totalHits = $resultSet->getTotalHits();
$this->aggregations = $resultSet->getAggregations();
$this->suggests = $resultSet->getSuggests();
$this->maxScore = $resultSet->getMaxScore();
return $resultSet;
} | php | {
"resource": ""
} |
q255153 | TemplateResetter.deleteTemplateIndexes | test | public function deleteTemplateIndexes(IndexTemplateConfig $template)
{
$this->client->request($template->getTemplate() . '/', Request::DELETE);
} | php | {
"resource": ""
} |
q255154 | IndexManager.getIndex | test | public function getIndex($name = null)
{
if (null === $name) {
return $this->defaultIndex;
}
if (!isset($this->indexes[$name])) {
throw new \InvalidArgumentException(sprintf('The index "%s" does not exist', $name));
}
return $this->indexes[$name];
} | php | {
"resource": ""
} |
q255155 | PersisterRegistry.getPersister | test | public function getPersister($index, $type)
{
if (!isset($this->persisters[$index][$type])) {
throw new \InvalidArgumentException(sprintf('No persister was registered for index "%s" and type "%s".', $index, $type));
}
return $this->container->get($this->persisters[$index][$type]);
} | php | {
"resource": ""
} |
q255156 | PopulateCommand.populateIndex | test | private function populateIndex(OutputInterface $output, $index, $reset, $options)
{
$event = new IndexPopulateEvent($index, $reset, $options);
$this->dispatcher->dispatch(IndexPopulateEvent::PRE_INDEX_POPULATE, $event);
if ($event->isReset()) {
$output->writeln(sprintf('<info>Resetting</info> <comment>%s</comment>', $index));
$this->resetter->resetIndex($index, true);
}
$types = array_keys($this->pagerProviderRegistry->getIndexProviders($index));
foreach ($types as $type) {
$this->populateIndexType($output, $index, $type, false, $event->getOptions());
}
$this->dispatcher->dispatch(IndexPopulateEvent::POST_INDEX_POPULATE, $event);
$this->refreshIndex($output, $index);
} | php | {
"resource": ""
} |
q255157 | PopulateCommand.refreshIndex | test | private function refreshIndex(OutputInterface $output, $index)
{
$output->writeln(sprintf('<info>Refreshing</info> <comment>%s</comment>', $index));
$this->indexManager->getIndex($index)->refresh();
} | php | {
"resource": ""
} |
q255158 | ModelToElasticaAutoTransformer.transform | test | public function transform($object, array $fields)
{
$identifier = $this->propertyAccessor->getValue($object, $this->options['identifier']);
if ($identifier && !is_scalar($identifier)) {
$identifier = (string) $identifier;
}
return $this->transformObjectToDocument($object, $fields, $identifier);
} | php | {
"resource": ""
} |
q255159 | ModelToElasticaAutoTransformer.transformNested | test | protected function transformNested($objects, array $fields)
{
if (is_array($objects) || $objects instanceof \Traversable || $objects instanceof \ArrayAccess) {
$documents = [];
foreach ($objects as $object) {
$document = $this->transformObjectToDocument($object, $fields);
$documents[] = $document->getData();
}
return $documents;
} elseif (null !== $objects) {
$document = $this->transformObjectToDocument($objects, $fields);
return $document->getData();
}
return [];
} | php | {
"resource": ""
} |
q255160 | ModelToElasticaAutoTransformer.normalizeValue | test | protected function normalizeValue($value)
{
$normalizeValue = function (&$v) {
if ($v instanceof \DateTimeInterface) {
$v = $v->format('c');
} elseif (!is_scalar($v) && !is_null($v)) {
$v = (string) $v;
}
};
if (is_array($value) || $value instanceof \Traversable || $value instanceof \ArrayAccess) {
$value = is_array($value) ? $value : iterator_to_array($value, false);
array_walk_recursive($value, $normalizeValue);
} else {
$normalizeValue($value);
}
return $value;
} | php | {
"resource": ""
} |
q255161 | ModelToElasticaAutoTransformer.transformObjectToDocument | test | protected function transformObjectToDocument($object, array $fields, $identifier = '')
{
$document = new Document($identifier, [], '', $this->options['index']);
if ($this->dispatcher) {
$event = new TransformEvent($document, $fields, $object);
$this->dispatcher->dispatch(TransformEvent::PRE_TRANSFORM, $event);
$document = $event->getDocument();
}
foreach ($fields as $key => $mapping) {
if ('_parent' == $key) {
$property = (null !== $mapping['property']) ? $mapping['property'] : $mapping['type'];
$value = $this->propertyAccessor->getValue($object, $property);
$document->setParent($this->propertyAccessor->getValue($value, $mapping['identifier']));
continue;
}
$path = isset($mapping['property_path']) ?
$mapping['property_path'] :
$key;
if (false === $path) {
continue;
}
$value = $this->propertyAccessor->getValue($object, $path);
if (isset($mapping['type']) && in_array(
$mapping['type'], ['nested', 'object']
) && isset($mapping['properties']) && !empty($mapping['properties'])
) {
/* $value is a nested document or object. Transform $value into
* an array of documents, respective the mapped properties.
*/
$document->set($key, $this->transformNested($value, $mapping['properties']));
continue;
}
if (isset($mapping['type']) && 'attachment' == $mapping['type']) {
// $value is an attachment. Add it to the document.
if ($value instanceof \SplFileInfo) {
$document->addFile($key, $value->getPathName());
} else {
$document->addFileContent($key, $value);
}
continue;
}
$document->set($key, $this->normalizeValue($value));
}
if ($this->dispatcher) {
$event = new TransformEvent($document, $fields, $object);
$this->dispatcher->dispatch(TransformEvent::POST_TRANSFORM, $event);
$document = $event->getDocument();
}
return $document;
} | php | {
"resource": ""
} |
q255162 | ElasticaToModelTransformer.getEntityQueryBuilder | test | protected function getEntityQueryBuilder()
{
$repository = $this->registry
->getManagerForClass($this->objectClass)
->getRepository($this->objectClass);
return $repository->{$this->options['query_builder_method']}(static::ENTITY_ALIAS);
} | php | {
"resource": ""
} |
q255163 | IndexTemplateManager.getIndexTemplate | test | public function getIndexTemplate($name)
{
if (!isset($this->templates[$name])) {
throw new \InvalidArgumentException(sprintf('The index template "%s" does not exist', $name));
}
return $this->templates[$name];
} | php | {
"resource": ""
} |
q255164 | Resetter.resetAllIndexes | test | public function resetAllIndexes($populating = false, $force = false)
{
foreach ($this->configManager->getIndexNames() as $name) {
$this->resetIndex($name, $populating, $force);
}
} | php | {
"resource": ""
} |
q255165 | Resetter.resetIndex | test | public function resetIndex($indexName, $populating = false, $force = false)
{
$indexConfig = $this->configManager->getIndexConfiguration($indexName);
$index = $this->indexManager->getIndex($indexName);
if ($indexConfig->isUseAlias()) {
$this->aliasProcessor->setRootName($indexConfig, $index);
}
$event = new IndexResetEvent($indexName, $populating, $force);
$this->dispatcher->dispatch(IndexResetEvent::PRE_INDEX_RESET, $event);
$mapping = $this->mappingBuilder->buildIndexMapping($indexConfig);
$index->create($mapping, true);
if (!$populating and $indexConfig->isUseAlias()) {
$this->aliasProcessor->switchIndexAlias($indexConfig, $index, $force);
}
$this->dispatcher->dispatch(IndexResetEvent::POST_INDEX_RESET, $event);
} | php | {
"resource": ""
} |
q255166 | Resetter.resetIndexType | test | public function resetIndexType($indexName, $typeName)
{
$typeConfig = $this->configManager->getTypeConfiguration($indexName, $typeName);
$this->resetIndex($indexName, true);
$index = $this->indexManager->getIndex($indexName);
$type = $index->getType($typeName);
$event = new TypeResetEvent($indexName, $typeName);
$this->dispatcher->dispatch(TypeResetEvent::PRE_TYPE_RESET, $event);
$mapping = new Mapping();
foreach ($this->mappingBuilder->buildTypeMapping($typeConfig) as $name => $field) {
$mapping->setParam($name, $field);
}
$type->setMapping($mapping);
$this->dispatcher->dispatch(TypeResetEvent::POST_TYPE_RESET, $event);
} | php | {
"resource": ""
} |
q255167 | Resetter.switchIndexAlias | test | public function switchIndexAlias($indexName, $delete = true)
{
$indexConfig = $this->configManager->getIndexConfiguration($indexName);
if ($indexConfig->isUseAlias()) {
$index = $this->indexManager->getIndex($indexName);
$this->aliasProcessor->switchIndexAlias($indexConfig, $index, false, $delete);
}
} | php | {
"resource": ""
} |
q255168 | FOSElasticaExtension.loadIndexFinder | test | private function loadIndexFinder(ContainerBuilder $container, $name, Reference $index)
{
/* Note: transformer services may conflict with "collection.index", if
* an index and type names were "collection" and an index, respectively.
*/
$transformerId = sprintf('fos_elastica.elastica_to_model_transformer.collection.%s', $name);
$transformerDef = new ChildDefinition('fos_elastica.elastica_to_model_transformer.collection');
$container->setDefinition($transformerId, $transformerDef);
$finderId = sprintf('fos_elastica.finder.%s', $name);
$finderDef = new ChildDefinition('fos_elastica.finder');
$finderDef->replaceArgument(0, $index);
$finderDef->replaceArgument(1, new Reference($transformerId));
$container->setDefinition($finderId, $finderDef);
} | php | {
"resource": ""
} |
q255169 | FOSElasticaExtension.loadTypePersistenceIntegration | test | private function loadTypePersistenceIntegration(array $typeConfig, ContainerBuilder $container, Reference $typeRef, $indexName, $typeName)
{
if (isset($typeConfig['driver'])) {
$this->loadDriver($container, $typeConfig['driver']);
}
$elasticaToModelTransformerId = $this->loadElasticaToModelTransformer($typeConfig, $container, $indexName, $typeName);
$modelToElasticaTransformerId = $this->loadModelToElasticaTransformer($typeConfig, $container, $indexName, $typeName);
$objectPersisterId = $this->loadObjectPersister($typeConfig, $typeRef, $container, $indexName, $typeName, $modelToElasticaTransformerId);
if (isset($typeConfig['provider'])) {
$this->loadTypePagerProvider($typeConfig, $container, $indexName, $typeName);
}
if (isset($typeConfig['finder'])) {
$this->loadTypeFinder($typeConfig, $container, $elasticaToModelTransformerId, $typeRef, $indexName, $typeName);
}
if (isset($typeConfig['listener']) && $typeConfig['listener']['enabled']) {
$this->loadTypeListener($typeConfig, $container, $objectPersisterId, $indexName, $typeName);
}
} | php | {
"resource": ""
} |
q255170 | FOSElasticaExtension.loadElasticaToModelTransformer | test | private function loadElasticaToModelTransformer(array $typeConfig, ContainerBuilder $container, $indexName, $typeName)
{
if (isset($typeConfig['elastica_to_model_transformer']['service'])) {
return $typeConfig['elastica_to_model_transformer']['service'];
}
/* Note: transformer services may conflict with "prototype.driver", if
* the index and type names were "prototype" and a driver, respectively.
*/
$abstractId = sprintf('fos_elastica.elastica_to_model_transformer.prototype.%s', $typeConfig['driver']);
$serviceId = sprintf('fos_elastica.elastica_to_model_transformer.%s.%s', $indexName, $typeName);
$serviceDef = new ChildDefinition($abstractId);
$serviceDef->addTag('fos_elastica.elastica_to_model_transformer', ['type' => $typeName, 'index' => $indexName]);
$serviceDef->replaceArgument(1, $typeConfig['model']);
$serviceDef->replaceArgument(2, array_merge($typeConfig['elastica_to_model_transformer'], [
'identifier' => $typeConfig['identifier'],
]));
$container->setDefinition($serviceId, $serviceDef);
return $serviceId;
} | php | {
"resource": ""
} |
q255171 | FOSElasticaExtension.loadObjectPersister | test | private function loadObjectPersister(array $typeConfig, Reference $typeRef, ContainerBuilder $container, $indexName, $typeName, $transformerId)
{
if (isset($typeConfig['persister']['service'])) {
return $typeConfig['persister']['service'];
}
$arguments = [
$typeRef,
new Reference($transformerId),
$typeConfig['model'],
];
if ($container->hasDefinition('fos_elastica.serializer_callback_prototype')) {
$abstractId = 'fos_elastica.object_serializer_persister';
$callbackId = sprintf('%s.%s.serializer.callback', $this->indexConfigs[$indexName]['reference'], $typeName);
$arguments[] = [new Reference($callbackId), 'serialize'];
} else {
$abstractId = 'fos_elastica.object_persister';
$mapping = $this->indexConfigs[$indexName]['types'][$typeName]['mapping'];
$argument = $mapping['properties'];
if (isset($mapping['_parent'])) {
$argument['_parent'] = $mapping['_parent'];
}
$arguments[] = $argument;
}
$arguments[] = array_intersect_key($typeConfig['persister'], array_flip(['refresh']));
$serviceId = sprintf('fos_elastica.object_persister.%s.%s', $indexName, $typeName);
$serviceDef = new ChildDefinition($abstractId);
foreach ($arguments as $i => $argument) {
$serviceDef->replaceArgument($i, $argument);
}
$serviceDef->addTag('fos_elastica.persister', ['index' => $indexName, 'type' => $typeName]);
$container->setDefinition($serviceId, $serviceDef);
return $serviceId;
} | php | {
"resource": ""
} |
q255172 | FOSElasticaExtension.loadTypePagerProvider | test | private function loadTypePagerProvider(array $typeConfig, ContainerBuilder $container, $indexName, $typeName)
{
if (isset($typeConfig['provider']['service'])) {
return $typeConfig['provider']['service'];
}
$baseConfig = $typeConfig['provider'];
unset($baseConfig['service']);
$driver = $typeConfig['driver'];
switch ($driver) {
case 'orm':
$providerDef = new ChildDefinition('fos_elastica.pager_provider.prototype.'.$driver);
$providerDef->replaceArgument(2, $typeConfig['model']);
$providerDef->replaceArgument(3, $baseConfig);
break;
case 'mongodb':
$providerDef = new ChildDefinition('fos_elastica.pager_provider.prototype.'.$driver);
$providerDef->replaceArgument(2, $typeConfig['model']);
$providerDef->replaceArgument(3, $baseConfig);
break;
case 'phpcr':
$providerDef = new ChildDefinition('fos_elastica.pager_provider.prototype.'.$driver);
$providerDef->replaceArgument(2, $typeConfig['model']);
$providerDef->replaceArgument(3, $baseConfig);
break;
default:
throw new \LogicException(sprintf('The pager provider for driver "%s" does not exist.', $driver));
}
/* Note: provider services may conflict with "prototype.driver", if the
* index and type names were "prototype" and a driver, respectively.
*/
$providerId = sprintf('fos_elastica.pager_provider.%s.%s', $indexName, $typeName);
$providerDef->addTag('fos_elastica.pager_provider', ['index' => $indexName, 'type' => $typeName]);
$container->setDefinition($providerId, $providerDef);
return $providerId;
} | php | {
"resource": ""
} |
q255173 | FOSElasticaExtension.loadTypeListener | test | private function loadTypeListener(array $typeConfig, ContainerBuilder $container, $objectPersisterId, $indexName, $typeName)
{
if (isset($typeConfig['listener']['service'])) {
return $typeConfig['listener']['service'];
}
/* Note: listener services may conflict with "prototype.driver", if the
* index and type names were "prototype" and a driver, respectively.
*/
$abstractListenerId = sprintf('fos_elastica.listener.prototype.%s', $typeConfig['driver']);
$listenerId = sprintf('fos_elastica.listener.%s.%s', $indexName, $typeName);
$listenerDef = new ChildDefinition($abstractListenerId);
$listenerDef->replaceArgument(0, new Reference($objectPersisterId));
$listenerDef->replaceArgument(3, $typeConfig['listener']['logger'] ?
new Reference($typeConfig['listener']['logger']) :
null
);
$listenerConfig = [
'identifier' => $typeConfig['identifier'],
'indexName' => $indexName,
'typeName' => $typeName,
];
$tagName = null;
switch ($typeConfig['driver']) {
case 'orm':
$tagName = 'doctrine.event_listener';
break;
case 'phpcr':
$tagName = 'doctrine_phpcr.event_listener';
break;
case 'mongodb':
$tagName = 'doctrine_mongodb.odm.event_listener';
break;
}
if ($typeConfig['listener']['defer']) {
$listenerDef->setPublic(true);
$listenerDef->addTag(
'kernel.event_listener',
['event' => 'kernel.terminate', 'method' => 'onTerminate']
);
$listenerDef->addTag(
'kernel.event_listener',
['event' => 'console.terminate', 'method' => 'onTerminate']
);
$listenerConfig['defer'] = true;
}
$listenerDef->replaceArgument(2, $listenerConfig);
if (null !== $tagName) {
foreach ($this->getDoctrineEvents($typeConfig) as $event) {
$listenerDef->addTag($tagName, ['event' => $event]);
}
}
$container->setDefinition($listenerId, $listenerDef);
return $listenerId;
} | php | {
"resource": ""
} |
q255174 | FOSElasticaExtension.getDoctrineEvents | test | private function getDoctrineEvents(array $typeConfig)
{
switch ($typeConfig['driver']) {
case 'orm':
$eventsClass = '\Doctrine\ORM\Events';
break;
case 'phpcr':
$eventsClass = '\Doctrine\ODM\PHPCR\Event';
break;
case 'mongodb':
$eventsClass = '\Doctrine\ODM\MongoDB\Events';
break;
default:
throw new \InvalidArgumentException(sprintf('Cannot determine events for driver "%s"', $typeConfig['driver']));
}
$events = [];
$eventMapping = [
'insert' => [constant($eventsClass.'::postPersist')],
'update' => [constant($eventsClass.'::postUpdate')],
'delete' => [constant($eventsClass.'::preRemove')],
'flush' => [constant($eventsClass.'::postFlush')],
];
foreach ($eventMapping as $event => $doctrineEvents) {
if (isset($typeConfig['listener'][$event]) && $typeConfig['listener'][$event]) {
$events = array_merge($events, $doctrineEvents);
}
}
return $events;
} | php | {
"resource": ""
} |
q255175 | FOSElasticaExtension.loadTypeFinder | test | private function loadTypeFinder(array $typeConfig, ContainerBuilder $container, $elasticaToModelId, Reference $typeRef, $indexName, $typeName)
{
if (isset($typeConfig['finder']['service'])) {
$finderId = $typeConfig['finder']['service'];
} else {
$finderId = sprintf('fos_elastica.finder.%s.%s', $indexName, $typeName);
$finderDef = new ChildDefinition('fos_elastica.finder');
$finderDef->replaceArgument(0, $typeRef);
$finderDef->replaceArgument(1, new Reference($elasticaToModelId));
$container->setDefinition($finderId, $finderDef);
}
$indexTypeName = "$indexName/$typeName";
$arguments = [$indexTypeName, new Reference($finderId)];
if (isset($typeConfig['repository'])) {
$arguments[] = $typeConfig['repository'];
}
$container->getDefinition('fos_elastica.repository_manager')
->addMethodCall('addType', $arguments);
$managerId = sprintf('fos_elastica.manager.%s', $typeConfig['driver']);
$container->getDefinition($managerId)
->addMethodCall('addEntity', [$typeConfig['model'], $indexTypeName]);
return $finderId;
} | php | {
"resource": ""
} |
q255176 | FOSElasticaExtension.loadIndexManager | test | private function loadIndexManager(ContainerBuilder $container)
{
$indexRefs = array_map(function ($index) {
return $index['reference'];
}, $this->indexConfigs);
$managerDef = $container->getDefinition('fos_elastica.index_manager');
$managerDef->replaceArgument(0, $indexRefs);
} | php | {
"resource": ""
} |
q255177 | FOSElasticaExtension.loadIndexTemplateManager | test | private function loadIndexTemplateManager(ContainerBuilder $container)
{
$indexTemplateRefs = array_map(function ($index) {
return $index['reference'];
}, $this->indexTemplateConfigs);
$managerDef = $container->getDefinition('fos_elastica.index_template_manager');
$managerDef->replaceArgument(0, $indexTemplateRefs);
} | php | {
"resource": ""
} |
q255178 | FOSElasticaExtension.loadDriver | test | private function loadDriver(ContainerBuilder $container, $driver)
{
if (in_array($driver, $this->loadedDrivers)) {
return;
}
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load($driver.'.xml');
$this->loadedDrivers[] = $driver;
} | php | {
"resource": ""
} |
q255179 | FOSElasticaExtension.loadSerializer | test | private function loadSerializer($config, ContainerBuilder $container)
{
$container->setAlias('fos_elastica.serializer', $config['serializer']);
$serializer = $container->getDefinition('fos_elastica.serializer_callback_prototype');
$serializer->setClass($config['callback_class']);
if (is_subclass_of($config['callback_class'], ContainerAwareInterface::class)) {
$serializer->addMethodCall('setContainer', [new Reference('service_container')]);
}
} | php | {
"resource": ""
} |
q255180 | FOSElasticaExtension.createDefaultManagerAlias | test | private function createDefaultManagerAlias($defaultManager, ContainerBuilder $container)
{
if (0 == count($this->loadedDrivers)) {
return;
}
if (count($this->loadedDrivers) > 1
&& in_array($defaultManager, $this->loadedDrivers)
) {
$defaultManagerService = $defaultManager;
} else {
$defaultManagerService = $this->loadedDrivers[0];
}
$container->setAlias('fos_elastica.manager', sprintf('fos_elastica.manager.%s', $defaultManagerService));
$container->getAlias('fos_elastica.manager')->setPublic(true);
$container->setAlias(RepositoryManagerInterface::class, 'fos_elastica.manager');
$container->getAlias(RepositoryManagerInterface::class)->setPublic(false);
} | php | {
"resource": ""
} |
q255181 | Configuration.getDynamicTemplateNode | test | private function getDynamicTemplateNode()
{
$node = $this->createTreeBuilderNode('dynamic_templates');
$node
->prototype('array')
->prototype('array')
->children()
->scalarNode('match')->end()
->scalarNode('unmatch')->end()
->scalarNode('match_mapping_type')->end()
->scalarNode('path_match')->end()
->scalarNode('path_unmatch')->end()
->scalarNode('match_pattern')->end()
->arrayNode('mapping')
->prototype('variable')
->treatNullLike([])
->end()
->end()
->end()
->end()
->end()
;
return $node;
} | php | {
"resource": ""
} |
q255182 | Configuration.getTypesNode | test | private function getTypesNode()
{
$node = $this->createTreeBuilderNode('types');
$node
->useAttributeAsKey('name')
->prototype('array')
->treatNullLike([])
->beforeNormalization()
->ifNull()
->thenEmptyArray()
->end()
// Support multiple dynamic_template formats to match the old bundle style
// and the way ElasticSearch expects them
->beforeNormalization()
->ifTrue(function ($v) {
return isset($v['dynamic_templates']);
})
->then(function ($v) {
$dt = [];
foreach ($v['dynamic_templates'] as $key => $type) {
if (is_int($key)) {
$dt[] = $type;
} else {
$dt[][$key] = $type;
}
}
$v['dynamic_templates'] = $dt;
return $v;
})
->end()
->children()
->booleanNode('date_detection')->end()
->arrayNode('dynamic_date_formats')->prototype('scalar')->end()->end()
->scalarNode('analyzer')->end()
->booleanNode('numeric_detection')->end()
->scalarNode('dynamic')->end()
->variableNode('indexable_callback')->end()
->append($this->getPersistenceNode())
->append($this->getSerializerNode())
->end()
->append($this->getIdNode())
->append($this->getPropertiesNode())
->append($this->getDynamicTemplateNode())
->append($this->getSourceNode())
->append($this->getRoutingNode())
->append($this->getParentNode())
->append($this->getAllNode())
->end()
;
return $node;
} | php | {
"resource": ""
} |
q255183 | Configuration.getIdNode | test | private function getIdNode()
{
$node = $this->createTreeBuilderNode('_id');
$node
->children()
->scalarNode('path')->end()
->end()
;
return $node;
} | php | {
"resource": ""
} |
q255184 | Configuration.getSourceNode | test | private function getSourceNode()
{
$node = $this->createTreeBuilderNode('_source');
$node
->children()
->arrayNode('excludes')
->useAttributeAsKey('name')
->prototype('scalar')->end()
->end()
->arrayNode('includes')
->useAttributeAsKey('name')
->prototype('scalar')->end()
->end()
->scalarNode('compress')->end()
->scalarNode('compress_threshold')->end()
->scalarNode('enabled')->defaultTrue()->end()
->end()
;
return $node;
} | php | {
"resource": ""
} |
q255185 | Configuration.getRoutingNode | test | private function getRoutingNode()
{
$node = $this->createTreeBuilderNode('_routing');
$node
->children()
->scalarNode('required')->end()
->scalarNode('path')->end()
->end()
;
return $node;
} | php | {
"resource": ""
} |
q255186 | Configuration.getParentNode | test | private function getParentNode()
{
$node = $this->createTreeBuilderNode('_parent');
$node
->children()
->scalarNode('type')->end()
->scalarNode('property')->defaultValue(null)->end()
->scalarNode('identifier')->defaultValue('id')->end()
->end()
;
return $node;
} | php | {
"resource": ""
} |
q255187 | Configuration.getAllNode | test | private function getAllNode()
{
$node = $this->createTreeBuilderNode('_all');
$node
->children()
->scalarNode('enabled')->defaultValue(true)->end()
->scalarNode('analyzer')->end()
->end()
;
return $node;
} | php | {
"resource": ""
} |
q255188 | Configuration.addIndexesSection | test | private function addIndexesSection(ArrayNodeDefinition $rootNode)
{
$rootNode
->fixXmlConfig('index')
->children()
->arrayNode('indexes')
->useAttributeAsKey('name')
->prototype('array')
->children()
->scalarNode('index_name')
->info('Defaults to the name of the index, but can be modified if the index name is different in ElasticSearch')
->end()
->booleanNode('use_alias')->defaultValue(false)->end()
->scalarNode('client')->end()
->scalarNode('finder')
->treatNullLike(true)
->defaultFalse()
->end()
->arrayNode('type_prototype')
->children()
->scalarNode('analyzer')->end()
->append($this->getPersistenceNode())
->append($this->getSerializerNode())
->end()
->end()
->variableNode('settings')->defaultValue([])->end()
->end()
->append($this->getTypesNode())
->end()
->end()
->end()
;
} | php | {
"resource": ""
} |
q255189 | Configuration.addIndexTemplatesSection | test | private function addIndexTemplatesSection(ArrayNodeDefinition $rootNode)
{
$rootNode
->fixXmlConfig('index_template')
->children()
->arrayNode('index_templates')
->useAttributeAsKey('name')
->prototype('array')
->children()
->scalarNode('template_name')
->info('Defaults to the name of the index template, but can be modified if the index name is different in ElasticSearch')
->end()
->scalarNode('template')->isRequired()->end()
->scalarNode('client')->end()
->variableNode('settings')->defaultValue([])->end()
->end()
->append($this->getTypesNode())
->end()
->end()
->end()
;
} | php | {
"resource": ""
} |
q255190 | AbstractElasticaToModelTransformer.transform | test | public function transform(array $elasticaObjects)
{
$ids = $highlights = [];
foreach ($elasticaObjects as $elasticaObject) {
$ids[] = $elasticaObject->getId();
$highlights[$elasticaObject->getId()] = $elasticaObject->getHighlights();
}
$objects = $this->findByIdentifiers($ids, $this->options['hydrate']);
$objectsCnt = count($objects);
$elasticaObjectsCnt = count($elasticaObjects);
if (!$this->options['ignore_missing'] && $objectsCnt < $elasticaObjectsCnt) {
throw new \RuntimeException(sprintf('Cannot find corresponding Doctrine objects (%d) for all Elastica results (%d). IDs: %s', $objectsCnt, $elasticaObjectsCnt, implode(', ', $ids)));
}
$propertyAccessor = $this->propertyAccessor;
$identifier = $this->options['identifier'];
foreach ($objects as $object) {
if ($object instanceof HighlightableModelInterface) {
$id = $propertyAccessor->getValue($object, $identifier);
$object->setElasticHighlights($highlights[(string) $id]);
}
}
// sort objects in the order of ids
$idPos = array_flip($ids);
usort(
$objects,
function ($a, $b) use ($idPos, $identifier, $propertyAccessor) {
if ($this->options['hydrate']) {
return $idPos[(string) $propertyAccessor->getValue(
$a,
$identifier
)] > $idPos[(string) $propertyAccessor->getValue($b, $identifier)];
}
return $idPos[$a[$identifier]] > $idPos[$b[$identifier]];
}
);
return $objects;
} | php | {
"resource": ""
} |
q255191 | Indexable.isObjectIndexable | test | public function isObjectIndexable($indexName, $typeName, $object)
{
$type = sprintf('%s/%s', $indexName, $typeName);
$callback = $this->getCallback($type, $object);
if (!$callback) {
return true;
}
if ($callback instanceof Expression) {
return (bool) $this->getExpressionLanguage()->evaluate($callback, [
'object' => $object,
$this->getExpressionVar($object) => $object,
]);
}
return is_string($callback)
? call_user_func([$object, $callback])
: call_user_func($callback, $object);
} | php | {
"resource": ""
} |
q255192 | Indexable.buildCallback | test | private function buildCallback($type, $object)
{
if (!array_key_exists($type, $this->callbacks)) {
return null;
}
$callback = $this->callbacks[$type];
if (is_callable($callback) or is_callable([$object, $callback])) {
return $callback;
}
if (is_string($callback)) {
return $this->buildExpressionCallback($type, $object, $callback);
}
throw new \InvalidArgumentException(sprintf('Callback for type "%s" is not a valid callback.', $type));
} | php | {
"resource": ""
} |
q255193 | Indexable.buildExpressionCallback | test | private function buildExpressionCallback($type, $object, $callback)
{
$expression = $this->getExpressionLanguage();
if (!$expression) {
throw new \RuntimeException('Unable to process an expression without the ExpressionLanguage component.');
}
try {
$callback = new Expression($callback);
$expression->compile($callback, [
'object', $this->getExpressionVar($object),
]);
return $callback;
} catch (SyntaxError $e) {
throw new \InvalidArgumentException(sprintf(
'Callback for type "%s" is an invalid expression',
$type
), $e->getCode(), $e);
}
} | php | {
"resource": ""
} |
q255194 | Indexable.getCallback | test | private function getCallback($type, $object)
{
if (!array_key_exists($type, $this->initialisedCallbacks)) {
$this->initialisedCallbacks[$type] = $this->buildCallback($type, $object);
}
return $this->initialisedCallbacks[$type];
} | php | {
"resource": ""
} |
q255195 | Indexable.getExpressionVar | test | private function getExpressionVar($object = null)
{
if (!is_object($object)) {
return 'object';
}
$ref = new \ReflectionClass($object);
return strtolower($ref->getShortName());
} | php | {
"resource": ""
} |
q255196 | AliasProcessor.setRootName | test | public function setRootName(IndexConfig $indexConfig, Index $index)
{
$index->overrideName(
sprintf('%s_%s',
$indexConfig->getElasticSearchName(),
date('Y-m-d-His')
)
);
} | php | {
"resource": ""
} |
q255197 | AliasProcessor.switchIndexAlias | test | public function switchIndexAlias(IndexConfig $indexConfig, Index $index, $force = false, $delete = true)
{
$client = $index->getClient();
$aliasName = $indexConfig->getElasticSearchName();
$oldIndexName = null;
$newIndexName = $index->getName();
try {
$oldIndexName = $this->getAliasedIndex($client, $aliasName);
} catch (AliasIsIndexException $e) {
if (!$force) {
throw $e;
}
if ($delete) {
$this->deleteIndex($client, $aliasName);
} else {
$this->closeIndex($client, $aliasName);
}
}
try {
$aliasUpdateRequest = $this->buildAliasUpdateRequest($oldIndexName, $aliasName, $newIndexName);
$client->request('_aliases', 'POST', $aliasUpdateRequest);
} catch (ExceptionInterface $e) {
$this->cleanupRenameFailure($client, $newIndexName, $e);
}
// Delete the old index after the alias has been switched
if (null !== $oldIndexName) {
if ($delete) {
$this->deleteIndex($client, $oldIndexName);
} else {
$this->closeIndex($client, $oldIndexName);
}
}
} | php | {
"resource": ""
} |
q255198 | AliasProcessor.buildAliasUpdateRequest | test | private function buildAliasUpdateRequest($aliasedIndex, $aliasName, $newIndexName)
{
$aliasUpdateRequest = ['actions' => []];
if (null !== $aliasedIndex) {
// if the alias is set - add an action to remove it
$aliasUpdateRequest['actions'][] = [
'remove' => ['index' => $aliasedIndex, 'alias' => $aliasName],
];
}
// add an action to point the alias to the new index
$aliasUpdateRequest['actions'][] = [
'add' => ['index' => $newIndexName, 'alias' => $aliasName],
];
return $aliasUpdateRequest;
} | php | {
"resource": ""
} |
q255199 | AliasProcessor.cleanupRenameFailure | test | private function cleanupRenameFailure(Client $client, $indexName, \Exception $renameAliasException)
{
$additionalError = '';
try {
$this->deleteIndex($client, $indexName);
} catch (ExceptionInterface $deleteNewIndexException) {
$additionalError = sprintf(
'Tried to delete newly built index %s, but also failed: %s',
$indexName,
$deleteNewIndexException->getMessage()
);
}
throw new \RuntimeException(sprintf(
'Failed to updated index alias: %s. %s',
$renameAliasException->getMessage(),
$additionalError ?: sprintf('Newly built index %s was deleted', $indexName)
), 0, $renameAliasException);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.