repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
alterphp/EasyAdminExtensionBundle | src/Configuration/EmbeddedListViewConfigPass.php | EmbeddedListViewConfigPass.processSortingConfig | private function processSortingConfig(array $backendConfig)
{
foreach ($backendConfig['entities'] as $entityName => $entityConfig) {
if (
!isset($entityConfig['embeddedList']['sort'])
&& isset($entityConfig['list']['sort'])
) {
$backendConfig['entities'][$entityName]['embeddedList']['sort'] = $entityConfig['list']['sort'];
} elseif (isset($entityConfig['embeddedList']['sort'])) {
$sortConfig = $entityConfig['embeddedList']['sort'];
if (!\is_string($sortConfig) && !\is_array($sortConfig)) {
throw new \InvalidArgumentException(\sprintf('The "sort" option of the "embeddedList" view of the "%s" entity contains an invalid value (it can only be a string or an array).', $entityName));
}
if (\is_string($sortConfig)) {
$sortConfig = ['field' => $sortConfig, 'direction' => 'DESC'];
} else {
$sortConfig = ['field' => $sortConfig[0], 'direction' => \strtoupper($sortConfig[1])];
}
$backendConfig['entities'][$entityName]['embeddedList']['sort'] = $sortConfig;
}
}
return $backendConfig;
} | php | private function processSortingConfig(array $backendConfig)
{
foreach ($backendConfig['entities'] as $entityName => $entityConfig) {
if (
!isset($entityConfig['embeddedList']['sort'])
&& isset($entityConfig['list']['sort'])
) {
$backendConfig['entities'][$entityName]['embeddedList']['sort'] = $entityConfig['list']['sort'];
} elseif (isset($entityConfig['embeddedList']['sort'])) {
$sortConfig = $entityConfig['embeddedList']['sort'];
if (!\is_string($sortConfig) && !\is_array($sortConfig)) {
throw new \InvalidArgumentException(\sprintf('The "sort" option of the "embeddedList" view of the "%s" entity contains an invalid value (it can only be a string or an array).', $entityName));
}
if (\is_string($sortConfig)) {
$sortConfig = ['field' => $sortConfig, 'direction' => 'DESC'];
} else {
$sortConfig = ['field' => $sortConfig[0], 'direction' => \strtoupper($sortConfig[1])];
}
$backendConfig['entities'][$entityName]['embeddedList']['sort'] = $sortConfig;
}
}
return $backendConfig;
} | [
"private",
"function",
"processSortingConfig",
"(",
"array",
"$",
"backendConfig",
")",
"{",
"foreach",
"(",
"$",
"backendConfig",
"[",
"'entities'",
"]",
"as",
"$",
"entityName",
"=>",
"$",
"entityConfig",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"ent... | @param array $backendConfig
@return array | [
"@param",
"array",
"$backendConfig"
] | train | https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Configuration/EmbeddedListViewConfigPass.php#L49-L74 |
alterphp/EasyAdminExtensionBundle | src/Configuration/ShowViewConfigPass.php | ShowViewConfigPass.processCustomShowTypes | private function processCustomShowTypes(array $backendConfig)
{
foreach ($backendConfig['entities'] as $entityName => $entityConfig) {
foreach ($entityConfig['show']['fields'] as $fieldName => $fieldMetadata) {
if (\array_key_exists($fieldMetadata['type'], static::$mapTypeToTemplates)) {
$template = $this->isFieldTemplateDefined($fieldMetadata)
? $fieldMetadata['template']
: static::$mapTypeToTemplates[$fieldMetadata['type']];
$entityConfig['show']['fields'][$fieldName]['template'] = $template;
$entityConfig['show']['fields'][$fieldName]['template_options'] = $this->processTemplateOptions(
$fieldMetadata['type'], $fieldMetadata
);
}
}
$backendConfig['entities'][$entityName] = $entityConfig;
}
return $backendConfig;
} | php | private function processCustomShowTypes(array $backendConfig)
{
foreach ($backendConfig['entities'] as $entityName => $entityConfig) {
foreach ($entityConfig['show']['fields'] as $fieldName => $fieldMetadata) {
if (\array_key_exists($fieldMetadata['type'], static::$mapTypeToTemplates)) {
$template = $this->isFieldTemplateDefined($fieldMetadata)
? $fieldMetadata['template']
: static::$mapTypeToTemplates[$fieldMetadata['type']];
$entityConfig['show']['fields'][$fieldName]['template'] = $template;
$entityConfig['show']['fields'][$fieldName]['template_options'] = $this->processTemplateOptions(
$fieldMetadata['type'], $fieldMetadata
);
}
}
$backendConfig['entities'][$entityName] = $entityConfig;
}
return $backendConfig;
} | [
"private",
"function",
"processCustomShowTypes",
"(",
"array",
"$",
"backendConfig",
")",
"{",
"foreach",
"(",
"$",
"backendConfig",
"[",
"'entities'",
"]",
"as",
"$",
"entityName",
"=>",
"$",
"entityConfig",
")",
"{",
"foreach",
"(",
"$",
"entityConfig",
"[",... | Process custom types for SHOW view.
@param array $backendConfig
@return array | [
"Process",
"custom",
"types",
"for",
"SHOW",
"view",
"."
] | train | https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Configuration/ShowViewConfigPass.php#L50-L70 |
alterphp/EasyAdminExtensionBundle | src/Configuration/ListFormFiltersConfigPass.php | ListFormFiltersConfigPass.process | public function process(array $backendConfig): array
{
if (!isset($backendConfig['entities'])) {
return $backendConfig;
}
foreach ($backendConfig['entities'] as $entityName => $entityConfig) {
if (!isset($entityConfig['list']['form_filters'])) {
continue;
}
$formFilters = [];
foreach ($entityConfig['list']['form_filters'] as $i => $formFilter) {
// Detects invalid config node
if (!\is_string($formFilter) && !\is_array($formFilter)) {
throw new \RuntimeException(
\sprintf(
'The values of the "form_filters" option for the list view of the "%s" entity can only be strings or arrays.',
$entityConfig['class']
)
);
}
// Key mapping
if (\is_string($formFilter)) {
$filterConfig = ['property' => $formFilter];
} else {
if (!\array_key_exists('property', $formFilter)) {
throw new \RuntimeException(
\sprintf(
'One of the values of the "form_filters" option for the "list" view of the "%s" entity does not define the mandatory option "property".',
$entityConfig['class']
)
);
}
$filterConfig = $formFilter;
}
// Auto set name with property value
$filterConfig['name'] = $filterConfig['name'] ?? $filterConfig['property'];
// Auto set label with name value
$filterConfig['label'] = $filterConfig['label'] ?? $filterConfig['name'];
// Auto-set translation_domain
$filterConfig['translation_domain'] = $filterConfig['translation_domain'] ?? $entityConfig['translation_domain'];
$this->configureFilter($entityConfig['class'], $filterConfig);
// If type is not configured at this steps => not guessable
if (!isset($filterConfig['type'])) {
continue;
}
$formFilters[$filterConfig['name']] = $filterConfig;
}
// set form filters config and form !
$backendConfig['entities'][$entityName]['list']['form_filters'] = $formFilters;
}
return $backendConfig;
} | php | public function process(array $backendConfig): array
{
if (!isset($backendConfig['entities'])) {
return $backendConfig;
}
foreach ($backendConfig['entities'] as $entityName => $entityConfig) {
if (!isset($entityConfig['list']['form_filters'])) {
continue;
}
$formFilters = [];
foreach ($entityConfig['list']['form_filters'] as $i => $formFilter) {
// Detects invalid config node
if (!\is_string($formFilter) && !\is_array($formFilter)) {
throw new \RuntimeException(
\sprintf(
'The values of the "form_filters" option for the list view of the "%s" entity can only be strings or arrays.',
$entityConfig['class']
)
);
}
// Key mapping
if (\is_string($formFilter)) {
$filterConfig = ['property' => $formFilter];
} else {
if (!\array_key_exists('property', $formFilter)) {
throw new \RuntimeException(
\sprintf(
'One of the values of the "form_filters" option for the "list" view of the "%s" entity does not define the mandatory option "property".',
$entityConfig['class']
)
);
}
$filterConfig = $formFilter;
}
// Auto set name with property value
$filterConfig['name'] = $filterConfig['name'] ?? $filterConfig['property'];
// Auto set label with name value
$filterConfig['label'] = $filterConfig['label'] ?? $filterConfig['name'];
// Auto-set translation_domain
$filterConfig['translation_domain'] = $filterConfig['translation_domain'] ?? $entityConfig['translation_domain'];
$this->configureFilter($entityConfig['class'], $filterConfig);
// If type is not configured at this steps => not guessable
if (!isset($filterConfig['type'])) {
continue;
}
$formFilters[$filterConfig['name']] = $filterConfig;
}
// set form filters config and form !
$backendConfig['entities'][$entityName]['list']['form_filters'] = $formFilters;
}
return $backendConfig;
} | [
"public",
"function",
"process",
"(",
"array",
"$",
"backendConfig",
")",
":",
"array",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"backendConfig",
"[",
"'entities'",
"]",
")",
")",
"{",
"return",
"$",
"backendConfig",
";",
"}",
"foreach",
"(",
"$",
"back... | @param array $backendConfig
@return array | [
"@param",
"array",
"$backendConfig"
] | train | https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Configuration/ListFormFiltersConfigPass.php#L33-L95 |
alterphp/EasyAdminExtensionBundle | src/Model/ListFilter.php | ListFilter.getOperatorsList | public static function getOperatorsList()
{
// Build $operatorValues if this is the first call
if (null === static::$operatorValues) {
static::$operatorValues = [];
$refClass = new \ReflectionClass(static::class);
$classConstants = $refClass->getConstants();
$className = $refClass->getShortName();
$constantPrefix = 'OPERATOR_';
foreach ($classConstants as $key => $val) {
if (\substr($key, 0, \strlen($constantPrefix)) === $constantPrefix) {
static::$operatorValues[] = $val;
}
}
}
return static::$operatorValues;
} | php | public static function getOperatorsList()
{
// Build $operatorValues if this is the first call
if (null === static::$operatorValues) {
static::$operatorValues = [];
$refClass = new \ReflectionClass(static::class);
$classConstants = $refClass->getConstants();
$className = $refClass->getShortName();
$constantPrefix = 'OPERATOR_';
foreach ($classConstants as $key => $val) {
if (\substr($key, 0, \strlen($constantPrefix)) === $constantPrefix) {
static::$operatorValues[] = $val;
}
}
}
return static::$operatorValues;
} | [
"public",
"static",
"function",
"getOperatorsList",
"(",
")",
"{",
"// Build $operatorValues if this is the first call",
"if",
"(",
"null",
"===",
"static",
"::",
"$",
"operatorValues",
")",
"{",
"static",
"::",
"$",
"operatorValues",
"=",
"[",
"]",
";",
"$",
"r... | Returns operators list.
@return array | [
"Returns",
"operators",
"list",
"."
] | train | https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Model/ListFilter.php#L50-L68 |
alterphp/EasyAdminExtensionBundle | src/Form/Type/EasyAdminEmbeddedListType.php | EasyAdminEmbeddedListType.buildView | public function buildView(FormView $view, FormInterface $form, array $options)
{
$parentData = $form->getParent()->getData();
$embeddedListEntity = $options['entity'];
$embeddedListFilters = $options['filters'];
// Guess entity FQCN from parent metadata
$entityFqcn = $this->embeddedListHelper->getEntityFqcnFromParent(\get_class($parentData), $form->getName());
if (null !== $entityFqcn) {
$view->vars['entity_fqcn'] = $entityFqcn;
// Guess embeddedList entity if not set
if (null === $embeddedListEntity) {
$embeddedListEntity = $this->embeddedListHelper->guessEntityEntry($entityFqcn);
}
}
$view->vars['entity'] = $embeddedListEntity;
$view->vars['parent_entity_property'] = $form->getConfig()->getName();
// Only for backward compatibility (when there were no guesser)
$propertyAccessor = PropertyAccess::createPropertyAccessor();
$filters = \array_map(function ($filter) use ($propertyAccessor, $form) {
if (0 === \strpos($filter, 'form:')) {
$filter = $propertyAccessor->getValue($form, \substr($filter, 5));
}
return $filter;
}, $embeddedListFilters);
$view->vars['filters'] = $filters;
if ($options['sort']) {
$sort['field'] = $options['sort'][0];
$sort['direction'] = $options['sort'][1] ?? 'DESC';
$view->vars['sort'] = $sort;
}
} | php | public function buildView(FormView $view, FormInterface $form, array $options)
{
$parentData = $form->getParent()->getData();
$embeddedListEntity = $options['entity'];
$embeddedListFilters = $options['filters'];
// Guess entity FQCN from parent metadata
$entityFqcn = $this->embeddedListHelper->getEntityFqcnFromParent(\get_class($parentData), $form->getName());
if (null !== $entityFqcn) {
$view->vars['entity_fqcn'] = $entityFqcn;
// Guess embeddedList entity if not set
if (null === $embeddedListEntity) {
$embeddedListEntity = $this->embeddedListHelper->guessEntityEntry($entityFqcn);
}
}
$view->vars['entity'] = $embeddedListEntity;
$view->vars['parent_entity_property'] = $form->getConfig()->getName();
// Only for backward compatibility (when there were no guesser)
$propertyAccessor = PropertyAccess::createPropertyAccessor();
$filters = \array_map(function ($filter) use ($propertyAccessor, $form) {
if (0 === \strpos($filter, 'form:')) {
$filter = $propertyAccessor->getValue($form, \substr($filter, 5));
}
return $filter;
}, $embeddedListFilters);
$view->vars['filters'] = $filters;
if ($options['sort']) {
$sort['field'] = $options['sort'][0];
$sort['direction'] = $options['sort'][1] ?? 'DESC';
$view->vars['sort'] = $sort;
}
} | [
"public",
"function",
"buildView",
"(",
"FormView",
"$",
"view",
",",
"FormInterface",
"$",
"form",
",",
"array",
"$",
"options",
")",
"{",
"$",
"parentData",
"=",
"$",
"form",
"->",
"getParent",
"(",
")",
"->",
"getData",
"(",
")",
";",
"$",
"embedded... | {@inheritdoc} | [
"{"
] | train | https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Form/Type/EasyAdminEmbeddedListType.php#L39-L76 |
alterphp/EasyAdminExtensionBundle | src/Form/Type/EasyAdminEmbeddedListType.php | EasyAdminEmbeddedListType.configureOptions | public function configureOptions(OptionsResolver $resolver)
{
$resolver
->setDefault('entity', null)
->setDefault('filters', [])
->setDefault('sort', null)
->setAllowedTypes('entity', ['null', 'string'])
->setAllowedTypes('filters', ['array'])
->setAllowedTypes('sort', ['null', 'string', 'array'])
;
} | php | public function configureOptions(OptionsResolver $resolver)
{
$resolver
->setDefault('entity', null)
->setDefault('filters', [])
->setDefault('sort', null)
->setAllowedTypes('entity', ['null', 'string'])
->setAllowedTypes('filters', ['array'])
->setAllowedTypes('sort', ['null', 'string', 'array'])
;
} | [
"public",
"function",
"configureOptions",
"(",
"OptionsResolver",
"$",
"resolver",
")",
"{",
"$",
"resolver",
"->",
"setDefault",
"(",
"'entity'",
",",
"null",
")",
"->",
"setDefault",
"(",
"'filters'",
",",
"[",
"]",
")",
"->",
"setDefault",
"(",
"'sort'",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Form/Type/EasyAdminEmbeddedListType.php#L81-L91 |
alterphp/EasyAdminExtensionBundle | src/Configuration/ExcludeFieldsConfigPass.php | ExcludeFieldsConfigPass.process | public function process(array $backendConfig): array
{
if (!isset($backendConfig['entities'])) {
return $backendConfig;
}
foreach ($backendConfig['entities'] as $entityName => $entityConfig) {
foreach (['form', 'edit', 'new'] as $section) {
if (!isset($entityConfig[$section]['exclude_fields'])) {
continue;
}
$this->ensureFieldConfigurationIsValid($entityConfig, $entityName, $section);
$propertyNames = $this->getPropertyNamesForEntity($entityConfig, $entityName);
// filter fields to be displayed
$fields = [];
foreach ($propertyNames as $propertyName) {
if ($this->shouldSkipField($propertyName, $entityConfig[$section]['exclude_fields'])) {
continue;
}
$fields[] = $propertyName;
}
// set it!
$backendConfig['entities'][$entityName][$section]['fields'] = $fields;
}
}
return $backendConfig;
} | php | public function process(array $backendConfig): array
{
if (!isset($backendConfig['entities'])) {
return $backendConfig;
}
foreach ($backendConfig['entities'] as $entityName => $entityConfig) {
foreach (['form', 'edit', 'new'] as $section) {
if (!isset($entityConfig[$section]['exclude_fields'])) {
continue;
}
$this->ensureFieldConfigurationIsValid($entityConfig, $entityName, $section);
$propertyNames = $this->getPropertyNamesForEntity($entityConfig, $entityName);
// filter fields to be displayed
$fields = [];
foreach ($propertyNames as $propertyName) {
if ($this->shouldSkipField($propertyName, $entityConfig[$section]['exclude_fields'])) {
continue;
}
$fields[] = $propertyName;
}
// set it!
$backendConfig['entities'][$entityName][$section]['fields'] = $fields;
}
}
return $backendConfig;
} | [
"public",
"function",
"process",
"(",
"array",
"$",
"backendConfig",
")",
":",
"array",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"backendConfig",
"[",
"'entities'",
"]",
")",
")",
"{",
"return",
"$",
"backendConfig",
";",
"}",
"foreach",
"(",
"$",
"back... | @param mixed[] $backendConfig
@return mixed[]
@throws ConflictingConfigurationException
@throws \ReflectionException | [
"@param",
"mixed",
"[]",
"$backendConfig"
] | train | https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Configuration/ExcludeFieldsConfigPass.php#L30-L62 |
alterphp/EasyAdminExtensionBundle | src/Configuration/ExcludeFieldsConfigPass.php | ExcludeFieldsConfigPass.shouldSkipField | private function shouldSkipField(string $propertyName, array $excludedFields): bool
{
if ('id' === $propertyName) {
return true;
}
return \in_array($propertyName, $excludedFields, true);
} | php | private function shouldSkipField(string $propertyName, array $excludedFields): bool
{
if ('id' === $propertyName) {
return true;
}
return \in_array($propertyName, $excludedFields, true);
} | [
"private",
"function",
"shouldSkipField",
"(",
"string",
"$",
"propertyName",
",",
"array",
"$",
"excludedFields",
")",
":",
"bool",
"{",
"if",
"(",
"'id'",
"===",
"$",
"propertyName",
")",
"{",
"return",
"true",
";",
"}",
"return",
"\\",
"in_array",
"(",
... | @param string $propertyName
@param string[] $excludedFields
@return bool | [
"@param",
"string",
"$propertyName",
"@param",
"string",
"[]",
"$excludedFields"
] | train | https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Configuration/ExcludeFieldsConfigPass.php#L70-L77 |
alterphp/EasyAdminExtensionBundle | src/Configuration/ExcludeFieldsConfigPass.php | ExcludeFieldsConfigPass.ensureFieldConfigurationIsValid | private function ensureFieldConfigurationIsValid(array $entityConfig, string $entityName, string $section)
{
if (!isset($entityConfig[$section]['fields']) || !\count($entityConfig[$section]['fields'])) {
return;
}
throw new ConflictingConfigurationException(\sprintf(
'"%s" and "%s" are mutually conflicting. Pick just one of them in %s YAML configuration',
'exclude_fields',
'fields',
\sprintf('easy_admin > entities > %s > %s', $entityName, $section)
));
} | php | private function ensureFieldConfigurationIsValid(array $entityConfig, string $entityName, string $section)
{
if (!isset($entityConfig[$section]['fields']) || !\count($entityConfig[$section]['fields'])) {
return;
}
throw new ConflictingConfigurationException(\sprintf(
'"%s" and "%s" are mutually conflicting. Pick just one of them in %s YAML configuration',
'exclude_fields',
'fields',
\sprintf('easy_admin > entities > %s > %s', $entityName, $section)
));
} | [
"private",
"function",
"ensureFieldConfigurationIsValid",
"(",
"array",
"$",
"entityConfig",
",",
"string",
"$",
"entityName",
",",
"string",
"$",
"section",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"entityConfig",
"[",
"$",
"section",
"]",
"[",
"'fields... | Explicit "fields" option and "exclude_fields" won't work together
@param mixed[] $entityConfig
@param string $entityName
@param string $section
@throws ConflictingConfigurationException | [
"Explicit",
"fields",
"option",
"and",
"exclude_fields",
"won",
"t",
"work",
"together"
] | train | https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Configuration/ExcludeFieldsConfigPass.php#L88-L100 |
alterphp/EasyAdminExtensionBundle | src/Configuration/ExcludeFieldsConfigPass.php | ExcludeFieldsConfigPass.getPropertyNamesForEntity | private function getPropertyNamesForEntity(array $entityConfig, string $entityName): array
{
$entityClass = $entityConfig['class'] ?: $entityName;
$entityReflectionClass = new ReflectionClass($entityClass);
return \array_map(function (ReflectionProperty $reflectionProperty) {
return $reflectionProperty->getName();
}, $entityReflectionClass->getProperties());
} | php | private function getPropertyNamesForEntity(array $entityConfig, string $entityName): array
{
$entityClass = $entityConfig['class'] ?: $entityName;
$entityReflectionClass = new ReflectionClass($entityClass);
return \array_map(function (ReflectionProperty $reflectionProperty) {
return $reflectionProperty->getName();
}, $entityReflectionClass->getProperties());
} | [
"private",
"function",
"getPropertyNamesForEntity",
"(",
"array",
"$",
"entityConfig",
",",
"string",
"$",
"entityName",
")",
":",
"array",
"{",
"$",
"entityClass",
"=",
"$",
"entityConfig",
"[",
"'class'",
"]",
"?",
":",
"$",
"entityName",
";",
"$",
"entity... | @param mixed[] $entityConfig
@param string $entityName
@return string[]
@throws \ReflectionException | [
"@param",
"mixed",
"[]",
"$entityConfig",
"@param",
"string",
"$entityName"
] | train | https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Configuration/ExcludeFieldsConfigPass.php#L110-L118 |
alterphp/EasyAdminExtensionBundle | src/Controller/EasyAdminController.php | EasyAdminController.isActionAllowed | protected function isActionAllowed($actionName)
{
switch ($actionName) {
// autocomplete action is mapped to list action for access permissions
case 'autocomplete':
// embeddedList action is mapped to list action for access permissions
case 'embeddedList':
$actionName = 'list';
break;
// newAjax action is mapped to new action for access permissions
case 'newAjax':
$actionName = 'new';
break;
default:
break;
}
// Get item for edit/show or custom actions => security voters may apply
$easyadmin = $this->request->attributes->get('easyadmin');
$subject = $easyadmin['item'] ?? null;
$this->get(AdminAuthorizationChecker::class)->checksUserAccess($this->entity, $actionName, $subject);
return parent::isActionAllowed($actionName);
} | php | protected function isActionAllowed($actionName)
{
switch ($actionName) {
// autocomplete action is mapped to list action for access permissions
case 'autocomplete':
// embeddedList action is mapped to list action for access permissions
case 'embeddedList':
$actionName = 'list';
break;
// newAjax action is mapped to new action for access permissions
case 'newAjax':
$actionName = 'new';
break;
default:
break;
}
// Get item for edit/show or custom actions => security voters may apply
$easyadmin = $this->request->attributes->get('easyadmin');
$subject = $easyadmin['item'] ?? null;
$this->get(AdminAuthorizationChecker::class)->checksUserAccess($this->entity, $actionName, $subject);
return parent::isActionAllowed($actionName);
} | [
"protected",
"function",
"isActionAllowed",
"(",
"$",
"actionName",
")",
"{",
"switch",
"(",
"$",
"actionName",
")",
"{",
"// autocomplete action is mapped to list action for access permissions",
"case",
"'autocomplete'",
":",
"// embeddedList action is mapped to list action for ... | {@inheritdoc}
@throws \Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException | [
"{",
"@inheritdoc",
"}"
] | train | https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Controller/EasyAdminController.php#L48-L71 |
alterphp/EasyAdminExtensionBundle | src/Controller/EasyAdminController.php | EasyAdminController.newAjaxAction | protected function newAjaxAction()
{
$this->dispatch(EasyAdminEvents::PRE_NEW);
$entity = $this->executeDynamicMethod('createNew<EntityName>Entity');
$easyadmin = \array_merge($this->request->attributes->get('easyadmin'), ['item' => $entity]);
$this->request->attributes->set('easyadmin', $easyadmin);
$fields = $this->entity['new']['fields'];
$newForm = $this->executeDynamicMethod('create<EntityName>NewForm', [$entity, $fields]);
$newForm->handleRequest($this->request);
if ($newForm->isSubmitted() && $newForm->isValid()) {
$this->dispatch(EasyAdminEvents::PRE_PERSIST, ['entity' => $entity]);
$this->executeDynamicMethod('persist<EntityName>Entity', [$entity]);
$this->dispatch(EasyAdminEvents::POST_PERSIST, ['entity' => $entity]);
return new JsonResponse(['option' => ['id' => $entity->getId(), 'text' => (string) $entity]]);
}
$this->dispatch(EasyAdminEvents::POST_NEW, ['entity_fields' => $fields, 'form' => $newForm, 'entity' => $entity]);
$parameters = ['form' => $newForm->createView(), 'entity_fields' => $fields, 'entity' => $entity];
$templatePath = '@EasyAdminExtension/default/new_ajax.html.twig';
if (isset($this->entity['templates']['new_ajax'])) {
$templatePath = $this->entity['templates']['new_ajax'];
}
return new JsonResponse(['html' => $this->renderView($templatePath, $parameters)]);
} | php | protected function newAjaxAction()
{
$this->dispatch(EasyAdminEvents::PRE_NEW);
$entity = $this->executeDynamicMethod('createNew<EntityName>Entity');
$easyadmin = \array_merge($this->request->attributes->get('easyadmin'), ['item' => $entity]);
$this->request->attributes->set('easyadmin', $easyadmin);
$fields = $this->entity['new']['fields'];
$newForm = $this->executeDynamicMethod('create<EntityName>NewForm', [$entity, $fields]);
$newForm->handleRequest($this->request);
if ($newForm->isSubmitted() && $newForm->isValid()) {
$this->dispatch(EasyAdminEvents::PRE_PERSIST, ['entity' => $entity]);
$this->executeDynamicMethod('persist<EntityName>Entity', [$entity]);
$this->dispatch(EasyAdminEvents::POST_PERSIST, ['entity' => $entity]);
return new JsonResponse(['option' => ['id' => $entity->getId(), 'text' => (string) $entity]]);
}
$this->dispatch(EasyAdminEvents::POST_NEW, ['entity_fields' => $fields, 'form' => $newForm, 'entity' => $entity]);
$parameters = ['form' => $newForm->createView(), 'entity_fields' => $fields, 'entity' => $entity];
$templatePath = '@EasyAdminExtension/default/new_ajax.html.twig';
if (isset($this->entity['templates']['new_ajax'])) {
$templatePath = $this->entity['templates']['new_ajax'];
}
return new JsonResponse(['html' => $this->renderView($templatePath, $parameters)]);
} | [
"protected",
"function",
"newAjaxAction",
"(",
")",
"{",
"$",
"this",
"->",
"dispatch",
"(",
"EasyAdminEvents",
"::",
"PRE_NEW",
")",
";",
"$",
"entity",
"=",
"$",
"this",
"->",
"executeDynamicMethod",
"(",
"'createNew<EntityName>Entity'",
")",
";",
"$",
"easy... | The method that is executed when the user performs a 'new ajax' action on an entity.
@return JsonResponse | [
"The",
"method",
"that",
"is",
"executed",
"when",
"the",
"user",
"performs",
"a",
"new",
"ajax",
"action",
"on",
"an",
"entity",
"."
] | train | https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Controller/EasyAdminController.php#L78-L106 |
alterphp/EasyAdminExtensionBundle | src/Helper/EmbeddedListHelper.php | EmbeddedListHelper.getEntityFqcnFromParent | public function getEntityFqcnFromParent(string $parentFqcn, string $parentProperty)
{
$parentClassMetadata = $this->doctrine->getManagerForClass($parentFqcn)->getClassMetadata($parentFqcn);
// Required to use getAssociationMappings method
if (!$parentClassMetadata instanceof ClassMetadataInfo) {
return;
}
try {
$entityFqcn = $parentClassMetadata->getAssociationTargetClass($parentProperty);
} catch (\Exception $e) {
return;
}
return $entityFqcn;
} | php | public function getEntityFqcnFromParent(string $parentFqcn, string $parentProperty)
{
$parentClassMetadata = $this->doctrine->getManagerForClass($parentFqcn)->getClassMetadata($parentFqcn);
// Required to use getAssociationMappings method
if (!$parentClassMetadata instanceof ClassMetadataInfo) {
return;
}
try {
$entityFqcn = $parentClassMetadata->getAssociationTargetClass($parentProperty);
} catch (\Exception $e) {
return;
}
return $entityFqcn;
} | [
"public",
"function",
"getEntityFqcnFromParent",
"(",
"string",
"$",
"parentFqcn",
",",
"string",
"$",
"parentProperty",
")",
"{",
"$",
"parentClassMetadata",
"=",
"$",
"this",
"->",
"doctrine",
"->",
"getManagerForClass",
"(",
"$",
"parentFqcn",
")",
"->",
"get... | Returns EasyAdmin entity entry name for a parent FQCN and property for embedded list.
@param string $parentFqcn
@param string $parentProperty
@return mixed
@throws \RuntimeException | [
"Returns",
"EasyAdmin",
"entity",
"entry",
"name",
"for",
"a",
"parent",
"FQCN",
"and",
"property",
"for",
"embedded",
"list",
"."
] | train | https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Helper/EmbeddedListHelper.php#L46-L62 |
alterphp/EasyAdminExtensionBundle | src/Helper/EmbeddedListHelper.php | EmbeddedListHelper.guessEntityEntry | public function guessEntityEntry(string $entityFqcn)
{
$matchingEntityConfigs = \array_filter(
$this->easyAdminConfig['entities'],
function ($entityConfig) use ($entityFqcn) {
return $entityFqcn === $entityConfig['class'];
}
);
if (empty($matchingEntityConfigs)) {
throw new \RuntimeException(
\sprintf('No entity defined in EasyAdmin configuration matches %s FQCN.', $entityFqcn)
);
}
if (1 < \count($matchingEntityConfigs)) {
throw new \RuntimeException(
\sprintf('More than 1 entity defined in EasyAdmin configuration matches %s FQCN.', $entityFqcn)
);
}
return (string) \key($matchingEntityConfigs);
} | php | public function guessEntityEntry(string $entityFqcn)
{
$matchingEntityConfigs = \array_filter(
$this->easyAdminConfig['entities'],
function ($entityConfig) use ($entityFqcn) {
return $entityFqcn === $entityConfig['class'];
}
);
if (empty($matchingEntityConfigs)) {
throw new \RuntimeException(
\sprintf('No entity defined in EasyAdmin configuration matches %s FQCN.', $entityFqcn)
);
}
if (1 < \count($matchingEntityConfigs)) {
throw new \RuntimeException(
\sprintf('More than 1 entity defined in EasyAdmin configuration matches %s FQCN.', $entityFqcn)
);
}
return (string) \key($matchingEntityConfigs);
} | [
"public",
"function",
"guessEntityEntry",
"(",
"string",
"$",
"entityFqcn",
")",
"{",
"$",
"matchingEntityConfigs",
"=",
"\\",
"array_filter",
"(",
"$",
"this",
"->",
"easyAdminConfig",
"[",
"'entities'",
"]",
",",
"function",
"(",
"$",
"entityConfig",
")",
"u... | Returns EasyAdmin entity entry name for a FQCN.
@param string $entityFqcn
@return string
@throws \RuntimeException | [
"Returns",
"EasyAdmin",
"entity",
"entry",
"name",
"for",
"a",
"FQCN",
"."
] | train | https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Helper/EmbeddedListHelper.php#L73-L95 |
alterphp/EasyAdminExtensionBundle | src/Helper/EmbeddedListHelper.php | EmbeddedListHelper.guessDefaultFilter | public function guessDefaultFilter(string $entityFqcn, string $parentEntityProperty, $parentEntity)
{
$entityClassMetadata = $this->doctrine->getManagerForClass($entityFqcn)->getClassMetadata($entityFqcn);
// Required to use getAssociationMappings method
if (!$entityClassMetadata instanceof ClassMetadataInfo) {
return [];
}
$entityAssociations = $entityClassMetadata->getAssociationMappings();
$parentEntityFqcn = \get_class($parentEntity);
foreach ($entityAssociations as $assoc) {
// If association matches embeddedList relation
if ($parentEntityFqcn === $assoc['targetEntity'] && $parentEntityProperty === $assoc['inversedBy']) {
// OneToMany association
if (isset($assoc['joinColumns']) && 1 === \count($assoc['joinColumns'])) {
$assocFieldPart = 'entity.'.$assoc['fieldName'];
$assocIdentifierValue = PropertyAccess::createPropertyAccessor()->getValue(
$parentEntity, $assoc['joinColumns'][0]['referencedColumnName']
);
return [$assocFieldPart => $assocIdentifierValue];
}
// ManyToMany association
elseif (isset($assoc['joinTable'])) {
$relatedItems = PropertyAccess::createPropertyAccessor()->getValue(
$parentEntity, $parentEntityProperty
);
$itemIds = $relatedItems->map(function ($entity) {
return $entity->getId();
});
return ['entity.id' => $itemIds->toArray()];
}
}
}
return [];
} | php | public function guessDefaultFilter(string $entityFqcn, string $parentEntityProperty, $parentEntity)
{
$entityClassMetadata = $this->doctrine->getManagerForClass($entityFqcn)->getClassMetadata($entityFqcn);
// Required to use getAssociationMappings method
if (!$entityClassMetadata instanceof ClassMetadataInfo) {
return [];
}
$entityAssociations = $entityClassMetadata->getAssociationMappings();
$parentEntityFqcn = \get_class($parentEntity);
foreach ($entityAssociations as $assoc) {
// If association matches embeddedList relation
if ($parentEntityFqcn === $assoc['targetEntity'] && $parentEntityProperty === $assoc['inversedBy']) {
// OneToMany association
if (isset($assoc['joinColumns']) && 1 === \count($assoc['joinColumns'])) {
$assocFieldPart = 'entity.'.$assoc['fieldName'];
$assocIdentifierValue = PropertyAccess::createPropertyAccessor()->getValue(
$parentEntity, $assoc['joinColumns'][0]['referencedColumnName']
);
return [$assocFieldPart => $assocIdentifierValue];
}
// ManyToMany association
elseif (isset($assoc['joinTable'])) {
$relatedItems = PropertyAccess::createPropertyAccessor()->getValue(
$parentEntity, $parentEntityProperty
);
$itemIds = $relatedItems->map(function ($entity) {
return $entity->getId();
});
return ['entity.id' => $itemIds->toArray()];
}
}
}
return [];
} | [
"public",
"function",
"guessDefaultFilter",
"(",
"string",
"$",
"entityFqcn",
",",
"string",
"$",
"parentEntityProperty",
",",
"$",
"parentEntity",
")",
"{",
"$",
"entityClassMetadata",
"=",
"$",
"this",
"->",
"doctrine",
"->",
"getManagerForClass",
"(",
"$",
"e... | Returns default filter for embeddedList.
@param string $entityFqcn
@param string $parentEntityProperty
@param object $parentEntity
@return array | [
"Returns",
"default",
"filter",
"for",
"embeddedList",
"."
] | train | https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Helper/EmbeddedListHelper.php#L106-L144 |
alterphp/EasyAdminExtensionBundle | src/Form/Type/Configurator/UnauthorizedFieldConfigurator.php | UnauthorizedFieldConfigurator.configure | public function configure($name, array $options, array $metadata, FormConfigInterface $parentConfig)
{
if (!$this->authorizationChecker->isGranted($metadata['role'])) {
$options['disabled'] = true;
}
return $options;
} | php | public function configure($name, array $options, array $metadata, FormConfigInterface $parentConfig)
{
if (!$this->authorizationChecker->isGranted($metadata['role'])) {
$options['disabled'] = true;
}
return $options;
} | [
"public",
"function",
"configure",
"(",
"$",
"name",
",",
"array",
"$",
"options",
",",
"array",
"$",
"metadata",
",",
"FormConfigInterface",
"$",
"parentConfig",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"authorizationChecker",
"->",
"isGranted",
"(",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/Form/Type/Configurator/UnauthorizedFieldConfigurator.php#L27-L34 |
alterphp/EasyAdminExtensionBundle | src/EasyAdminExtensionBundle.php | EasyAdminExtensionBundle.addRegisterMappingsPass | private function addRegisterMappingsPass(ContainerBuilder $container)
{
$easyAdminExtensionBundleRefl = new \ReflectionClass($this);
if ($easyAdminExtensionBundleRefl->isUserDefined()) {
$easyAdminExtensionBundlePath = \dirname((string) $easyAdminExtensionBundleRefl->getFileName());
$easyAdminExtensionDoctrineMapping = $easyAdminExtensionBundlePath.'/Resources/config/doctrine-mapping';
$mappings = [
\realpath($easyAdminExtensionDoctrineMapping) => 'AlterPHP\EasyAdminExtensionBundle\Model',
];
if (\class_exists(DoctrineOrmMappingsPass::class)) {
$container->addCompilerPass(DoctrineOrmMappingsPass::createXmlMappingDriver($mappings));
}
}
} | php | private function addRegisterMappingsPass(ContainerBuilder $container)
{
$easyAdminExtensionBundleRefl = new \ReflectionClass($this);
if ($easyAdminExtensionBundleRefl->isUserDefined()) {
$easyAdminExtensionBundlePath = \dirname((string) $easyAdminExtensionBundleRefl->getFileName());
$easyAdminExtensionDoctrineMapping = $easyAdminExtensionBundlePath.'/Resources/config/doctrine-mapping';
$mappings = [
\realpath($easyAdminExtensionDoctrineMapping) => 'AlterPHP\EasyAdminExtensionBundle\Model',
];
if (\class_exists(DoctrineOrmMappingsPass::class)) {
$container->addCompilerPass(DoctrineOrmMappingsPass::createXmlMappingDriver($mappings));
}
}
} | [
"private",
"function",
"addRegisterMappingsPass",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"easyAdminExtensionBundleRefl",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"this",
")",
";",
"if",
"(",
"$",
"easyAdminExtensionBundleRefl",
"->",
"isUser... | Register storage mapping for model-based persisted objects from EasyAdminExtension.
Much inspired from FOSUserBundle implementation.
@see https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/FOSUserBundle.php
@param ContainerBuilder $container
@throws \ReflectionException | [
"Register",
"storage",
"mapping",
"for",
"model",
"-",
"based",
"persisted",
"objects",
"from",
"EasyAdminExtension",
".",
"Much",
"inspired",
"from",
"FOSUserBundle",
"implementation",
"."
] | train | https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/EasyAdminExtensionBundle.php#L28-L43 |
alterphp/EasyAdminExtensionBundle | src/DependencyInjection/Configuration.php | Configuration.getConfigTreeBuilder | public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('easy_admin_extension');
$rootNode
->children()
->arrayNode('custom_form_types')
->useAttributeAsKey('short_name')
->prototype('scalar')
->validate()
->ifTrue(function ($v) {
return !\class_exists($v);
})
->thenInvalid('Class %s for custom type does not exist !')
->end()
->end()
->end()
->scalarNode('minimum_role')
->defaultNull()
->end()
->arrayNode('embedded_list')
->addDefaultsIfNotSet()
->children()
->booleanNode('open_new_tab')
->defaultTrue()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
} | php | public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('easy_admin_extension');
$rootNode
->children()
->arrayNode('custom_form_types')
->useAttributeAsKey('short_name')
->prototype('scalar')
->validate()
->ifTrue(function ($v) {
return !\class_exists($v);
})
->thenInvalid('Class %s for custom type does not exist !')
->end()
->end()
->end()
->scalarNode('minimum_role')
->defaultNull()
->end()
->arrayNode('embedded_list')
->addDefaultsIfNotSet()
->children()
->booleanNode('open_new_tab')
->defaultTrue()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
} | [
"public",
"function",
"getConfigTreeBuilder",
"(",
")",
"{",
"$",
"treeBuilder",
"=",
"new",
"TreeBuilder",
"(",
")",
";",
"$",
"rootNode",
"=",
"$",
"treeBuilder",
"->",
"root",
"(",
"'easy_admin_extension'",
")",
";",
"$",
"rootNode",
"->",
"children",
"("... | {@inheritdoc} | [
"{"
] | train | https://github.com/alterphp/EasyAdminExtensionBundle/blob/c9e8cc3530ba053ae22edde8ca3d14d1984936b3/src/DependencyInjection/Configuration.php#L18-L51 |
sensiolabs/SensioDistributionBundle | Composer/ScriptHandler.php | ScriptHandler.defineDirectoryStructure | public static function defineDirectoryStructure(Event $event)
{
$options = static::getOptions($event);
if (!getenv('SENSIOLABS_ENABLE_NEW_DIRECTORY_STRUCTURE') || !$event->getIO()->askConfirmation('Would you like to use Symfony 3 directory structure? [y/N] ', false)) {
return;
}
$rootDir = getcwd();
$appDir = $options['symfony-app-dir'];
$webDir = $options['symfony-web-dir'];
$binDir = static::$options['symfony-bin-dir'] = 'bin';
$varDir = static::$options['symfony-var-dir'] = 'var';
static::updateDirectoryStructure($event, $rootDir, $appDir, $binDir, $varDir, $webDir);
} | php | public static function defineDirectoryStructure(Event $event)
{
$options = static::getOptions($event);
if (!getenv('SENSIOLABS_ENABLE_NEW_DIRECTORY_STRUCTURE') || !$event->getIO()->askConfirmation('Would you like to use Symfony 3 directory structure? [y/N] ', false)) {
return;
}
$rootDir = getcwd();
$appDir = $options['symfony-app-dir'];
$webDir = $options['symfony-web-dir'];
$binDir = static::$options['symfony-bin-dir'] = 'bin';
$varDir = static::$options['symfony-var-dir'] = 'var';
static::updateDirectoryStructure($event, $rootDir, $appDir, $binDir, $varDir, $webDir);
} | [
"public",
"static",
"function",
"defineDirectoryStructure",
"(",
"Event",
"$",
"event",
")",
"{",
"$",
"options",
"=",
"static",
"::",
"getOptions",
"(",
"$",
"event",
")",
";",
"if",
"(",
"!",
"getenv",
"(",
"'SENSIOLABS_ENABLE_NEW_DIRECTORY_STRUCTURE'",
")",
... | Asks if the new directory structure should be used, installs the structure if needed.
@param Event $event | [
"Asks",
"if",
"the",
"new",
"directory",
"structure",
"should",
"be",
"used",
"installs",
"the",
"structure",
"if",
"needed",
"."
] | train | https://github.com/sensiolabs/SensioDistributionBundle/blob/59eac70f15f97ee945924948a6f5e2f6f86b7a4b/Composer/ScriptHandler.php#L43-L58 |
sensiolabs/SensioDistributionBundle | Composer/ScriptHandler.php | ScriptHandler.buildBootstrap | public static function buildBootstrap(Event $event)
{
$options = static::getOptions($event);
$bootstrapDir = $autoloadDir = $options['symfony-app-dir'];
if (static::useNewDirectoryStructure($options)) {
$bootstrapDir = $options['symfony-var-dir'];
if (!static::hasDirectory($event, 'symfony-var-dir', $bootstrapDir, 'build bootstrap file')) {
return;
}
}
if (!static::useSymfonyAutoloader($options)) {
$autoloadDir = $options['vendor-dir'];
}
if (!static::hasDirectory($event, 'symfony-app-dir', $autoloadDir, 'build bootstrap file')) {
return;
}
static::executeBuildBootstrap($event, $bootstrapDir, $autoloadDir, $options['process-timeout']);
} | php | public static function buildBootstrap(Event $event)
{
$options = static::getOptions($event);
$bootstrapDir = $autoloadDir = $options['symfony-app-dir'];
if (static::useNewDirectoryStructure($options)) {
$bootstrapDir = $options['symfony-var-dir'];
if (!static::hasDirectory($event, 'symfony-var-dir', $bootstrapDir, 'build bootstrap file')) {
return;
}
}
if (!static::useSymfonyAutoloader($options)) {
$autoloadDir = $options['vendor-dir'];
}
if (!static::hasDirectory($event, 'symfony-app-dir', $autoloadDir, 'build bootstrap file')) {
return;
}
static::executeBuildBootstrap($event, $bootstrapDir, $autoloadDir, $options['process-timeout']);
} | [
"public",
"static",
"function",
"buildBootstrap",
"(",
"Event",
"$",
"event",
")",
"{",
"$",
"options",
"=",
"static",
"::",
"getOptions",
"(",
"$",
"event",
")",
";",
"$",
"bootstrapDir",
"=",
"$",
"autoloadDir",
"=",
"$",
"options",
"[",
"'symfony-app-di... | Builds the bootstrap file.
The bootstrap file contains PHP file that are always needed by the application.
It speeds up the application bootstrapping.
@param Event $event | [
"Builds",
"the",
"bootstrap",
"file",
"."
] | train | https://github.com/sensiolabs/SensioDistributionBundle/blob/59eac70f15f97ee945924948a6f5e2f6f86b7a4b/Composer/ScriptHandler.php#L68-L89 |
sensiolabs/SensioDistributionBundle | Composer/ScriptHandler.php | ScriptHandler.installAssets | public static function installAssets(Event $event)
{
$options = static::getOptions($event);
$consoleDir = static::getConsoleDir($event, 'install assets');
if (null === $consoleDir) {
return;
}
$webDir = $options['symfony-web-dir'];
$symlink = '';
if ('symlink' == $options['symfony-assets-install']) {
$symlink = '--symlink ';
} elseif ('relative' == $options['symfony-assets-install']) {
$symlink = '--symlink --relative ';
}
if (!static::hasDirectory($event, 'symfony-web-dir', $webDir, 'install assets')) {
return;
}
static::executeCommand($event, $consoleDir, 'assets:install '.$symlink.ProcessExecutor::escape($webDir), $options['process-timeout']);
} | php | public static function installAssets(Event $event)
{
$options = static::getOptions($event);
$consoleDir = static::getConsoleDir($event, 'install assets');
if (null === $consoleDir) {
return;
}
$webDir = $options['symfony-web-dir'];
$symlink = '';
if ('symlink' == $options['symfony-assets-install']) {
$symlink = '--symlink ';
} elseif ('relative' == $options['symfony-assets-install']) {
$symlink = '--symlink --relative ';
}
if (!static::hasDirectory($event, 'symfony-web-dir', $webDir, 'install assets')) {
return;
}
static::executeCommand($event, $consoleDir, 'assets:install '.$symlink.ProcessExecutor::escape($webDir), $options['process-timeout']);
} | [
"public",
"static",
"function",
"installAssets",
"(",
"Event",
"$",
"event",
")",
"{",
"$",
"options",
"=",
"static",
"::",
"getOptions",
"(",
"$",
"event",
")",
";",
"$",
"consoleDir",
"=",
"static",
"::",
"getConsoleDir",
"(",
"$",
"event",
",",
"'inst... | Installs the assets under the web root directory.
For better interoperability, assets are copied instead of symlinked by default.
Even if symlinks work on Windows, this is only true on Windows Vista and later,
but then, only when running the console with admin rights or when disabling the
strict user permission checks (which can be done on Windows 7 but not on Windows
Vista).
@param Event $event | [
"Installs",
"the",
"assets",
"under",
"the",
"web",
"root",
"directory",
"."
] | train | https://github.com/sensiolabs/SensioDistributionBundle/blob/59eac70f15f97ee945924948a6f5e2f6f86b7a4b/Composer/ScriptHandler.php#L159-L182 |
sensiolabs/SensioDistributionBundle | Composer/ScriptHandler.php | ScriptHandler.installRequirementsFile | public static function installRequirementsFile(Event $event)
{
$options = static::getOptions($event);
$appDir = $options['symfony-app-dir'];
$fs = new Filesystem();
$newDirectoryStructure = static::useNewDirectoryStructure($options);
if (!$newDirectoryStructure) {
if (!static::hasDirectory($event, 'symfony-app-dir', $appDir, 'install the requirements files')) {
return;
}
$fs->copy(__DIR__.'/../Resources/skeleton/app/SymfonyRequirements.php', $appDir.'/SymfonyRequirements.php', true);
$fs->copy(__DIR__.'/../Resources/skeleton/app/check.php', $appDir.'/check.php', true);
} else {
$binDir = $options['symfony-bin-dir'];
$varDir = $options['symfony-var-dir'];
if (!static::hasDirectory($event, 'symfony-var-dir', $varDir, 'install the requirements files')) {
return;
}
if (!static::hasDirectory($event, 'symfony-bin-dir', $binDir, 'install the requirements files')) {
return;
}
$fs->copy(__DIR__.'/../Resources/skeleton/app/SymfonyRequirements.php', $varDir.'/SymfonyRequirements.php', true);
$fs->copy(__DIR__.'/../Resources/skeleton/app/check.php', $binDir.'/symfony_requirements', true);
$fs->remove(array($appDir.'/check.php', $appDir.'/SymfonyRequirements.php', true));
$fs->dumpFile($binDir.'/symfony_requirements', '#!/usr/bin/env php'."\n".str_replace(".'/SymfonyRequirements.php'", ".'/".$fs->makePathRelative(realpath($varDir), realpath($binDir))."SymfonyRequirements.php'", file_get_contents($binDir.'/symfony_requirements')));
$fs->chmod($binDir.'/symfony_requirements', 0755);
}
$webDir = $options['symfony-web-dir'];
// if the user has already removed the config.php file, do nothing
// as the file must be removed for production use
if ($fs->exists($webDir.'/config.php')) {
$requiredDir = $newDirectoryStructure ? $varDir : $appDir;
$fs->dumpFile($webDir.'/config.php', str_replace('/../app/SymfonyRequirements.php', '/'.$fs->makePathRelative(realpath($requiredDir), realpath($webDir)).'SymfonyRequirements.php', file_get_contents(__DIR__.'/../Resources/skeleton/web/config.php')));
}
} | php | public static function installRequirementsFile(Event $event)
{
$options = static::getOptions($event);
$appDir = $options['symfony-app-dir'];
$fs = new Filesystem();
$newDirectoryStructure = static::useNewDirectoryStructure($options);
if (!$newDirectoryStructure) {
if (!static::hasDirectory($event, 'symfony-app-dir', $appDir, 'install the requirements files')) {
return;
}
$fs->copy(__DIR__.'/../Resources/skeleton/app/SymfonyRequirements.php', $appDir.'/SymfonyRequirements.php', true);
$fs->copy(__DIR__.'/../Resources/skeleton/app/check.php', $appDir.'/check.php', true);
} else {
$binDir = $options['symfony-bin-dir'];
$varDir = $options['symfony-var-dir'];
if (!static::hasDirectory($event, 'symfony-var-dir', $varDir, 'install the requirements files')) {
return;
}
if (!static::hasDirectory($event, 'symfony-bin-dir', $binDir, 'install the requirements files')) {
return;
}
$fs->copy(__DIR__.'/../Resources/skeleton/app/SymfonyRequirements.php', $varDir.'/SymfonyRequirements.php', true);
$fs->copy(__DIR__.'/../Resources/skeleton/app/check.php', $binDir.'/symfony_requirements', true);
$fs->remove(array($appDir.'/check.php', $appDir.'/SymfonyRequirements.php', true));
$fs->dumpFile($binDir.'/symfony_requirements', '#!/usr/bin/env php'."\n".str_replace(".'/SymfonyRequirements.php'", ".'/".$fs->makePathRelative(realpath($varDir), realpath($binDir))."SymfonyRequirements.php'", file_get_contents($binDir.'/symfony_requirements')));
$fs->chmod($binDir.'/symfony_requirements', 0755);
}
$webDir = $options['symfony-web-dir'];
// if the user has already removed the config.php file, do nothing
// as the file must be removed for production use
if ($fs->exists($webDir.'/config.php')) {
$requiredDir = $newDirectoryStructure ? $varDir : $appDir;
$fs->dumpFile($webDir.'/config.php', str_replace('/../app/SymfonyRequirements.php', '/'.$fs->makePathRelative(realpath($requiredDir), realpath($webDir)).'SymfonyRequirements.php', file_get_contents(__DIR__.'/../Resources/skeleton/web/config.php')));
}
} | [
"public",
"static",
"function",
"installRequirementsFile",
"(",
"Event",
"$",
"event",
")",
"{",
"$",
"options",
"=",
"static",
"::",
"getOptions",
"(",
"$",
"event",
")",
";",
"$",
"appDir",
"=",
"$",
"options",
"[",
"'symfony-app-dir'",
"]",
";",
"$",
... | Updated the requirements file.
@param Event $event | [
"Updated",
"the",
"requirements",
"file",
"."
] | train | https://github.com/sensiolabs/SensioDistributionBundle/blob/59eac70f15f97ee945924948a6f5e2f6f86b7a4b/Composer/ScriptHandler.php#L189-L229 |
sensiolabs/SensioDistributionBundle | Composer/ScriptHandler.php | ScriptHandler.getConsoleDir | protected static function getConsoleDir(Event $event, $actionName)
{
$options = static::getOptions($event);
if (static::useNewDirectoryStructure($options)) {
if (!static::hasDirectory($event, 'symfony-bin-dir', $options['symfony-bin-dir'], $actionName)) {
return;
}
return $options['symfony-bin-dir'];
}
if (!static::hasDirectory($event, 'symfony-app-dir', $options['symfony-app-dir'], 'execute command')) {
return;
}
return $options['symfony-app-dir'];
} | php | protected static function getConsoleDir(Event $event, $actionName)
{
$options = static::getOptions($event);
if (static::useNewDirectoryStructure($options)) {
if (!static::hasDirectory($event, 'symfony-bin-dir', $options['symfony-bin-dir'], $actionName)) {
return;
}
return $options['symfony-bin-dir'];
}
if (!static::hasDirectory($event, 'symfony-app-dir', $options['symfony-app-dir'], 'execute command')) {
return;
}
return $options['symfony-app-dir'];
} | [
"protected",
"static",
"function",
"getConsoleDir",
"(",
"Event",
"$",
"event",
",",
"$",
"actionName",
")",
"{",
"$",
"options",
"=",
"static",
"::",
"getOptions",
"(",
"$",
"event",
")",
";",
"if",
"(",
"static",
"::",
"useNewDirectoryStructure",
"(",
"$... | Returns a relative path to the directory that contains the `console` command.
@param Event $event The command event
@param string $actionName The name of the action
@return string|null The path to the console directory, null if not found | [
"Returns",
"a",
"relative",
"path",
"to",
"the",
"directory",
"that",
"contains",
"the",
"console",
"command",
"."
] | train | https://github.com/sensiolabs/SensioDistributionBundle/blob/59eac70f15f97ee945924948a6f5e2f6f86b7a4b/Composer/ScriptHandler.php#L433-L450 |
opis/json-schema | src/Validator.php | Validator.validateSchema | protected function validateSchema(&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag): bool
{
if (is_bool($schema)) {
if ($schema) {
return true;
}
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, '$schema', [
'schema' => $schema
]));
return false;
}
if (!is_object($schema)) {
throw new InvalidSchemaException($schema);
}
if (property_exists($schema, '$ref') && is_string($schema->{'$ref'})) {
return $this->validateRef($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
}
return $this->validateKeywords($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
} | php | protected function validateSchema(&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag): bool
{
if (is_bool($schema)) {
if ($schema) {
return true;
}
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, '$schema', [
'schema' => $schema
]));
return false;
}
if (!is_object($schema)) {
throw new InvalidSchemaException($schema);
}
if (property_exists($schema, '$ref') && is_string($schema->{'$ref'})) {
return $this->validateRef($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
}
return $this->validateKeywords($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
} | [
"protected",
"function",
"validateSchema",
"(",
"&",
"$",
"document_data",
",",
"&",
"$",
"data",
",",
"array",
"$",
"data_pointer",
",",
"array",
"$",
"parent_data_pointer",
",",
"ISchema",
"$",
"document",
",",
"$",
"schema",
",",
"ValidationResult",
"$",
... | Validates a schema
@param $document_data
@param $data
@param array $data_pointer
@param array $parent_data_pointer
@param ISchema $document
@param $schema
@param ValidationResult $bag
@return bool | [
"Validates",
"a",
"schema"
] | train | https://github.com/opis/json-schema/blob/91f2464d44ffbaa34c3ee24e3bb6330690025859/src/Validator.php#L305-L326 |
opis/json-schema | src/Validator.php | Validator.validateRef | protected function validateRef(&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, stdClass $schema, ValidationResult $bag): bool
{
$ref = $schema->{'$ref'};
// $vars
if ($this->varsSupport) {
$ref = URI::parseTemplate($ref, $this->getVars($document_data, $data_pointer, $schema));
}
$map_used = $this->mapSupport && property_exists($schema, Schema::MAP_PROP);
// $map
if ($map_used) {
unset($data);
$data = $this->deepClone($schema->{Schema::MAP_PROP});
$this->resolveVars($data,$document_data, $data_pointer);
unset($document_data);
$document_data = &$data;
if ($data_pointer) {
$parent_data_pointer = array_merge($parent_data_pointer, $data_pointer);
$data_pointer = [];
}
}
// Check if is relative json pointer
if ($relative = JsonPointer::parseRelativePointer($ref, true)) {
if (!JsonPointer::isEscapedPointer($ref)) {
throw new InvalidJsonPointerException($ref);
}
$schema = JsonPointer::getDataByRelativePointer(
$document->resolve(),
$relative,
$schema->{Schema::PATH_PROP} ?? [],
$this
);
if ($schema === $this) {
throw new InvalidJsonPointerException($ref);
}
return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
}
// Check if is a json pointer relative to this document
if (isset($ref[0]) && $ref[0] === '#') {
$pointer = substr($ref, 1);
if (JsonPointer::isPointer($pointer)) {
if (!JsonPointer::isEscapedPointer($pointer)) {
throw new InvalidJsonPointerException($pointer);
}
$schema = JsonPointer::getDataByPointer($document->resolve(), $pointer, $this);
if ($schema === $this) {
throw new InvalidJsonPointerException($pointer);
}
return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
}
unset($pointer);
}
// Merge uris
$ref = URI::merge($ref, $schema->{Schema::BASE_ID_PROP} ?? '', true);
list($base_ref, $fragment) = explode('#', $ref, 2);
if (JsonPointer::isPointer($fragment)) {
if (!JsonPointer::isEscapedPointer($fragment)) {
throw new InvalidJsonPointerException($fragment);
}
// try to resolve locally
$schema = $document->resolve($base_ref . '#');
if ($schema === null) {
if (!$this->loader) {
throw new SchemaNotFoundException($base_ref);
}
// use loader
$document = $this->loader->loadSchema($base_ref);
if (!($document instanceof ISchema)) {
throw new SchemaNotFoundException($base_ref);
}
if ($fragment === '' || $fragment === '/') {
$schema = $document->resolve();
} else {
$schema = JsonPointer::getDataByPointer($document->resolve(), $fragment, $this);
if ($schema === $this) {
throw new InvalidJsonPointerException($fragment);
}
}
if (!$map_used) {
unset($document_data);
$document_data = &$data;
if ($data_pointer) {
$parent_data_pointer = array_merge($parent_data_pointer, $data_pointer);
$data_pointer = [];
}
}
} else {
if ($fragment !== '' && $fragment !== '/') {
$schema = JsonPointer::getDataByPointer($schema, $fragment, $this);
if ($schema === $this) {
throw new InvalidJsonPointerException($fragment);
}
}
}
return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
}
// Not a json pointer
$schema = $document->resolve($ref);
if ($schema !== null) {
return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
}
if (!$this->loader) {
throw new SchemaNotFoundException($base_ref);
}
// use loader
$document = $this->loader->loadSchema($base_ref);
if (!($document instanceof ISchema)) {
throw new SchemaNotFoundException($base_ref);
}
$schema = $document->resolve($ref);
if (!$map_used) {
unset($document_data);
$document_data = &$data;
if ($data_pointer) {
$parent_data_pointer = array_merge($parent_data_pointer, $data_pointer);
$data_pointer = [];
}
}
return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
} | php | protected function validateRef(&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, stdClass $schema, ValidationResult $bag): bool
{
$ref = $schema->{'$ref'};
// $vars
if ($this->varsSupport) {
$ref = URI::parseTemplate($ref, $this->getVars($document_data, $data_pointer, $schema));
}
$map_used = $this->mapSupport && property_exists($schema, Schema::MAP_PROP);
// $map
if ($map_used) {
unset($data);
$data = $this->deepClone($schema->{Schema::MAP_PROP});
$this->resolveVars($data,$document_data, $data_pointer);
unset($document_data);
$document_data = &$data;
if ($data_pointer) {
$parent_data_pointer = array_merge($parent_data_pointer, $data_pointer);
$data_pointer = [];
}
}
// Check if is relative json pointer
if ($relative = JsonPointer::parseRelativePointer($ref, true)) {
if (!JsonPointer::isEscapedPointer($ref)) {
throw new InvalidJsonPointerException($ref);
}
$schema = JsonPointer::getDataByRelativePointer(
$document->resolve(),
$relative,
$schema->{Schema::PATH_PROP} ?? [],
$this
);
if ($schema === $this) {
throw new InvalidJsonPointerException($ref);
}
return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
}
// Check if is a json pointer relative to this document
if (isset($ref[0]) && $ref[0] === '#') {
$pointer = substr($ref, 1);
if (JsonPointer::isPointer($pointer)) {
if (!JsonPointer::isEscapedPointer($pointer)) {
throw new InvalidJsonPointerException($pointer);
}
$schema = JsonPointer::getDataByPointer($document->resolve(), $pointer, $this);
if ($schema === $this) {
throw new InvalidJsonPointerException($pointer);
}
return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
}
unset($pointer);
}
// Merge uris
$ref = URI::merge($ref, $schema->{Schema::BASE_ID_PROP} ?? '', true);
list($base_ref, $fragment) = explode('#', $ref, 2);
if (JsonPointer::isPointer($fragment)) {
if (!JsonPointer::isEscapedPointer($fragment)) {
throw new InvalidJsonPointerException($fragment);
}
// try to resolve locally
$schema = $document->resolve($base_ref . '#');
if ($schema === null) {
if (!$this->loader) {
throw new SchemaNotFoundException($base_ref);
}
// use loader
$document = $this->loader->loadSchema($base_ref);
if (!($document instanceof ISchema)) {
throw new SchemaNotFoundException($base_ref);
}
if ($fragment === '' || $fragment === '/') {
$schema = $document->resolve();
} else {
$schema = JsonPointer::getDataByPointer($document->resolve(), $fragment, $this);
if ($schema === $this) {
throw new InvalidJsonPointerException($fragment);
}
}
if (!$map_used) {
unset($document_data);
$document_data = &$data;
if ($data_pointer) {
$parent_data_pointer = array_merge($parent_data_pointer, $data_pointer);
$data_pointer = [];
}
}
} else {
if ($fragment !== '' && $fragment !== '/') {
$schema = JsonPointer::getDataByPointer($schema, $fragment, $this);
if ($schema === $this) {
throw new InvalidJsonPointerException($fragment);
}
}
}
return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
}
// Not a json pointer
$schema = $document->resolve($ref);
if ($schema !== null) {
return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
}
if (!$this->loader) {
throw new SchemaNotFoundException($base_ref);
}
// use loader
$document = $this->loader->loadSchema($base_ref);
if (!($document instanceof ISchema)) {
throw new SchemaNotFoundException($base_ref);
}
$schema = $document->resolve($ref);
if (!$map_used) {
unset($document_data);
$document_data = &$data;
if ($data_pointer) {
$parent_data_pointer = array_merge($parent_data_pointer, $data_pointer);
$data_pointer = [];
}
}
return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
} | [
"protected",
"function",
"validateRef",
"(",
"&",
"$",
"document_data",
",",
"&",
"$",
"data",
",",
"array",
"$",
"data_pointer",
",",
"array",
"$",
"parent_data_pointer",
",",
"ISchema",
"$",
"document",
",",
"stdClass",
"$",
"schema",
",",
"ValidationResult"... | Resolves $ref property and validates resulted schema
@param $document_data
@param $data
@param array $data_pointer
@param array $parent_data_pointer
@param ISchema $document
@param stdClass $schema
@param ValidationResult $bag
@return bool | [
"Resolves",
"$ref",
"property",
"and",
"validates",
"resulted",
"schema"
] | train | https://github.com/opis/json-schema/blob/91f2464d44ffbaa34c3ee24e3bb6330690025859/src/Validator.php#L339-L480 |
opis/json-schema | src/Validator.php | Validator.validateKeywords | protected function validateKeywords(&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag): bool
{
// here the $ref is already resolved
$defaults = null;
// Set defaults if used
if ($this->defaultSupport && is_object($data) && is_object($schema) && property_exists($schema, 'properties')) {
foreach ($schema->properties as $property => $value) {
if (property_exists($data, $property) || !is_object($value) || !property_exists($value, 'default')) {
continue;
}
$defaults[$property] = $this->deepClone($value->default);
}
}
if (!$this->validateCommons($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag, $defaults)) {
return false;
}
if (!$this->validateProperties($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag, $defaults)) {
return false;
}
if (!$this->validateConditionals($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag)) {
return false;
}
if ($this->filtersSupport && !$this->validateFilters($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag)) {
return false;
}
return true;
} | php | protected function validateKeywords(&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag): bool
{
// here the $ref is already resolved
$defaults = null;
// Set defaults if used
if ($this->defaultSupport && is_object($data) && is_object($schema) && property_exists($schema, 'properties')) {
foreach ($schema->properties as $property => $value) {
if (property_exists($data, $property) || !is_object($value) || !property_exists($value, 'default')) {
continue;
}
$defaults[$property] = $this->deepClone($value->default);
}
}
if (!$this->validateCommons($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag, $defaults)) {
return false;
}
if (!$this->validateProperties($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag, $defaults)) {
return false;
}
if (!$this->validateConditionals($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag)) {
return false;
}
if ($this->filtersSupport && !$this->validateFilters($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag)) {
return false;
}
return true;
} | [
"protected",
"function",
"validateKeywords",
"(",
"&",
"$",
"document_data",
",",
"&",
"$",
"data",
",",
"array",
"$",
"data_pointer",
",",
"array",
"$",
"parent_data_pointer",
",",
"ISchema",
"$",
"document",
",",
"$",
"schema",
",",
"ValidationResult",
"$",
... | Validates schema keywords
@param $document_data
@param $data
@param array $data_pointer
@param array $parent_data_pointer
@param ISchema $document
@param $schema
@param ValidationResult $bag
@return bool | [
"Validates",
"schema",
"keywords"
] | train | https://github.com/opis/json-schema/blob/91f2464d44ffbaa34c3ee24e3bb6330690025859/src/Validator.php#L493-L525 |
opis/json-schema | src/Validator.php | Validator.validateCommons | protected function validateCommons(/** @noinspection PhpUnusedParameterInspection */
&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag, array &$defaults = null): bool
{
$ok = true;
// type
if (property_exists($schema, 'type')) {
if (is_string($schema->type)) {
if (!$this->helper->typeExists($schema->type)) {
throw new SchemaKeywordException(
$schema,
'type',
$schema->type,
"'type' keyword contains unknown value: " . $schema->type
);
}
} elseif (is_array($schema->type)) {
/** @noinspection PhpParamsInspection */
if (count($schema->type) === 0) {
throw new SchemaKeywordException(
$schema,
'type',
$schema->type,
"'type' keyword must not be an empty array"
);
}
/** @noinspection PhpParamsInspection */
if ($schema->type != array_unique($schema->type)) {
throw new SchemaKeywordException(
$schema,
'type',
$schema->type,
"'type' keyword contains duplicate items"
);
}
foreach ($schema->type as $type) {
if (!is_string($type)) {
throw new SchemaKeywordException(
$schema,
'type',
$type,
"'type' keyword must have only strings if array, found " . gettype($type)
);
}
if (!$this->helper->typeExists($type)) {
throw new SchemaKeywordException(
$schema,
'type',
$type,
"'type' keyword contains unknown value: " . $type
);
}
}
unset($type);
} else {
throw new SchemaKeywordException(
$schema,
'type',
$schema->type,
"'type' keyword must be a string or an array of strings, " . gettype($schema->type) . " given"
);
}
if (!$this->helper->isValidType($data, $schema->type)) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'type', [
'expected' => $schema->type,
'used' => $this->helper->type($data, true),
]));
if ($bag->isFull()) {
return false;
}
}
}
// const
if (property_exists($schema, 'const')) {
if (!$this->helper->equals($data, $schema->const, $defaults)) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'const', [
'expected' => $schema->const,
]));
if ($bag->isFull()) {
return false;
}
}
}
// enum
if (property_exists($schema, 'enum')) {
if (!is_array($schema->enum)) {
throw new SchemaKeywordException(
$schema,
'enum',
$schema->enum,
"'enum' keyword must be an array, " . gettype($schema->enum) . " given"
);
}
if (count($schema->enum) === 0) {
throw new SchemaKeywordException(
$schema,
'enum',
$schema->enum,
"'enum' keyword must not be empty"
);
}
$found = false;
foreach ($schema->enum as $v) {
if ($this->helper->equals($data, $v, $defaults)) {
$found = true;
break;
}
}
unset($v);
if (!$found) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'enum', [
'expected' => $schema->enum,
]));
if ($bag->isFull()) {
return false;
}
}
unset($found);
}
return $ok;
} | php | protected function validateCommons(/** @noinspection PhpUnusedParameterInspection */
&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag, array &$defaults = null): bool
{
$ok = true;
// type
if (property_exists($schema, 'type')) {
if (is_string($schema->type)) {
if (!$this->helper->typeExists($schema->type)) {
throw new SchemaKeywordException(
$schema,
'type',
$schema->type,
"'type' keyword contains unknown value: " . $schema->type
);
}
} elseif (is_array($schema->type)) {
/** @noinspection PhpParamsInspection */
if (count($schema->type) === 0) {
throw new SchemaKeywordException(
$schema,
'type',
$schema->type,
"'type' keyword must not be an empty array"
);
}
/** @noinspection PhpParamsInspection */
if ($schema->type != array_unique($schema->type)) {
throw new SchemaKeywordException(
$schema,
'type',
$schema->type,
"'type' keyword contains duplicate items"
);
}
foreach ($schema->type as $type) {
if (!is_string($type)) {
throw new SchemaKeywordException(
$schema,
'type',
$type,
"'type' keyword must have only strings if array, found " . gettype($type)
);
}
if (!$this->helper->typeExists($type)) {
throw new SchemaKeywordException(
$schema,
'type',
$type,
"'type' keyword contains unknown value: " . $type
);
}
}
unset($type);
} else {
throw new SchemaKeywordException(
$schema,
'type',
$schema->type,
"'type' keyword must be a string or an array of strings, " . gettype($schema->type) . " given"
);
}
if (!$this->helper->isValidType($data, $schema->type)) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'type', [
'expected' => $schema->type,
'used' => $this->helper->type($data, true),
]));
if ($bag->isFull()) {
return false;
}
}
}
// const
if (property_exists($schema, 'const')) {
if (!$this->helper->equals($data, $schema->const, $defaults)) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'const', [
'expected' => $schema->const,
]));
if ($bag->isFull()) {
return false;
}
}
}
// enum
if (property_exists($schema, 'enum')) {
if (!is_array($schema->enum)) {
throw new SchemaKeywordException(
$schema,
'enum',
$schema->enum,
"'enum' keyword must be an array, " . gettype($schema->enum) . " given"
);
}
if (count($schema->enum) === 0) {
throw new SchemaKeywordException(
$schema,
'enum',
$schema->enum,
"'enum' keyword must not be empty"
);
}
$found = false;
foreach ($schema->enum as $v) {
if ($this->helper->equals($data, $v, $defaults)) {
$found = true;
break;
}
}
unset($v);
if (!$found) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'enum', [
'expected' => $schema->enum,
]));
if ($bag->isFull()) {
return false;
}
}
unset($found);
}
return $ok;
} | [
"protected",
"function",
"validateCommons",
"(",
"/** @noinspection PhpUnusedParameterInspection */",
"&",
"$",
"document_data",
",",
"&",
"$",
"data",
",",
"array",
"$",
"data_pointer",
",",
"array",
"$",
"parent_data_pointer",
",",
"ISchema",
"$",
"document",
",",
... | Validates common keywords
@param $document_data
@param $data
@param array $data_pointer
@param array $parent_data_pointer
@param ISchema $document
@param stdClass $schema
@param ValidationResult $bag
@param array|null $defaults
@return bool | [
"Validates",
"common",
"keywords"
] | train | https://github.com/opis/json-schema/blob/91f2464d44ffbaa34c3ee24e3bb6330690025859/src/Validator.php#L539-L667 |
opis/json-schema | src/Validator.php | Validator.validateConditionals | protected function validateConditionals(&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag): bool
{
$ok = true;
// not
if (property_exists($schema, 'not')) {
if (!is_bool($schema->not) && !is_object($schema->not)) {
throw new SchemaKeywordException(
$schema,
'not',
$schema->not,
"'not' keyword must be a boolean or an object, " . gettype($schema->not) . " given"
);
}
$newbag = new ValidationResult(1);
$this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema->not, $newbag);
if (!$newbag->hasErrors()) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'not'));
if ($bag->isFull()) {
return false;
}
}
unset($newbag);
}
// if, then, else
if (property_exists($schema, 'if') && $document->draft() !== '06') {
if (!is_bool($schema->if) && !is_object($schema->if)) {
throw new SchemaKeywordException(
$schema,
'if',
$schema->if,
"'if' keyword must be a boolean or an object, " . gettype($schema->if) . " given"
);
}
if ($this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema->if, new ValidationResult(1))) {
if (property_exists($schema, 'then')) {
if (!is_bool($schema->then) && !is_object($schema->then)) {
throw new SchemaKeywordException(
$schema,
'then',
$schema->then,
"'then' keyword must be a boolean or an object, " . gettype($schema->then) . " given"
);
}
$newbag = $bag->createByDiff();
$this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema->then, $newbag);
if ($newbag->hasErrors()) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'then', [], $newbag->getErrors()));
if ($bag->isFull()) {
return false;
}
}
unset($newbag);
}
} elseif (property_exists($schema, 'else')) {
if (!is_bool($schema->else) && !is_object($schema->else)) {
throw new SchemaKeywordException(
$schema,
'else',
$schema->else,
"'else' keyword must be a boolean or an object, " . gettype($schema->then) . " given"
);
}
$newbag = $bag->createByDiff();
$this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema->else, $newbag);
if ($newbag->hasErrors()) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'else', [], $newbag->getErrors()));
if ($bag->isFull()) {
return false;
}
}
unset($newbag);
}
}
// anyOf
if (property_exists($schema, 'anyOf')) {
if (!is_array($schema->anyOf)) {
throw new SchemaKeywordException(
$schema,
'anyOf',
$schema->anyOf,
"'anyOf' keyword must be an array, " . gettype($schema->anyOf) . " given"
);
}
if (count($schema->anyOf) === 0) {
throw new SchemaKeywordException(
$schema,
'anyOf',
$schema->anyOf,
"'anyOf' keyword must not be empty"
);
}
$newbag = new ValidationResult(1);
$valid = false;
$errors = [];
foreach ($schema->anyOf as &$one) {
if (!is_bool($one) && !is_object($one)) {
throw new SchemaKeywordException(
$schema,
'anyOf',
$schema->anyOf,
"'anyOf' keyword items must be booleans or objects, found " . gettype($one)
);
}
if ($this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $one, $newbag)) {
$valid = true;
break;
}
$errors = array_merge($errors, $newbag->getErrors());
$newbag->clear();
}
unset($one, $newbag);
if (!$valid) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'anyOf', [], $errors));
if ($bag->isFull()) {
return false;
}
}
unset($errors);
}
// oneOf
if (property_exists($schema, 'oneOf')) {
if (!is_array($schema->oneOf)) {
throw new SchemaKeywordException(
$schema,
'oneOf',
$schema->oneOf,
"'oneOf' keyword must be an array, " . gettype($schema->oneOf) . " given"
);
}
if (count($schema->oneOf) === 0) {
throw new SchemaKeywordException(
$schema,
'oneOf',
$schema->oneOf,
"'oneOf' keyword must not be empty"
);
}
$errors = [];
$newbag = new ValidationResult(1);
$count = 0;
foreach ($schema->oneOf as &$one) {
if (!is_bool($one) && !is_object($one)) {
throw new SchemaKeywordException(
$schema,
'oneOf',
$schema->oneOf,
"'oneOf' keyword items must be booleans or objects, found " . gettype($one)
);
}
if ($this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $one, $newbag)) {
if (++$count > 1) {
break;
}
}
$errors = array_merge($errors, $newbag->getErrors());
$newbag->clear();
}
unset($one, $newbag);
if ($count !== 1) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'oneOf', [
'matched' => $count,
], $errors));
if ($bag->isFull()) {
return false;
}
}
unset($errors);
}
// allOf
if (property_exists($schema, 'allOf')) {
if (!is_array($schema->allOf)) {
throw new SchemaKeywordException(
$schema,
'allOf',
$schema->allOf,
"'allOf' keyword must be an array, " . gettype($schema->allOf) . " given"
);
}
if (count($schema->allOf) === 0) {
throw new SchemaKeywordException(
$schema,
'allOf',
$schema->allOf,
"'allOf' keyword must not be empty"
);
}
$newbag = $bag->createByDiff();
$errors = null;
$valid = true;
foreach ($schema->allOf as &$one) {
if (!is_bool($one) && !is_object($one)) {
throw new SchemaKeywordException(
$schema,
'allOf',
$schema->allOf,
"'allOf' keyword items must be booleans or objects, found " . gettype($one)
);
}
if (!$this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $one, $newbag)) {
$valid = false;
$errors = $newbag->getErrors();
break;
}
$newbag->clear();
}
unset($one, $newbag);
if (!$valid) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'allOf', [], $errors));
if ($bag->isFull()) {
return false;
}
}
unset($errors);
}
return $ok;
} | php | protected function validateConditionals(&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag): bool
{
$ok = true;
// not
if (property_exists($schema, 'not')) {
if (!is_bool($schema->not) && !is_object($schema->not)) {
throw new SchemaKeywordException(
$schema,
'not',
$schema->not,
"'not' keyword must be a boolean or an object, " . gettype($schema->not) . " given"
);
}
$newbag = new ValidationResult(1);
$this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema->not, $newbag);
if (!$newbag->hasErrors()) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'not'));
if ($bag->isFull()) {
return false;
}
}
unset($newbag);
}
// if, then, else
if (property_exists($schema, 'if') && $document->draft() !== '06') {
if (!is_bool($schema->if) && !is_object($schema->if)) {
throw new SchemaKeywordException(
$schema,
'if',
$schema->if,
"'if' keyword must be a boolean or an object, " . gettype($schema->if) . " given"
);
}
if ($this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema->if, new ValidationResult(1))) {
if (property_exists($schema, 'then')) {
if (!is_bool($schema->then) && !is_object($schema->then)) {
throw new SchemaKeywordException(
$schema,
'then',
$schema->then,
"'then' keyword must be a boolean or an object, " . gettype($schema->then) . " given"
);
}
$newbag = $bag->createByDiff();
$this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema->then, $newbag);
if ($newbag->hasErrors()) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'then', [], $newbag->getErrors()));
if ($bag->isFull()) {
return false;
}
}
unset($newbag);
}
} elseif (property_exists($schema, 'else')) {
if (!is_bool($schema->else) && !is_object($schema->else)) {
throw new SchemaKeywordException(
$schema,
'else',
$schema->else,
"'else' keyword must be a boolean or an object, " . gettype($schema->then) . " given"
);
}
$newbag = $bag->createByDiff();
$this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema->else, $newbag);
if ($newbag->hasErrors()) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'else', [], $newbag->getErrors()));
if ($bag->isFull()) {
return false;
}
}
unset($newbag);
}
}
// anyOf
if (property_exists($schema, 'anyOf')) {
if (!is_array($schema->anyOf)) {
throw new SchemaKeywordException(
$schema,
'anyOf',
$schema->anyOf,
"'anyOf' keyword must be an array, " . gettype($schema->anyOf) . " given"
);
}
if (count($schema->anyOf) === 0) {
throw new SchemaKeywordException(
$schema,
'anyOf',
$schema->anyOf,
"'anyOf' keyword must not be empty"
);
}
$newbag = new ValidationResult(1);
$valid = false;
$errors = [];
foreach ($schema->anyOf as &$one) {
if (!is_bool($one) && !is_object($one)) {
throw new SchemaKeywordException(
$schema,
'anyOf',
$schema->anyOf,
"'anyOf' keyword items must be booleans or objects, found " . gettype($one)
);
}
if ($this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $one, $newbag)) {
$valid = true;
break;
}
$errors = array_merge($errors, $newbag->getErrors());
$newbag->clear();
}
unset($one, $newbag);
if (!$valid) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'anyOf', [], $errors));
if ($bag->isFull()) {
return false;
}
}
unset($errors);
}
// oneOf
if (property_exists($schema, 'oneOf')) {
if (!is_array($schema->oneOf)) {
throw new SchemaKeywordException(
$schema,
'oneOf',
$schema->oneOf,
"'oneOf' keyword must be an array, " . gettype($schema->oneOf) . " given"
);
}
if (count($schema->oneOf) === 0) {
throw new SchemaKeywordException(
$schema,
'oneOf',
$schema->oneOf,
"'oneOf' keyword must not be empty"
);
}
$errors = [];
$newbag = new ValidationResult(1);
$count = 0;
foreach ($schema->oneOf as &$one) {
if (!is_bool($one) && !is_object($one)) {
throw new SchemaKeywordException(
$schema,
'oneOf',
$schema->oneOf,
"'oneOf' keyword items must be booleans or objects, found " . gettype($one)
);
}
if ($this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $one, $newbag)) {
if (++$count > 1) {
break;
}
}
$errors = array_merge($errors, $newbag->getErrors());
$newbag->clear();
}
unset($one, $newbag);
if ($count !== 1) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'oneOf', [
'matched' => $count,
], $errors));
if ($bag->isFull()) {
return false;
}
}
unset($errors);
}
// allOf
if (property_exists($schema, 'allOf')) {
if (!is_array($schema->allOf)) {
throw new SchemaKeywordException(
$schema,
'allOf',
$schema->allOf,
"'allOf' keyword must be an array, " . gettype($schema->allOf) . " given"
);
}
if (count($schema->allOf) === 0) {
throw new SchemaKeywordException(
$schema,
'allOf',
$schema->allOf,
"'allOf' keyword must not be empty"
);
}
$newbag = $bag->createByDiff();
$errors = null;
$valid = true;
foreach ($schema->allOf as &$one) {
if (!is_bool($one) && !is_object($one)) {
throw new SchemaKeywordException(
$schema,
'allOf',
$schema->allOf,
"'allOf' keyword items must be booleans or objects, found " . gettype($one)
);
}
if (!$this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $one, $newbag)) {
$valid = false;
$errors = $newbag->getErrors();
break;
}
$newbag->clear();
}
unset($one, $newbag);
if (!$valid) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'allOf', [], $errors));
if ($bag->isFull()) {
return false;
}
}
unset($errors);
}
return $ok;
} | [
"protected",
"function",
"validateConditionals",
"(",
"&",
"$",
"document_data",
",",
"&",
"$",
"data",
",",
"array",
"$",
"data_pointer",
",",
"array",
"$",
"parent_data_pointer",
",",
"ISchema",
"$",
"document",
",",
"$",
"schema",
",",
"ValidationResult",
"... | Validates conditionals and boolean logic
@param $document_data
@param $data
@param array $data_pointer
@param array $parent_data_pointer
@param ISchema $document
@param stdClass $schema
@param ValidationResult $bag
@return bool | [
"Validates",
"conditionals",
"and",
"boolean",
"logic"
] | train | https://github.com/opis/json-schema/blob/91f2464d44ffbaa34c3ee24e3bb6330690025859/src/Validator.php#L680-L911 |
opis/json-schema | src/Validator.php | Validator.validateProperties | protected function validateProperties(&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag, array $defaults = null): bool
{
$type = $this->helper->type($data, true);
if ($type === 'null' || $type === 'boolean') {
return true;
}
$valid = false;
switch ($type) {
case 'string':
$valid = $this->validateString($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
break;
case 'number':
case 'integer':
$valid = $this->validateNumber($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
break;
case 'array':
$valid = $this->validateArray($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
break;
case 'object':
$valid = $this->validateObject($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag, $defaults);
// Setup unused defaults
if (!$valid && $defaults) {
$this->setObjectDefaults($data, $defaults);
}
break;
}
if (!$valid && $bag->isFull()) {
return false;
}
if (property_exists($schema, 'format') && $this->formats) {
if (!is_string($schema->format)) {
throw new SchemaKeywordException(
$schema,
'format',
$schema->format,
"'format' keyword must be a string, " . gettype($schema->format) . ", given"
);
}
$formatObj = $this->formats->get($type, $schema->format);
if ($formatObj === null && $type === 'integer') {
$formatObj = $this->formats->get('number', $schema->format);
}
if ($formatObj !== null) {
if (!$formatObj->validate($data)) {
$valid = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'format', [
'type' => $type,
'format' => $schema->format,
]));
if ($bag->isFull()) {
return false;
}
}
}
unset($formatObj);
}
return $valid;
} | php | protected function validateProperties(&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag, array $defaults = null): bool
{
$type = $this->helper->type($data, true);
if ($type === 'null' || $type === 'boolean') {
return true;
}
$valid = false;
switch ($type) {
case 'string':
$valid = $this->validateString($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
break;
case 'number':
case 'integer':
$valid = $this->validateNumber($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
break;
case 'array':
$valid = $this->validateArray($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
break;
case 'object':
$valid = $this->validateObject($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag, $defaults);
// Setup unused defaults
if (!$valid && $defaults) {
$this->setObjectDefaults($data, $defaults);
}
break;
}
if (!$valid && $bag->isFull()) {
return false;
}
if (property_exists($schema, 'format') && $this->formats) {
if (!is_string($schema->format)) {
throw new SchemaKeywordException(
$schema,
'format',
$schema->format,
"'format' keyword must be a string, " . gettype($schema->format) . ", given"
);
}
$formatObj = $this->formats->get($type, $schema->format);
if ($formatObj === null && $type === 'integer') {
$formatObj = $this->formats->get('number', $schema->format);
}
if ($formatObj !== null) {
if (!$formatObj->validate($data)) {
$valid = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'format', [
'type' => $type,
'format' => $schema->format,
]));
if ($bag->isFull()) {
return false;
}
}
}
unset($formatObj);
}
return $valid;
} | [
"protected",
"function",
"validateProperties",
"(",
"&",
"$",
"document_data",
",",
"&",
"$",
"data",
",",
"array",
"$",
"data_pointer",
",",
"array",
"$",
"parent_data_pointer",
",",
"ISchema",
"$",
"document",
",",
"$",
"schema",
",",
"ValidationResult",
"$"... | Validates keywords based on data type
@param $document_data
@param $data
@param array $data_pointer
@param array $parent_data_pointer
@param ISchema $document
@param $schema
@param ValidationResult $bag
@param array|null $defaults
@return bool | [
"Validates",
"keywords",
"based",
"on",
"data",
"type"
] | train | https://github.com/opis/json-schema/blob/91f2464d44ffbaa34c3ee24e3bb6330690025859/src/Validator.php#L925-L987 |
opis/json-schema | src/Validator.php | Validator.validateFilters | protected function validateFilters(/** @noinspection PhpUnusedParameterInspection */
&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag): bool
{
if (!property_exists($schema, Schema::FILTERS_PROP) || !$this->filters) {
return true;
}
/** @var array $filters */
$filters = null;
if (is_string($schema->{Schema::FILTERS_PROP})) {
$filters = [(object)[Schema::FUNC_NAME => $schema->{Schema::FILTERS_PROP}]];
}
elseif (is_object($schema->{Schema::FILTERS_PROP})) {
$filters = [$schema->{Schema::FILTERS_PROP}];
} elseif (is_array($schema->{Schema::FILTERS_PROP})) {
$filters = $schema->{Schema::FILTERS_PROP};
if (count($filters) === 0) {
return true;
}
foreach ($filters as &$filter) {
if (is_string($filter)) {
$filter = (object)[Schema::FUNC_NAME => $filter];
}
}
unset($filter);
} else {
throw new SchemaKeywordException(
$schema,
Schema::FILTERS_PROP,
$schema->{Schema::FILTERS_PROP},
"'" . Schema::FILTERS_PROP . "' keyword must be a string, an object or an array of objects, " . gettype($schema->{Schema::FILTERS_PROP}) . " given"
);
}
$type = $this->helper->type($data, true);
$filter_name = null;
$valid = true;
foreach ($filters as $filter) {
if (!is_object($filter)) {
throw new SchemaKeywordException(
$schema,
Schema::FILTERS_PROP,
$schema->{Schema::FILTERS_PROP},
"'" . Schema::FILTERS_PROP . "' keyword must be a string, an object or an array of objects, found " . gettype($filter)
);
}
if (!property_exists($filter, Schema::FUNC_NAME)) {
throw new SchemaKeywordException(
$filter,
Schema::FUNC_NAME,
null,
"'" . Schema::FUNC_NAME . "' keyword is required"
);
}
if (!is_string($filter->{Schema::FUNC_NAME})) {
throw new SchemaKeywordException(
$filter,
Schema::FUNC_NAME,
$filter->{Schema::FUNC_NAME},
"'" . Schema::FUNC_NAME . "' keyword must be a string, " . gettype($filter->{Schema::FUNC_NAME}) . " given"
);
}
$filterObj = $this->filters->get($type, $filter->{Schema::FUNC_NAME});
if ($filterObj === null) {
if ($type === 'integer') {
$filterObj = $this->filters->get('number', $filter->{Schema::FUNC_NAME});
if ($filterObj === null) {
throw new FilterNotFoundException($type, $filter->{Schema::FUNC_NAME});
}
} else {
throw new FilterNotFoundException($type, $filter->{Schema::FUNC_NAME});
}
}
if (property_exists($filter, Schema::VARS_PROP)) {
if (!is_object($filter->{Schema::VARS_PROP})) {
throw new SchemaKeywordException(
$filter,
Schema::VARS_PROP,
$filter->{Schema::VARS_PROP},
"'" . Schema::VARS_PROP . "' keyword must be an object, " . gettype($filter->{Schema::VARS_PROP}) . " given"
);
}
$vars = $this->deepClone($filter->{Schema::VARS_PROP});
$this->resolveVars($vars, $document_data, $data_pointer);
$vars = (array)$vars;
if ($this->globalVars) {
$vars += $this->globalVars;
}
} else {
$vars = $this->globalVars;
}
if (!$filterObj->validate($data, $vars)) {
$valid = false;
$filter_name = $filter->{Schema::FUNC_NAME};
break;
}
unset($vars, $filterObj);
}
if (!$valid) {
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, Schema::FILTERS_PROP, [
'type' => $type,
'filter' => $filter_name,
]));
return false;
}
return true;
} | php | protected function validateFilters(/** @noinspection PhpUnusedParameterInspection */
&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag): bool
{
if (!property_exists($schema, Schema::FILTERS_PROP) || !$this->filters) {
return true;
}
/** @var array $filters */
$filters = null;
if (is_string($schema->{Schema::FILTERS_PROP})) {
$filters = [(object)[Schema::FUNC_NAME => $schema->{Schema::FILTERS_PROP}]];
}
elseif (is_object($schema->{Schema::FILTERS_PROP})) {
$filters = [$schema->{Schema::FILTERS_PROP}];
} elseif (is_array($schema->{Schema::FILTERS_PROP})) {
$filters = $schema->{Schema::FILTERS_PROP};
if (count($filters) === 0) {
return true;
}
foreach ($filters as &$filter) {
if (is_string($filter)) {
$filter = (object)[Schema::FUNC_NAME => $filter];
}
}
unset($filter);
} else {
throw new SchemaKeywordException(
$schema,
Schema::FILTERS_PROP,
$schema->{Schema::FILTERS_PROP},
"'" . Schema::FILTERS_PROP . "' keyword must be a string, an object or an array of objects, " . gettype($schema->{Schema::FILTERS_PROP}) . " given"
);
}
$type = $this->helper->type($data, true);
$filter_name = null;
$valid = true;
foreach ($filters as $filter) {
if (!is_object($filter)) {
throw new SchemaKeywordException(
$schema,
Schema::FILTERS_PROP,
$schema->{Schema::FILTERS_PROP},
"'" . Schema::FILTERS_PROP . "' keyword must be a string, an object or an array of objects, found " . gettype($filter)
);
}
if (!property_exists($filter, Schema::FUNC_NAME)) {
throw new SchemaKeywordException(
$filter,
Schema::FUNC_NAME,
null,
"'" . Schema::FUNC_NAME . "' keyword is required"
);
}
if (!is_string($filter->{Schema::FUNC_NAME})) {
throw new SchemaKeywordException(
$filter,
Schema::FUNC_NAME,
$filter->{Schema::FUNC_NAME},
"'" . Schema::FUNC_NAME . "' keyword must be a string, " . gettype($filter->{Schema::FUNC_NAME}) . " given"
);
}
$filterObj = $this->filters->get($type, $filter->{Schema::FUNC_NAME});
if ($filterObj === null) {
if ($type === 'integer') {
$filterObj = $this->filters->get('number', $filter->{Schema::FUNC_NAME});
if ($filterObj === null) {
throw new FilterNotFoundException($type, $filter->{Schema::FUNC_NAME});
}
} else {
throw new FilterNotFoundException($type, $filter->{Schema::FUNC_NAME});
}
}
if (property_exists($filter, Schema::VARS_PROP)) {
if (!is_object($filter->{Schema::VARS_PROP})) {
throw new SchemaKeywordException(
$filter,
Schema::VARS_PROP,
$filter->{Schema::VARS_PROP},
"'" . Schema::VARS_PROP . "' keyword must be an object, " . gettype($filter->{Schema::VARS_PROP}) . " given"
);
}
$vars = $this->deepClone($filter->{Schema::VARS_PROP});
$this->resolveVars($vars, $document_data, $data_pointer);
$vars = (array)$vars;
if ($this->globalVars) {
$vars += $this->globalVars;
}
} else {
$vars = $this->globalVars;
}
if (!$filterObj->validate($data, $vars)) {
$valid = false;
$filter_name = $filter->{Schema::FUNC_NAME};
break;
}
unset($vars, $filterObj);
}
if (!$valid) {
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, Schema::FILTERS_PROP, [
'type' => $type,
'filter' => $filter_name,
]));
return false;
}
return true;
} | [
"protected",
"function",
"validateFilters",
"(",
"/** @noinspection PhpUnusedParameterInspection */",
"&",
"$",
"document_data",
",",
"&",
"$",
"data",
",",
"array",
"$",
"data_pointer",
",",
"array",
"$",
"parent_data_pointer",
",",
"ISchema",
"$",
"document",
",",
... | Validates custom filters
@param $document_data
@param $data
@param array $data_pointer
@param array $parent_data_pointer
@param ISchema $document
@param $schema
@param ValidationResult $bag
@return bool | [
"Validates",
"custom",
"filters"
] | train | https://github.com/opis/json-schema/blob/91f2464d44ffbaa34c3ee24e3bb6330690025859/src/Validator.php#L1000-L1112 |
opis/json-schema | src/Validator.php | Validator.validateString | protected function validateString(/** @noinspection PhpUnusedParameterInspection */
&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag): bool
{
$ok = true;
// minLength
if (property_exists($schema, 'minLength')) {
if (!is_int($schema->minLength)) {
throw new SchemaKeywordException(
$schema,
'minLength',
$schema->minLength,
"'minLength' keyword must be an integer, " . gettype($schema->minLength) . " given"
);
}
if ($schema->minLength < 0) {
throw new SchemaKeywordException(
$schema,
'minLength',
$schema->minLength,
"'minLength' keyword must be positive, " . $schema->minLength . " given"
);
}
$len = $this->helper->stringLength($data);
if ($len < $schema->minLength) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'minLength', [
'min' => $schema->minLength,
'length' => $len,
]));
if ($bag->isFull()) {
return false;
}
}
unset($len);
}
// maxLength
if (property_exists($schema, 'maxLength')) {
if (!is_int($schema->maxLength)) {
throw new SchemaKeywordException(
$schema,
'maxLength',
$schema->maxLength,
"'maxLength' keyword must be an integer, " . gettype($schema->maxLength) . " given"
);
}
if ($schema->maxLength < 0) {
throw new SchemaKeywordException(
$schema,
'maxLength',
$schema->maxLength,
"'maxLength' keyword must be positive, " . $schema->maxLength . " given"
);
}
$len = $this->helper->stringLength($data);
if ($len > $schema->maxLength) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'maxLength', [
'max' => $schema->maxLength,
'length' => $len,
]));
if ($bag->isFull()) {
return false;
}
}
unset($len);
}
// pattern
if (property_exists($schema, 'pattern')) {
if (!is_string($schema->pattern)) {
throw new SchemaKeywordException(
$schema,
'pattern',
$schema->pattern,
"'pattern' keyword must be a string, " . gettype($schema->pattern) . " given"
);
}
if ($schema->pattern === '') {
throw new SchemaKeywordException(
$schema,
'pattern',
$schema->pattern,
"'pattern' keyword must not be empty"
);
}
$match = @preg_match(self::BELL . $schema->pattern . self::BELL . 'u', $data);
if ($match === false) {
throw new SchemaKeywordException(
$schema,
'pattern',
$schema->pattern,
"'pattern' keyword must be a valid regex"
);
}
if (!$match) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'pattern', [
'pattern' => $schema->pattern,
]));
if ($bag->isFull()) {
return false;
}
}
}
// content encoding
if (property_exists($schema, 'contentEncoding')) {
if (!is_string($schema->contentEncoding)) {
throw new SchemaKeywordException(
$schema,
'contentEncoding',
$schema->contentEncoding,
"'contentEncoding' keyword must be a string, " . gettype($schema->contentEncoding) . " given"
);
}
switch ($schema->contentEncoding) {
case "binary":
$decoded = $data;
break;
case "base64":
$decoded = base64_decode($data, true);
break;
default:
$decoded = false;
break;
}
if ($decoded === false) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'contentEncoding', [
'encoding' => $schema->contentEncoding,
]));
if ($bag->isFull()) {
return false;
}
}
}
// media type
if (property_exists($schema, 'contentMediaType')) {
if (!is_string($schema->contentMediaType)) {
throw new SchemaKeywordException(
$schema,
'contentMediaType',
$schema->contentMediaType,
"'contentMediaType' keyword must be a string, " . gettype($schema->contentMediaType) . " given"
);
}
if (!$this->mediaTypes) {
throw new UnknownMediaTypeException($schema, $schema->contentMediaType);
}
if (!isset($decoded)) {
// is set in contentEncoding if any
$decoded = $data;
}
$valid = false;
if ($decoded !== false) {
$media = $this->mediaTypes->resolve($schema->contentMediaType);
if ($media === null) {
throw new UnknownMediaTypeException($schema, $schema->contentMediaType);
} else {
$valid = $media->validate($decoded, $schema->contentMediaType);
}
}
if (!$valid) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'contentMediaType', [
'media' => $schema->contentMediaType,
]));
if ($bag->isFull()) {
return false;
}
}
}
return $ok;
} | php | protected function validateString(/** @noinspection PhpUnusedParameterInspection */
&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag): bool
{
$ok = true;
// minLength
if (property_exists($schema, 'minLength')) {
if (!is_int($schema->minLength)) {
throw new SchemaKeywordException(
$schema,
'minLength',
$schema->minLength,
"'minLength' keyword must be an integer, " . gettype($schema->minLength) . " given"
);
}
if ($schema->minLength < 0) {
throw new SchemaKeywordException(
$schema,
'minLength',
$schema->minLength,
"'minLength' keyword must be positive, " . $schema->minLength . " given"
);
}
$len = $this->helper->stringLength($data);
if ($len < $schema->minLength) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'minLength', [
'min' => $schema->minLength,
'length' => $len,
]));
if ($bag->isFull()) {
return false;
}
}
unset($len);
}
// maxLength
if (property_exists($schema, 'maxLength')) {
if (!is_int($schema->maxLength)) {
throw new SchemaKeywordException(
$schema,
'maxLength',
$schema->maxLength,
"'maxLength' keyword must be an integer, " . gettype($schema->maxLength) . " given"
);
}
if ($schema->maxLength < 0) {
throw new SchemaKeywordException(
$schema,
'maxLength',
$schema->maxLength,
"'maxLength' keyword must be positive, " . $schema->maxLength . " given"
);
}
$len = $this->helper->stringLength($data);
if ($len > $schema->maxLength) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'maxLength', [
'max' => $schema->maxLength,
'length' => $len,
]));
if ($bag->isFull()) {
return false;
}
}
unset($len);
}
// pattern
if (property_exists($schema, 'pattern')) {
if (!is_string($schema->pattern)) {
throw new SchemaKeywordException(
$schema,
'pattern',
$schema->pattern,
"'pattern' keyword must be a string, " . gettype($schema->pattern) . " given"
);
}
if ($schema->pattern === '') {
throw new SchemaKeywordException(
$schema,
'pattern',
$schema->pattern,
"'pattern' keyword must not be empty"
);
}
$match = @preg_match(self::BELL . $schema->pattern . self::BELL . 'u', $data);
if ($match === false) {
throw new SchemaKeywordException(
$schema,
'pattern',
$schema->pattern,
"'pattern' keyword must be a valid regex"
);
}
if (!$match) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'pattern', [
'pattern' => $schema->pattern,
]));
if ($bag->isFull()) {
return false;
}
}
}
// content encoding
if (property_exists($schema, 'contentEncoding')) {
if (!is_string($schema->contentEncoding)) {
throw new SchemaKeywordException(
$schema,
'contentEncoding',
$schema->contentEncoding,
"'contentEncoding' keyword must be a string, " . gettype($schema->contentEncoding) . " given"
);
}
switch ($schema->contentEncoding) {
case "binary":
$decoded = $data;
break;
case "base64":
$decoded = base64_decode($data, true);
break;
default:
$decoded = false;
break;
}
if ($decoded === false) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'contentEncoding', [
'encoding' => $schema->contentEncoding,
]));
if ($bag->isFull()) {
return false;
}
}
}
// media type
if (property_exists($schema, 'contentMediaType')) {
if (!is_string($schema->contentMediaType)) {
throw new SchemaKeywordException(
$schema,
'contentMediaType',
$schema->contentMediaType,
"'contentMediaType' keyword must be a string, " . gettype($schema->contentMediaType) . " given"
);
}
if (!$this->mediaTypes) {
throw new UnknownMediaTypeException($schema, $schema->contentMediaType);
}
if (!isset($decoded)) {
// is set in contentEncoding if any
$decoded = $data;
}
$valid = false;
if ($decoded !== false) {
$media = $this->mediaTypes->resolve($schema->contentMediaType);
if ($media === null) {
throw new UnknownMediaTypeException($schema, $schema->contentMediaType);
} else {
$valid = $media->validate($decoded, $schema->contentMediaType);
}
}
if (!$valid) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'contentMediaType', [
'media' => $schema->contentMediaType,
]));
if ($bag->isFull()) {
return false;
}
}
}
return $ok;
} | [
"protected",
"function",
"validateString",
"(",
"/** @noinspection PhpUnusedParameterInspection */",
"&",
"$",
"document_data",
",",
"&",
"$",
"data",
",",
"array",
"$",
"data_pointer",
",",
"array",
"$",
"parent_data_pointer",
",",
"ISchema",
"$",
"document",
",",
... | Validates string keywords
@param $document_data
@param $data
@param array $data_pointer
@param array $parent_data_pointer
@param ISchema $document
@param $schema
@param ValidationResult $bag
@return bool | [
"Validates",
"string",
"keywords"
] | train | https://github.com/opis/json-schema/blob/91f2464d44ffbaa34c3ee24e3bb6330690025859/src/Validator.php#L1125-L1309 |
opis/json-schema | src/Validator.php | Validator.validateNumber | protected function validateNumber(/** @noinspection PhpUnusedParameterInspection */
&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag): bool
{
$ok = true;
// minimum, exclusiveMinimum
if (property_exists($schema, 'minimum')) {
if (!is_int($schema->minimum) && !is_float($schema->minimum)) {
throw new SchemaKeywordException(
$schema,
'minimum',
$schema->minimum,
"'minimum' keyword must be an integer or a float, " . gettype($schema->minimum) . " given"
);
}
$exclusive = false;
if (property_exists($schema, 'exclusiveMinimum')) {
if (!is_bool($schema->exclusiveMinimum)) {
throw new SchemaKeywordException(
$schema,
'exclusiveMinimum',
$schema->exclusiveMinimum,
"'exclusiveMinimum' keyword must be a boolean if 'minimum' keyword is present, " . gettype($schema->exclusiveMinimum) . " given"
);
}
$exclusive = $schema->exclusiveMinimum;
}
if ($exclusive && $data == $schema->minimum) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'exclusiveMinimum', [
'min' => $schema->minimum
]));
if ($bag->isFull()) {
return false;
}
} elseif ($data < $schema->minimum) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'minimum', [
'min' => $schema->minimum
]));
if ($bag->isFull()) {
return false;
}
}
} elseif (property_exists($schema, 'exclusiveMinimum')) {
if (!is_int($schema->exclusiveMinimum) && !is_float($schema->exclusiveMinimum)) {
throw new SchemaKeywordException(
$schema,
'exclusiveMinimum',
$schema->exclusiveMinimum,
"'exclusiveMinimum' keyword must be an integer or a float if 'minimum' keyword is not present, " . gettype($schema->exclusiveMinimum) . " given"
);
}
if ($data <= $schema->exclusiveMinimum) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'exclusiveMinimum', [
'min' => $schema->exclusiveMinimum
]));
if ($bag->isFull()) {
return false;
}
}
}
// maximum, exclusiveMaximum
if (property_exists($schema, 'maximum')) {
if (!is_int($schema->maximum) && !is_float($schema->maximum)) {
throw new SchemaKeywordException(
$schema,
'maximum',
$schema->maximum,
"'maximum' keyword must be an integer or a float, " . gettype($schema->maximum) . " given"
);
}
$exclusive = false;
if (property_exists($schema, 'exclusiveMaximum')) {
if (!is_bool($schema->exclusiveMaximum)) {
throw new SchemaKeywordException(
$schema,
'exclusiveMaximum',
$schema->exclusiveMaximum,
"'exclusiveMaximum' keyword must be a boolean is 'maximum' keyword is present, " . gettype($schema->exclusiveMaximum) . " given"
);
}
$exclusive = $schema->exclusiveMaximum;
}
if ($exclusive && $data == $schema->maximum) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'exclusiveMaximum', [
'max' => $schema->maximum
]));
if ($bag->isFull()) {
return false;
}
} elseif ($data > $schema->maximum) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'maximum', [
'max' => $schema->maximum
]));
if ($bag->isFull()) {
return false;
}
}
} elseif (property_exists($schema, 'exclusiveMaximum')) {
if (!is_int($schema->exclusiveMaximum) && !is_float($schema->exclusiveMaximum)) {
throw new SchemaKeywordException(
$schema,
'exclusiveMaximum',
$schema->exclusiveMaximum,
"'exclusiveMaximum' keyword must be an integer or a float if 'maximum' keyword is not present, " . gettype($schema->exclusiveMaximum) . " given"
);
}
if ($data >= $schema->exclusiveMaximum) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'exclusiveMaximum', [
'max' => $schema->exclusiveMaximum
]));
if ($bag->isFull()) {
return false;
}
}
}
// multipleOf
if (property_exists($schema, 'multipleOf')) {
if (!is_int($schema->multipleOf) && !is_float($schema->multipleOf)) {
throw new SchemaKeywordException(
$schema,
'multipleOf',
$schema->multipleOf,
"'multipleOf' keyword must be an integer or a float, " . gettype($schema->multipleOf) . " given"
);
}
if ($schema->multipleOf <= 0) {
throw new SchemaKeywordException(
$schema,
'multipleOf',
$schema->multipleOf,
"'multipleOf' keyword must be greater than 0"
);
}
if (!$this->helper->isMultipleOf($data, $schema->multipleOf)) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'multipleOf', [
'divisor' => $schema->multipleOf
]));
if ($bag->isFull()) {
return false;
}
}
}
return $ok;
} | php | protected function validateNumber(/** @noinspection PhpUnusedParameterInspection */
&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag): bool
{
$ok = true;
// minimum, exclusiveMinimum
if (property_exists($schema, 'minimum')) {
if (!is_int($schema->minimum) && !is_float($schema->minimum)) {
throw new SchemaKeywordException(
$schema,
'minimum',
$schema->minimum,
"'minimum' keyword must be an integer or a float, " . gettype($schema->minimum) . " given"
);
}
$exclusive = false;
if (property_exists($schema, 'exclusiveMinimum')) {
if (!is_bool($schema->exclusiveMinimum)) {
throw new SchemaKeywordException(
$schema,
'exclusiveMinimum',
$schema->exclusiveMinimum,
"'exclusiveMinimum' keyword must be a boolean if 'minimum' keyword is present, " . gettype($schema->exclusiveMinimum) . " given"
);
}
$exclusive = $schema->exclusiveMinimum;
}
if ($exclusive && $data == $schema->minimum) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'exclusiveMinimum', [
'min' => $schema->minimum
]));
if ($bag->isFull()) {
return false;
}
} elseif ($data < $schema->minimum) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'minimum', [
'min' => $schema->minimum
]));
if ($bag->isFull()) {
return false;
}
}
} elseif (property_exists($schema, 'exclusiveMinimum')) {
if (!is_int($schema->exclusiveMinimum) && !is_float($schema->exclusiveMinimum)) {
throw new SchemaKeywordException(
$schema,
'exclusiveMinimum',
$schema->exclusiveMinimum,
"'exclusiveMinimum' keyword must be an integer or a float if 'minimum' keyword is not present, " . gettype($schema->exclusiveMinimum) . " given"
);
}
if ($data <= $schema->exclusiveMinimum) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'exclusiveMinimum', [
'min' => $schema->exclusiveMinimum
]));
if ($bag->isFull()) {
return false;
}
}
}
// maximum, exclusiveMaximum
if (property_exists($schema, 'maximum')) {
if (!is_int($schema->maximum) && !is_float($schema->maximum)) {
throw new SchemaKeywordException(
$schema,
'maximum',
$schema->maximum,
"'maximum' keyword must be an integer or a float, " . gettype($schema->maximum) . " given"
);
}
$exclusive = false;
if (property_exists($schema, 'exclusiveMaximum')) {
if (!is_bool($schema->exclusiveMaximum)) {
throw new SchemaKeywordException(
$schema,
'exclusiveMaximum',
$schema->exclusiveMaximum,
"'exclusiveMaximum' keyword must be a boolean is 'maximum' keyword is present, " . gettype($schema->exclusiveMaximum) . " given"
);
}
$exclusive = $schema->exclusiveMaximum;
}
if ($exclusive && $data == $schema->maximum) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'exclusiveMaximum', [
'max' => $schema->maximum
]));
if ($bag->isFull()) {
return false;
}
} elseif ($data > $schema->maximum) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'maximum', [
'max' => $schema->maximum
]));
if ($bag->isFull()) {
return false;
}
}
} elseif (property_exists($schema, 'exclusiveMaximum')) {
if (!is_int($schema->exclusiveMaximum) && !is_float($schema->exclusiveMaximum)) {
throw new SchemaKeywordException(
$schema,
'exclusiveMaximum',
$schema->exclusiveMaximum,
"'exclusiveMaximum' keyword must be an integer or a float if 'maximum' keyword is not present, " . gettype($schema->exclusiveMaximum) . " given"
);
}
if ($data >= $schema->exclusiveMaximum) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'exclusiveMaximum', [
'max' => $schema->exclusiveMaximum
]));
if ($bag->isFull()) {
return false;
}
}
}
// multipleOf
if (property_exists($schema, 'multipleOf')) {
if (!is_int($schema->multipleOf) && !is_float($schema->multipleOf)) {
throw new SchemaKeywordException(
$schema,
'multipleOf',
$schema->multipleOf,
"'multipleOf' keyword must be an integer or a float, " . gettype($schema->multipleOf) . " given"
);
}
if ($schema->multipleOf <= 0) {
throw new SchemaKeywordException(
$schema,
'multipleOf',
$schema->multipleOf,
"'multipleOf' keyword must be greater than 0"
);
}
if (!$this->helper->isMultipleOf($data, $schema->multipleOf)) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'multipleOf', [
'divisor' => $schema->multipleOf
]));
if ($bag->isFull()) {
return false;
}
}
}
return $ok;
} | [
"protected",
"function",
"validateNumber",
"(",
"/** @noinspection PhpUnusedParameterInspection */",
"&",
"$",
"document_data",
",",
"&",
"$",
"data",
",",
"array",
"$",
"data_pointer",
",",
"array",
"$",
"parent_data_pointer",
",",
"ISchema",
"$",
"document",
",",
... | Validates number/integer keywords
@param $document_data
@param $data
@param array $data_pointer
@param array $parent_data_pointer
@param ISchema $document
@param $schema
@param ValidationResult $bag
@return bool | [
"Validates",
"number",
"/",
"integer",
"keywords"
] | train | https://github.com/opis/json-schema/blob/91f2464d44ffbaa34c3ee24e3bb6330690025859/src/Validator.php#L1322-L1479 |
opis/json-schema | src/Validator.php | Validator.validateArray | protected function validateArray(&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag): bool
{
$ok = true;
// minItems
if (property_exists($schema, 'minItems')) {
if (!is_int($schema->minItems)) {
throw new SchemaKeywordException(
$schema,
'minItems',
$schema->minItems,
"'minItems' keyword must be an integer, " . gettype($schema->minItems) . " given"
);
}
if ($schema->minItems < 0) {
throw new SchemaKeywordException(
$schema,
'minItems',
$schema->minItems,
"'minItems' keyword must be positive, " . $schema->minItems . " given"
);
}
if (($count = count($data)) < $schema->minItems) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'minItems', [
'min' => $schema->minItems,
'count' => $count,
]));
if ($bag->isFull()) {
return false;
}
}
unset($count);
}
// maxItems
if (property_exists($schema, 'maxItems')) {
if (!is_int($schema->maxItems)) {
throw new SchemaKeywordException(
$schema,
'maxItems',
$schema->maxItems,
"'maxItems' keyword must be an integer, " . gettype($schema->maxItems) . " given"
);
}
if ($schema->maxItems < 0) {
throw new SchemaKeywordException(
$schema,
'maxItems',
$schema->maxItems,
"'maxItems' keyword must be positive, " . $schema->maxItems . " given"
);
}
if (($count = count($data)) > $schema->maxItems) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'maxItems', [
'max' => $schema->maxItems,
'count' => $count,
]));
if ($bag->isFull()) {
return false;
}
}
unset($count);
}
// uniqueItems
if (property_exists($schema, 'uniqueItems')) {
if (!is_bool($schema->uniqueItems)) {
throw new SchemaKeywordException(
$schema,
'uniqueItems',
$schema->uniqueItems,
"'uniqueItems' keyword must be a boolean, " . gettype($schema->uniqueItems) . " given"
);
}
if ($schema->uniqueItems) {
$valid = true;
$count = count($data);
$dup = null;
for ($i = 0; $i < $count - 1; $i++) {
for ($j = $i + 1; $j < $count; $j++) {
if ($this->helper->equals($data[$i], $data[$j])) {
$valid = false;
$dup = $data[$i];
break 2;
}
}
}
if (!$valid) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'uniqueItems', [
'duplicate' => $dup,
]));
if ($bag->isFull()) {
return false;
}
}
unset($valid, $count, $dup);
}
}
// contains
if (property_exists($schema, 'contains')) {
$valid = false;
$newbag = new ValidationResult(1);
$errors = [];
foreach ($data as $i => &$value) {
$data_pointer[] = $i;
$valid = $this->validateSchema($document_data, $value, $data_pointer, $parent_data_pointer, $document, $schema->contains, $newbag);
array_pop($data_pointer);
if ($valid) {
break;
}
$errors = array_merge($errors, $newbag->getErrors());
$newbag->clear();
}
unset($value, $newbag);
if (!$valid) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'contains', [], $errors));
if ($bag->isFull()) {
return false;
}
}
unset($valid, $errors);
}
// items, additionalItems
if (property_exists($schema, 'items')) {
if (is_array($schema->items)) {
$count = count($schema->items);
$data_count = count($data);
$max = min($count, $data_count);
for ($i = 0; $i < $max; $i++) {
$data_pointer[] = $i;
$valid = $this->validateSchema($document_data, $data[$i], $data_pointer, $parent_data_pointer, $document, $schema->items[$i], $bag);
array_pop($data_pointer);
if (!$valid) {
$ok = false;
if ($bag->isFull()) {
return false;
}
}
}
if ($max < $data_count && property_exists($schema, 'additionalItems')) {
if (!is_bool($schema->additionalItems) && !is_object($schema->additionalItems)) {
throw new SchemaKeywordException(
$schema,
'additionalItems',
$schema->additionalItems,
"'additionalItems' keyword must be a boolean or an object, " . gettype($schema->additionalItems) . " given"
);
}
for ($i = $max; $i < $data_count; $i++) {
$data_pointer[] = $i;
$valid = $this->validateSchema($document_data, $data[$i], $data_pointer, $parent_data_pointer, $document, $schema->additionalItems, $bag);
array_pop($data_pointer);
if (!$valid) {
$ok = false;
if ($bag->isFull()) {
return false;
}
}
}
}
unset($max, $count, $data_count);
} else {
$count = count($data);
for ($i = 0; $i < $count; $i++) {
$data_pointer[] = $i;
$valid = $this->validateSchema($document_data, $data[$i], $data_pointer, $parent_data_pointer, $document, $schema->items, $bag);
array_pop($data_pointer);
if (!$valid) {
$ok = false;
if ($bag->isFull()) {
return false;
}
}
}
}
}
return $ok;
} | php | protected function validateArray(&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag): bool
{
$ok = true;
// minItems
if (property_exists($schema, 'minItems')) {
if (!is_int($schema->minItems)) {
throw new SchemaKeywordException(
$schema,
'minItems',
$schema->minItems,
"'minItems' keyword must be an integer, " . gettype($schema->minItems) . " given"
);
}
if ($schema->minItems < 0) {
throw new SchemaKeywordException(
$schema,
'minItems',
$schema->minItems,
"'minItems' keyword must be positive, " . $schema->minItems . " given"
);
}
if (($count = count($data)) < $schema->minItems) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'minItems', [
'min' => $schema->minItems,
'count' => $count,
]));
if ($bag->isFull()) {
return false;
}
}
unset($count);
}
// maxItems
if (property_exists($schema, 'maxItems')) {
if (!is_int($schema->maxItems)) {
throw new SchemaKeywordException(
$schema,
'maxItems',
$schema->maxItems,
"'maxItems' keyword must be an integer, " . gettype($schema->maxItems) . " given"
);
}
if ($schema->maxItems < 0) {
throw new SchemaKeywordException(
$schema,
'maxItems',
$schema->maxItems,
"'maxItems' keyword must be positive, " . $schema->maxItems . " given"
);
}
if (($count = count($data)) > $schema->maxItems) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'maxItems', [
'max' => $schema->maxItems,
'count' => $count,
]));
if ($bag->isFull()) {
return false;
}
}
unset($count);
}
// uniqueItems
if (property_exists($schema, 'uniqueItems')) {
if (!is_bool($schema->uniqueItems)) {
throw new SchemaKeywordException(
$schema,
'uniqueItems',
$schema->uniqueItems,
"'uniqueItems' keyword must be a boolean, " . gettype($schema->uniqueItems) . " given"
);
}
if ($schema->uniqueItems) {
$valid = true;
$count = count($data);
$dup = null;
for ($i = 0; $i < $count - 1; $i++) {
for ($j = $i + 1; $j < $count; $j++) {
if ($this->helper->equals($data[$i], $data[$j])) {
$valid = false;
$dup = $data[$i];
break 2;
}
}
}
if (!$valid) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'uniqueItems', [
'duplicate' => $dup,
]));
if ($bag->isFull()) {
return false;
}
}
unset($valid, $count, $dup);
}
}
// contains
if (property_exists($schema, 'contains')) {
$valid = false;
$newbag = new ValidationResult(1);
$errors = [];
foreach ($data as $i => &$value) {
$data_pointer[] = $i;
$valid = $this->validateSchema($document_data, $value, $data_pointer, $parent_data_pointer, $document, $schema->contains, $newbag);
array_pop($data_pointer);
if ($valid) {
break;
}
$errors = array_merge($errors, $newbag->getErrors());
$newbag->clear();
}
unset($value, $newbag);
if (!$valid) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'contains', [], $errors));
if ($bag->isFull()) {
return false;
}
}
unset($valid, $errors);
}
// items, additionalItems
if (property_exists($schema, 'items')) {
if (is_array($schema->items)) {
$count = count($schema->items);
$data_count = count($data);
$max = min($count, $data_count);
for ($i = 0; $i < $max; $i++) {
$data_pointer[] = $i;
$valid = $this->validateSchema($document_data, $data[$i], $data_pointer, $parent_data_pointer, $document, $schema->items[$i], $bag);
array_pop($data_pointer);
if (!$valid) {
$ok = false;
if ($bag->isFull()) {
return false;
}
}
}
if ($max < $data_count && property_exists($schema, 'additionalItems')) {
if (!is_bool($schema->additionalItems) && !is_object($schema->additionalItems)) {
throw new SchemaKeywordException(
$schema,
'additionalItems',
$schema->additionalItems,
"'additionalItems' keyword must be a boolean or an object, " . gettype($schema->additionalItems) . " given"
);
}
for ($i = $max; $i < $data_count; $i++) {
$data_pointer[] = $i;
$valid = $this->validateSchema($document_data, $data[$i], $data_pointer, $parent_data_pointer, $document, $schema->additionalItems, $bag);
array_pop($data_pointer);
if (!$valid) {
$ok = false;
if ($bag->isFull()) {
return false;
}
}
}
}
unset($max, $count, $data_count);
} else {
$count = count($data);
for ($i = 0; $i < $count; $i++) {
$data_pointer[] = $i;
$valid = $this->validateSchema($document_data, $data[$i], $data_pointer, $parent_data_pointer, $document, $schema->items, $bag);
array_pop($data_pointer);
if (!$valid) {
$ok = false;
if ($bag->isFull()) {
return false;
}
}
}
}
}
return $ok;
} | [
"protected",
"function",
"validateArray",
"(",
"&",
"$",
"document_data",
",",
"&",
"$",
"data",
",",
"array",
"$",
"data_pointer",
",",
"array",
"$",
"parent_data_pointer",
",",
"ISchema",
"$",
"document",
",",
"$",
"schema",
",",
"ValidationResult",
"$",
"... | Validates array keywords
@param $document_data
@param $data
@param array $data_pointer
@param array $parent_data_pointer
@param ISchema $document
@param $schema
@param ValidationResult $bag
@return bool | [
"Validates",
"array",
"keywords"
] | train | https://github.com/opis/json-schema/blob/91f2464d44ffbaa34c3ee24e3bb6330690025859/src/Validator.php#L1492-L1676 |
opis/json-schema | src/Validator.php | Validator.validateObject | protected function validateObject(&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag, array &$defaults = null): bool
{
$ok = true;
// required
if (property_exists($schema, 'required')) {
if (!is_array($schema->required)) {
throw new SchemaKeywordException(
$schema,
'required',
$schema->required,
"'required' keyword must be an array, " . gettype($schema->required) . " given"
);
}
foreach ($schema->required as $prop) {
if (!is_string($prop)) {
throw new SchemaKeywordException(
$schema,
'required',
$schema->required,
"'required' keyword items must be strings, found " . gettype($prop)
);
}
if (!property_exists($data, $prop) && !($defaults && array_key_exists($prop, $defaults))) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'required', [
'missing' => $prop,
]));
if ($bag->isFull()) {
return false;
}
}
}
}
// dependencies
if (property_exists($schema, 'dependencies')) {
if (!is_object($schema->dependencies)) {
throw new SchemaKeywordException(
$schema,
'dependencies',
$schema->dependencies,
"'dependencies' keyword must be an object, " . gettype($schema->dependencies) . " given"
);
}
foreach ($schema->dependencies as $name => &$value) {
if (!property_exists($data, $name)) {
unset($value);
continue;
}
if (is_array($value)) {
foreach ($value as $prop) {
if (!is_string($prop)) {
throw new SchemaKeywordException(
$schema,
'dependencies',
$schema->dependencies,
"'dependencies' keyword items can only be array of strings, objects or booleans, found array with " . gettype($prop)
);
}
if (!property_exists($data, $prop) && !($defaults && array_key_exists($prop, $defaults))) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'dependencies', [
'missing' => $prop,
]));
if ($bag->isFull()) {
return false;
}
}
}
unset($prop, $value);
continue;
}
if (!is_bool($value) && !is_object($value)) {
throw new SchemaKeywordException(
$schema,
'dependencies',
$schema->dependencies,
"'dependencies' keyword items can only be array of strings, objects or booleans, found " . gettype($value)
);
}
$this->setObjectDefaults($data, $defaults);
$valid = $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $value, $bag);
if (!$valid) {
$ok = false;
if ($bag->isFull()) {
return false;
}
}
unset($valid, $value);
}
}
$properties = array_keys(get_object_vars($data));
// minProperties
if (property_exists($schema, 'minProperties')) {
if (!is_int($schema->minProperties)) {
throw new SchemaKeywordException(
$schema,
'minProperties',
$schema->minProperties,
"'minProperties' keyword must be an integer, " . gettype($schema->minProperties) . " given"
);
}
if ($schema->minProperties < 0) {
throw new SchemaKeywordException(
$schema,
'minProperties',
$schema->minProperties,
"'minProperties' keyword must be positive, " . $schema->minProperties . " given"
);
}
$count = count($properties);
if ($defaults) {
$count += count($defaults);
}
if ($count < $schema->minProperties) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'minProperties', [
'min' => $schema->minProperties,
'count' => $count,
]));
if ($bag->isFull()) {
return false;
}
}
unset($count);
}
// maxProperties
if (property_exists($schema, 'maxProperties')) {
if (!is_int($schema->maxProperties)) {
throw new SchemaKeywordException(
$schema,
'maxProperties',
$schema->maxProperties,
"'maxProperties' keyword must be an integer, " . gettype($schema->maxProperties) . " given"
);
}
if ($schema->maxProperties < 0) {
throw new SchemaKeywordException(
$schema,
'maxProperties',
$schema->maxProperties,
"'maxProperties' keyword must be positive, " . $schema->maxProperties . " given"
);
}
$count = count($properties);
if ($defaults) {
$count += count($defaults);
}
if ($count > $schema->maxProperties) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'maxProperties', [
'min' => $schema->maxProperties,
'count' => $count,
]));
if ($bag->isFull()) {
return false;
}
}
unset($count);
}
// propertyNames
if (property_exists($schema, 'propertyNames')) {
if (!is_bool($schema->propertyNames) && !is_object($schema->propertyNames)) {
throw new SchemaKeywordException(
$schema,
'propertyNames',
$schema->propertyNames,
"'propertyNames' keyword must be a boolean or an object, " . gettype($schema->propertyNames) . " given"
);
}
$newbag = $bag->createByDiff();
foreach ($properties as $property) {
if (!$this->validateSchema($document_data, $property, $data_pointer, $parent_data_pointer, $document, $schema->propertyNames, $newbag)) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'propertyNames', [
'property' => $property
], $newbag->getErrors()));
if ($bag->isFull()) {
return false;
}
}
$newbag->clear();
}
unset($newbag);
}
$checked_properties = [];
// properties
if (property_exists($schema, 'properties')) {
if (!is_object($schema->properties)) {
throw new SchemaKeywordException(
$schema,
'properties',
$schema->properties,
"'properties' keyword must be an object, " . gettype($schema->properties) . " given"
);
}
foreach ($schema->properties as $name => &$property) {
if (!is_bool($property) && !is_object($property)) {
throw new SchemaKeywordException(
$schema,
'properties',
$schema->properties,
"'properties' keyword items must be booleans or objects, found " . gettype($property)
);
}
$checked_properties[] = $name;
if (property_exists($data, $name)) {
$data_pointer[] = $name;
$valid = $this->validateSchema($document_data, $data->{$name}, $data_pointer, $parent_data_pointer, $document, $property, $bag);
array_pop($data_pointer);
if (!$valid) {
$ok = false;
if ($bag->isFull()) {
return false;
}
}
}
unset($property, $name);
}
}
// patternProperties
if (property_exists($schema, 'patternProperties')) {
if (!is_object($schema->patternProperties)) {
throw new SchemaKeywordException(
$schema,
'patternProperties',
$schema->patternProperties,
"'patternProperties' keyword must be an object, " . gettype($schema->patternProperties) . " given"
);
}
$newbag = $bag->createByDiff();
foreach ($schema->patternProperties as $pattern => &$property_schema) {
$regex = self::BELL . $pattern . self::BELL . 'u';
foreach ($properties as $name) {
$match = @preg_match($regex, $name);
if ($match === false) {
throw new SchemaKeywordException(
$schema,
'patternProperties',
$schema->patternProperties,
"'patternProperties' keyword must have as properties valid regex expressions, found " . $pattern
);
}
if (!$match) {
continue;
}
if (!in_array($name, $checked_properties)) {
$checked_properties[] = $name;
}
$data_pointer[] = $name;
$valid = $this->validateSchema($document_data, $data->{$name}, $data_pointer, $parent_data_pointer, $document, $property_schema, $newbag);
array_pop($data_pointer);
if (!$valid && $newbag->isFull()) {
break 2;
}
}
}
unset($property_schema, $regex);
if ($newbag->hasErrors()) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'patternProperties', [], $newbag->getErrors()));
if ($bag->isFull()) {
return false;
}
}
unset($newbag);
}
// additionalProperties
if (property_exists($schema, 'additionalProperties')) {
if (!is_bool($schema->additionalProperties) && !is_object($schema->additionalProperties)) {
throw new SchemaKeywordException(
$schema,
'additionalProperties',
$schema->additionalProperties,
"'additionalProperties' keyword must be a boolean or an object, " . gettype($schema->additionalProperties) . " given"
);
}
$newbag = $bag->createByDiff();
foreach (array_diff($properties, $checked_properties) as $property) {
$data_pointer[] = $property;
$valid = $this->validateSchema($document_data, $data->{$property}, $data_pointer, $parent_data_pointer, $document, $schema->additionalProperties, $newbag);
array_pop($data_pointer);
unset($property);
if (!$valid && $newbag->isFull()) {
break;
}
}
if ($newbag->hasErrors()) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'additionalProperties', [], $newbag->getErrors()));
if ($bag->isFull()) {
return false;
}
}
unset($newbag);
}
// set defaults
$this->setObjectDefaults($data, $defaults);
return $ok;
} | php | protected function validateObject(&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, $schema, ValidationResult $bag, array &$defaults = null): bool
{
$ok = true;
// required
if (property_exists($schema, 'required')) {
if (!is_array($schema->required)) {
throw new SchemaKeywordException(
$schema,
'required',
$schema->required,
"'required' keyword must be an array, " . gettype($schema->required) . " given"
);
}
foreach ($schema->required as $prop) {
if (!is_string($prop)) {
throw new SchemaKeywordException(
$schema,
'required',
$schema->required,
"'required' keyword items must be strings, found " . gettype($prop)
);
}
if (!property_exists($data, $prop) && !($defaults && array_key_exists($prop, $defaults))) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'required', [
'missing' => $prop,
]));
if ($bag->isFull()) {
return false;
}
}
}
}
// dependencies
if (property_exists($schema, 'dependencies')) {
if (!is_object($schema->dependencies)) {
throw new SchemaKeywordException(
$schema,
'dependencies',
$schema->dependencies,
"'dependencies' keyword must be an object, " . gettype($schema->dependencies) . " given"
);
}
foreach ($schema->dependencies as $name => &$value) {
if (!property_exists($data, $name)) {
unset($value);
continue;
}
if (is_array($value)) {
foreach ($value as $prop) {
if (!is_string($prop)) {
throw new SchemaKeywordException(
$schema,
'dependencies',
$schema->dependencies,
"'dependencies' keyword items can only be array of strings, objects or booleans, found array with " . gettype($prop)
);
}
if (!property_exists($data, $prop) && !($defaults && array_key_exists($prop, $defaults))) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'dependencies', [
'missing' => $prop,
]));
if ($bag->isFull()) {
return false;
}
}
}
unset($prop, $value);
continue;
}
if (!is_bool($value) && !is_object($value)) {
throw new SchemaKeywordException(
$schema,
'dependencies',
$schema->dependencies,
"'dependencies' keyword items can only be array of strings, objects or booleans, found " . gettype($value)
);
}
$this->setObjectDefaults($data, $defaults);
$valid = $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $value, $bag);
if (!$valid) {
$ok = false;
if ($bag->isFull()) {
return false;
}
}
unset($valid, $value);
}
}
$properties = array_keys(get_object_vars($data));
// minProperties
if (property_exists($schema, 'minProperties')) {
if (!is_int($schema->minProperties)) {
throw new SchemaKeywordException(
$schema,
'minProperties',
$schema->minProperties,
"'minProperties' keyword must be an integer, " . gettype($schema->minProperties) . " given"
);
}
if ($schema->minProperties < 0) {
throw new SchemaKeywordException(
$schema,
'minProperties',
$schema->minProperties,
"'minProperties' keyword must be positive, " . $schema->minProperties . " given"
);
}
$count = count($properties);
if ($defaults) {
$count += count($defaults);
}
if ($count < $schema->minProperties) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'minProperties', [
'min' => $schema->minProperties,
'count' => $count,
]));
if ($bag->isFull()) {
return false;
}
}
unset($count);
}
// maxProperties
if (property_exists($schema, 'maxProperties')) {
if (!is_int($schema->maxProperties)) {
throw new SchemaKeywordException(
$schema,
'maxProperties',
$schema->maxProperties,
"'maxProperties' keyword must be an integer, " . gettype($schema->maxProperties) . " given"
);
}
if ($schema->maxProperties < 0) {
throw new SchemaKeywordException(
$schema,
'maxProperties',
$schema->maxProperties,
"'maxProperties' keyword must be positive, " . $schema->maxProperties . " given"
);
}
$count = count($properties);
if ($defaults) {
$count += count($defaults);
}
if ($count > $schema->maxProperties) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'maxProperties', [
'min' => $schema->maxProperties,
'count' => $count,
]));
if ($bag->isFull()) {
return false;
}
}
unset($count);
}
// propertyNames
if (property_exists($schema, 'propertyNames')) {
if (!is_bool($schema->propertyNames) && !is_object($schema->propertyNames)) {
throw new SchemaKeywordException(
$schema,
'propertyNames',
$schema->propertyNames,
"'propertyNames' keyword must be a boolean or an object, " . gettype($schema->propertyNames) . " given"
);
}
$newbag = $bag->createByDiff();
foreach ($properties as $property) {
if (!$this->validateSchema($document_data, $property, $data_pointer, $parent_data_pointer, $document, $schema->propertyNames, $newbag)) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'propertyNames', [
'property' => $property
], $newbag->getErrors()));
if ($bag->isFull()) {
return false;
}
}
$newbag->clear();
}
unset($newbag);
}
$checked_properties = [];
// properties
if (property_exists($schema, 'properties')) {
if (!is_object($schema->properties)) {
throw new SchemaKeywordException(
$schema,
'properties',
$schema->properties,
"'properties' keyword must be an object, " . gettype($schema->properties) . " given"
);
}
foreach ($schema->properties as $name => &$property) {
if (!is_bool($property) && !is_object($property)) {
throw new SchemaKeywordException(
$schema,
'properties',
$schema->properties,
"'properties' keyword items must be booleans or objects, found " . gettype($property)
);
}
$checked_properties[] = $name;
if (property_exists($data, $name)) {
$data_pointer[] = $name;
$valid = $this->validateSchema($document_data, $data->{$name}, $data_pointer, $parent_data_pointer, $document, $property, $bag);
array_pop($data_pointer);
if (!$valid) {
$ok = false;
if ($bag->isFull()) {
return false;
}
}
}
unset($property, $name);
}
}
// patternProperties
if (property_exists($schema, 'patternProperties')) {
if (!is_object($schema->patternProperties)) {
throw new SchemaKeywordException(
$schema,
'patternProperties',
$schema->patternProperties,
"'patternProperties' keyword must be an object, " . gettype($schema->patternProperties) . " given"
);
}
$newbag = $bag->createByDiff();
foreach ($schema->patternProperties as $pattern => &$property_schema) {
$regex = self::BELL . $pattern . self::BELL . 'u';
foreach ($properties as $name) {
$match = @preg_match($regex, $name);
if ($match === false) {
throw new SchemaKeywordException(
$schema,
'patternProperties',
$schema->patternProperties,
"'patternProperties' keyword must have as properties valid regex expressions, found " . $pattern
);
}
if (!$match) {
continue;
}
if (!in_array($name, $checked_properties)) {
$checked_properties[] = $name;
}
$data_pointer[] = $name;
$valid = $this->validateSchema($document_data, $data->{$name}, $data_pointer, $parent_data_pointer, $document, $property_schema, $newbag);
array_pop($data_pointer);
if (!$valid && $newbag->isFull()) {
break 2;
}
}
}
unset($property_schema, $regex);
if ($newbag->hasErrors()) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'patternProperties', [], $newbag->getErrors()));
if ($bag->isFull()) {
return false;
}
}
unset($newbag);
}
// additionalProperties
if (property_exists($schema, 'additionalProperties')) {
if (!is_bool($schema->additionalProperties) && !is_object($schema->additionalProperties)) {
throw new SchemaKeywordException(
$schema,
'additionalProperties',
$schema->additionalProperties,
"'additionalProperties' keyword must be a boolean or an object, " . gettype($schema->additionalProperties) . " given"
);
}
$newbag = $bag->createByDiff();
foreach (array_diff($properties, $checked_properties) as $property) {
$data_pointer[] = $property;
$valid = $this->validateSchema($document_data, $data->{$property}, $data_pointer, $parent_data_pointer, $document, $schema->additionalProperties, $newbag);
array_pop($data_pointer);
unset($property);
if (!$valid && $newbag->isFull()) {
break;
}
}
if ($newbag->hasErrors()) {
$ok = false;
$bag->addError(new ValidationError($data, $data_pointer, $parent_data_pointer, $schema, 'additionalProperties', [], $newbag->getErrors()));
if ($bag->isFull()) {
return false;
}
}
unset($newbag);
}
// set defaults
$this->setObjectDefaults($data, $defaults);
return $ok;
} | [
"protected",
"function",
"validateObject",
"(",
"&",
"$",
"document_data",
",",
"&",
"$",
"data",
",",
"array",
"$",
"data_pointer",
",",
"array",
"$",
"parent_data_pointer",
",",
"ISchema",
"$",
"document",
",",
"$",
"schema",
",",
"ValidationResult",
"$",
... | Validates object keywords
@param $document_data
@param $data
@param array $data_pointer
@param array $parent_data_pointer
@param ISchema $document
@param $schema
@param ValidationResult $bag
@param array|null $defaults
@return bool | [
"Validates",
"object",
"keywords"
] | train | https://github.com/opis/json-schema/blob/91f2464d44ffbaa34c3ee24e3bb6330690025859/src/Validator.php#L1690-L2004 |
opis/json-schema | src/Validator.php | Validator.deepClone | protected function deepClone($vars)
{
if (is_object($vars)) {
$vars = get_object_vars($vars);
foreach ($vars as $key => $value) {
if (is_array($value) || is_object($value)) {
$vars[$key] = $this->deepClone($value);
}
unset($value);
}
return (object)$vars;
}
if (!is_array($vars)) {
return $vars;
}
foreach ($vars as &$value) {
if (is_array($value) || is_object($value)) {
$value = $this->deepClone($value);
}
unset($value);
}
return $vars;
} | php | protected function deepClone($vars)
{
if (is_object($vars)) {
$vars = get_object_vars($vars);
foreach ($vars as $key => $value) {
if (is_array($value) || is_object($value)) {
$vars[$key] = $this->deepClone($value);
}
unset($value);
}
return (object)$vars;
}
if (!is_array($vars)) {
return $vars;
}
foreach ($vars as &$value) {
if (is_array($value) || is_object($value)) {
$value = $this->deepClone($value);
}
unset($value);
}
return $vars;
} | [
"protected",
"function",
"deepClone",
"(",
"$",
"vars",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"vars",
")",
")",
"{",
"$",
"vars",
"=",
"get_object_vars",
"(",
"$",
"vars",
")",
";",
"foreach",
"(",
"$",
"vars",
"as",
"$",
"key",
"=>",
"$",
... | Clones a variable in depth
@param $vars
@return mixed | [
"Clones",
"a",
"variable",
"in",
"depth"
] | train | https://github.com/opis/json-schema/blob/91f2464d44ffbaa34c3ee24e3bb6330690025859/src/Validator.php#L2060-L2082 |
opis/json-schema | src/Validator.php | Validator.resolveVars | protected function resolveVars(&$vars, &$data, array &$data_pointer = [])
{
if (is_object($vars)) {
if (property_exists($vars, '$ref') && is_string($vars->{'$ref'})) {
$ref = $vars->{'$ref'};
$relative = JsonPointer::parseRelativePointer($ref, true);
if ($relative === null) {
$resolved = JsonPointer::getDataByPointer($data, $ref, $this, false);
} else {
if (!JsonPointer::isEscapedPointer($ref)) {
throw new InvalidJsonPointerException($ref);
}
$resolved = JsonPointer::getDataByRelativePointer($data, $relative, $data_pointer, $this);
}
if ($resolved === $this) {
throw new InvalidJsonPointerException($ref);
}
if (is_array($resolved) && property_exists($vars, '$each') && is_object($vars->{'$each'})) {
$pointer = $relative['pointer'] ?? [];
foreach ($resolved as $index => &$item) {
$copy = $this->deepClone($vars->{'$each'});
$pointer[] = $index;
$this->resolveVars($copy,$data,$pointer);
array_pop($pointer);
$item = $copy;
unset($copy, $item, $index);
}
unset($pointer);
}
$vars = $resolved;
return;
}
} elseif (!is_array($vars)) {
return;
}
foreach ($vars as $name => &$var) {
if (is_array($var) || is_object($var)) {
$this->resolveVars($var, $data, $data_pointer);
}
unset($var);
}
} | php | protected function resolveVars(&$vars, &$data, array &$data_pointer = [])
{
if (is_object($vars)) {
if (property_exists($vars, '$ref') && is_string($vars->{'$ref'})) {
$ref = $vars->{'$ref'};
$relative = JsonPointer::parseRelativePointer($ref, true);
if ($relative === null) {
$resolved = JsonPointer::getDataByPointer($data, $ref, $this, false);
} else {
if (!JsonPointer::isEscapedPointer($ref)) {
throw new InvalidJsonPointerException($ref);
}
$resolved = JsonPointer::getDataByRelativePointer($data, $relative, $data_pointer, $this);
}
if ($resolved === $this) {
throw new InvalidJsonPointerException($ref);
}
if (is_array($resolved) && property_exists($vars, '$each') && is_object($vars->{'$each'})) {
$pointer = $relative['pointer'] ?? [];
foreach ($resolved as $index => &$item) {
$copy = $this->deepClone($vars->{'$each'});
$pointer[] = $index;
$this->resolveVars($copy,$data,$pointer);
array_pop($pointer);
$item = $copy;
unset($copy, $item, $index);
}
unset($pointer);
}
$vars = $resolved;
return;
}
} elseif (!is_array($vars)) {
return;
}
foreach ($vars as $name => &$var) {
if (is_array($var) || is_object($var)) {
$this->resolveVars($var, $data, $data_pointer);
}
unset($var);
}
} | [
"protected",
"function",
"resolveVars",
"(",
"&",
"$",
"vars",
",",
"&",
"$",
"data",
",",
"array",
"&",
"$",
"data_pointer",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"vars",
")",
")",
"{",
"if",
"(",
"property_exists",
"(",
"$",
... | Resolves $vars
@param $vars
@param $data
@param array $data_pointer | [
"Resolves",
"$vars"
] | train | https://github.com/opis/json-schema/blob/91f2464d44ffbaa34c3ee24e3bb6330690025859/src/Validator.php#L2090-L2132 |
php-enqueue/enqueue-bundle | Profiler/MessageQueueCollector.php | MessageQueueCollector.collect | public function collect(Request $request, Response $response, \Exception $exception = null)
{
$this->data = [];
foreach ($this->producers as $name => $producer) {
if ($producer instanceof TraceableProducer) {
$this->data[$name] = $producer->getTraces();
}
}
} | php | public function collect(Request $request, Response $response, \Exception $exception = null)
{
$this->data = [];
foreach ($this->producers as $name => $producer) {
if ($producer instanceof TraceableProducer) {
$this->data[$name] = $producer->getTraces();
}
}
} | [
"public",
"function",
"collect",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
",",
"\\",
"Exception",
"$",
"exception",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"data",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"pro... | {@inheritdoc} | [
"{"
] | train | https://github.com/php-enqueue/enqueue-bundle/blob/12e771664235fff68cd70a2c78206c499d9241d3/Profiler/MessageQueueCollector.php#L28-L37 |
php-enqueue/enqueue-bundle | Profiler/MessageQueueCollector.php | MessageQueueCollector.prettyPrintPriority | public function prettyPrintPriority($priority)
{
$map = [
MessagePriority::VERY_LOW => 'very low',
MessagePriority::LOW => 'low',
MessagePriority::NORMAL => 'normal',
MessagePriority::HIGH => 'high',
MessagePriority::VERY_HIGH => 'very high',
];
return isset($map[$priority]) ? $map[$priority] : $priority;
} | php | public function prettyPrintPriority($priority)
{
$map = [
MessagePriority::VERY_LOW => 'very low',
MessagePriority::LOW => 'low',
MessagePriority::NORMAL => 'normal',
MessagePriority::HIGH => 'high',
MessagePriority::VERY_HIGH => 'very high',
];
return isset($map[$priority]) ? $map[$priority] : $priority;
} | [
"public",
"function",
"prettyPrintPriority",
"(",
"$",
"priority",
")",
"{",
"$",
"map",
"=",
"[",
"MessagePriority",
"::",
"VERY_LOW",
"=>",
"'very low'",
",",
"MessagePriority",
"::",
"LOW",
"=>",
"'low'",
",",
"MessagePriority",
"::",
"NORMAL",
"=>",
"'norm... | @param string $priority
@return string | [
"@param",
"string",
"$priority"
] | train | https://github.com/php-enqueue/enqueue-bundle/blob/12e771664235fff68cd70a2c78206c499d9241d3/Profiler/MessageQueueCollector.php#L62-L73 |
sonata-project/SonataCoreBundle | src/CoreBundle/Form/EventListener/ResizeFormListener.php | ResizeFormListener.preBind | public function preBind(FormEvent $event)
{
// BC prevention for class extending this one.
if (self::class !== \get_called_class()) {
@trigger_error(
__METHOD__.' method is deprecated since 2.3 and will be renamed in 4.0.'
.' Use '.__CLASS__.'::preSubmit instead.',
E_USER_DEPRECATED
);
}
$this->preSubmit($event);
} | php | public function preBind(FormEvent $event)
{
// BC prevention for class extending this one.
if (self::class !== \get_called_class()) {
@trigger_error(
__METHOD__.' method is deprecated since 2.3 and will be renamed in 4.0.'
.' Use '.__CLASS__.'::preSubmit instead.',
E_USER_DEPRECATED
);
}
$this->preSubmit($event);
} | [
"public",
"function",
"preBind",
"(",
"FormEvent",
"$",
"event",
")",
"{",
"// BC prevention for class extending this one.",
"if",
"(",
"self",
"::",
"class",
"!==",
"\\",
"get_called_class",
"(",
")",
")",
"{",
"@",
"trigger_error",
"(",
"__METHOD__",
".",
"' m... | NEXT_MAJOR: remove this method.
@deprecated Since version 2.3, to be renamed in 4.0.
Use {@link preSubmit} instead | [
"NEXT_MAJOR",
":",
"remove",
"this",
"method",
"."
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/CoreBundle/Form/EventListener/ResizeFormListener.php#L45-L57 |
sonata-project/SonataCoreBundle | src/CoreBundle/Form/EventListener/ResizeFormListener.php | ResizeFormListener.onBind | public function onBind(FormEvent $event)
{
// BC prevention for class extending this one.
if (self::class !== \get_called_class()) {
@trigger_error(
__METHOD__.' is deprecated since 2.3 and will be renamed in 4.0.'
.' Use '.__CLASS__.'::onSubmit instead.',
E_USER_DEPRECATED
);
}
$this->onSubmit($event);
} | php | public function onBind(FormEvent $event)
{
// BC prevention for class extending this one.
if (self::class !== \get_called_class()) {
@trigger_error(
__METHOD__.' is deprecated since 2.3 and will be renamed in 4.0.'
.' Use '.__CLASS__.'::onSubmit instead.',
E_USER_DEPRECATED
);
}
$this->onSubmit($event);
} | [
"public",
"function",
"onBind",
"(",
"FormEvent",
"$",
"event",
")",
"{",
"// BC prevention for class extending this one.",
"if",
"(",
"self",
"::",
"class",
"!==",
"\\",
"get_called_class",
"(",
")",
")",
"{",
"@",
"trigger_error",
"(",
"__METHOD__",
".",
"' is... | NEXT_MAJOR: remove this method.
@deprecated Since version 2.3, to be removed in 4.0.
Use {@link onSubmit} instead | [
"NEXT_MAJOR",
":",
"remove",
"this",
"method",
"."
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/CoreBundle/Form/EventListener/ResizeFormListener.php#L65-L77 |
sonata-project/SonataCoreBundle | src/CoreBundle/Twig/Extension/FlashMessageExtension.php | FlashMessageExtension.getFlashMessages | public function getFlashMessages($type, $domain = null)
{
@trigger_error(
'Method "FlashMessageExtension::getFlashMessages()" is deprecated since SonataCoreBundle 3.11.0 and will'.
' be removed in 4.0. Use the FlashMessageRuntime instead.',
E_USER_DEPRECATED
);
return $this->flashManager->get($type, $domain);
} | php | public function getFlashMessages($type, $domain = null)
{
@trigger_error(
'Method "FlashMessageExtension::getFlashMessages()" is deprecated since SonataCoreBundle 3.11.0 and will'.
' be removed in 4.0. Use the FlashMessageRuntime instead.',
E_USER_DEPRECATED
);
return $this->flashManager->get($type, $domain);
} | [
"public",
"function",
"getFlashMessages",
"(",
"$",
"type",
",",
"$",
"domain",
"=",
"null",
")",
"{",
"@",
"trigger_error",
"(",
"'Method \"FlashMessageExtension::getFlashMessages()\" is deprecated since SonataCoreBundle 3.11.0 and will'",
".",
"' be removed in 4.0. Use the Flas... | Returns flash messages handled by Sonata core flash manager.
@param string $type Type of flash message
@param string $domain Translation domain to use
@return string
@deprecated since 3.11.0, to be removed in 4.0. Use the FlashMessageRuntime instead. | [
"Returns",
"flash",
"messages",
"handled",
"by",
"Sonata",
"core",
"flash",
"manager",
"."
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/CoreBundle/Twig/Extension/FlashMessageExtension.php#L75-L84 |
sonata-project/SonataCoreBundle | src/Form/Validator/ErrorElement.php | ErrorElement.with | public function with($name, $key = false)
{
$key = $key ? $name.'.'.$key : $name;
$this->stack[] = $key;
$this->current = implode('.', $this->stack);
if (!isset($this->propertyPaths[$this->current])) {
$this->propertyPaths[$this->current] = new PropertyPath($this->current);
}
return $this;
} | php | public function with($name, $key = false)
{
$key = $key ? $name.'.'.$key : $name;
$this->stack[] = $key;
$this->current = implode('.', $this->stack);
if (!isset($this->propertyPaths[$this->current])) {
$this->propertyPaths[$this->current] = new PropertyPath($this->current);
}
return $this;
} | [
"public",
"function",
"with",
"(",
"$",
"name",
",",
"$",
"key",
"=",
"false",
")",
"{",
"$",
"key",
"=",
"$",
"key",
"?",
"$",
"name",
".",
"'.'",
".",
"$",
"key",
":",
"$",
"name",
";",
"$",
"this",
"->",
"stack",
"[",
"]",
"=",
"$",
"key... | @param string $name
@param bool $key
@return ErrorElement | [
"@param",
"string",
"$name",
"@param",
"bool",
"$key"
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/Form/Validator/ErrorElement.php#L129-L141 |
sonata-project/SonataCoreBundle | src/Form/Validator/ErrorElement.php | ErrorElement.addViolation | public function addViolation($message, $parameters = [], $value = null)
{
if (\is_array($message)) {
$value = $message[2] ?? $value;
$parameters = isset($message[1]) ? (array) $message[1] : [];
$message = $message[0] ?? 'error';
}
$subPath = (string) $this->getCurrentPropertyPath();
$translationDomain = self::DEFAULT_TRANSLATION_DOMAIN;
// NEXT_MAJOR: Remove this hack
if (\func_num_args() >= 4) {
$arg = func_get_arg(3);
if ((\is_string($arg))) {
$translationDomain = $arg;
}
}
if ($this->context instanceof LegacyExecutionContextInterface) {
$this->context->addViolationAt($subPath, $message, $parameters, $value);
} else {
$this->context->buildViolation($message)
->atPath($subPath)
->setParameters($parameters)
->setTranslationDomain($translationDomain)
->setInvalidValue($value)
->addViolation();
}
$this->errors[] = [$message, $parameters, $value];
return $this;
} | php | public function addViolation($message, $parameters = [], $value = null)
{
if (\is_array($message)) {
$value = $message[2] ?? $value;
$parameters = isset($message[1]) ? (array) $message[1] : [];
$message = $message[0] ?? 'error';
}
$subPath = (string) $this->getCurrentPropertyPath();
$translationDomain = self::DEFAULT_TRANSLATION_DOMAIN;
// NEXT_MAJOR: Remove this hack
if (\func_num_args() >= 4) {
$arg = func_get_arg(3);
if ((\is_string($arg))) {
$translationDomain = $arg;
}
}
if ($this->context instanceof LegacyExecutionContextInterface) {
$this->context->addViolationAt($subPath, $message, $parameters, $value);
} else {
$this->context->buildViolation($message)
->atPath($subPath)
->setParameters($parameters)
->setTranslationDomain($translationDomain)
->setInvalidValue($value)
->addViolation();
}
$this->errors[] = [$message, $parameters, $value];
return $this;
} | [
"public",
"function",
"addViolation",
"(",
"$",
"message",
",",
"$",
"parameters",
"=",
"[",
"]",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"\\",
"is_array",
"(",
"$",
"message",
")",
")",
"{",
"$",
"value",
"=",
"$",
"message",
"[",
"... | @param string|array $message
@param array $parameters
@param ?mixed $value
@param ?string $translationDomain
@return ErrorElement | [
"@param",
"string|array",
"$message",
"@param",
"array",
"$parameters",
"@param",
"?mixed",
"$value",
"@param",
"?string",
"$translationDomain"
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/Form/Validator/ErrorElement.php#L183-L216 |
sonata-project/SonataCoreBundle | src/Form/Validator/ErrorElement.php | ErrorElement.getValue | protected function getValue()
{
if ('' === $this->current) {
return $this->subject;
}
$propertyAccessor = PropertyAccess::createPropertyAccessor();
return $propertyAccessor->getValue($this->subject, $this->getCurrentPropertyPath());
} | php | protected function getValue()
{
if ('' === $this->current) {
return $this->subject;
}
$propertyAccessor = PropertyAccess::createPropertyAccessor();
return $propertyAccessor->getValue($this->subject, $this->getCurrentPropertyPath());
} | [
"protected",
"function",
"getValue",
"(",
")",
"{",
"if",
"(",
"''",
"===",
"$",
"this",
"->",
"current",
")",
"{",
"return",
"$",
"this",
"->",
"subject",
";",
"}",
"$",
"propertyAccessor",
"=",
"PropertyAccess",
"::",
"createPropertyAccessor",
"(",
")",
... | Return the value linked to.
@return mixed | [
"Return",
"the",
"value",
"linked",
"to",
"."
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/Form/Validator/ErrorElement.php#L244-L253 |
sonata-project/SonataCoreBundle | src/Form/Validator/ErrorElement.php | ErrorElement.newConstraint | protected function newConstraint($name, array $options = [])
{
if (false !== strpos($name, '\\') && class_exists($name)) {
$className = (string) $name;
} else {
$className = 'Symfony\\Component\\Validator\\Constraints\\'.$name;
}
return new $className($options);
} | php | protected function newConstraint($name, array $options = [])
{
if (false !== strpos($name, '\\') && class_exists($name)) {
$className = (string) $name;
} else {
$className = 'Symfony\\Component\\Validator\\Constraints\\'.$name;
}
return new $className($options);
} | [
"protected",
"function",
"newConstraint",
"(",
"$",
"name",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"false",
"!==",
"strpos",
"(",
"$",
"name",
",",
"'\\\\'",
")",
"&&",
"class_exists",
"(",
"$",
"name",
")",
")",
"{",
"$"... | @param string $name
@return | [
"@param",
"string",
"$name"
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/Form/Validator/ErrorElement.php#L260-L269 |
sonata-project/SonataCoreBundle | src/Serializer/BaseSerializerHandler.php | BaseSerializerHandler.serializeObjectToId | public function serializeObjectToId(VisitorInterface $visitor, $data, array $type, Context $context)
{
$className = $this->manager->getClass();
if ($data instanceof $className) {
return $visitor->visitInteger($data->getId(), $type, $context);
}
} | php | public function serializeObjectToId(VisitorInterface $visitor, $data, array $type, Context $context)
{
$className = $this->manager->getClass();
if ($data instanceof $className) {
return $visitor->visitInteger($data->getId(), $type, $context);
}
} | [
"public",
"function",
"serializeObjectToId",
"(",
"VisitorInterface",
"$",
"visitor",
",",
"$",
"data",
",",
"array",
"$",
"type",
",",
"Context",
"$",
"context",
")",
"{",
"$",
"className",
"=",
"$",
"this",
"->",
"manager",
"->",
"getClass",
"(",
")",
... | Serialize data object to id.
@param object $data
@return int|null | [
"Serialize",
"data",
"object",
"to",
"id",
"."
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/Serializer/BaseSerializerHandler.php#L102-L109 |
sonata-project/SonataCoreBundle | src/Twig/FlashMessage/FlashManager.php | FlashManager.get | public function get($type, $domain = null)
{
$this->handle($domain);
return $this->getSession()->getFlashBag()->get($type);
} | php | public function get($type, $domain = null)
{
$this->handle($domain);
return $this->getSession()->getFlashBag()->get($type);
} | [
"public",
"function",
"get",
"(",
"$",
"type",
",",
"$",
"domain",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"handle",
"(",
"$",
"domain",
")",
";",
"return",
"$",
"this",
"->",
"getSession",
"(",
")",
"->",
"getFlashBag",
"(",
")",
"->",
"get",
... | Returns flash bag messages for correct type after renaming with Sonata core type.
@param string $type Type of flash message
@param string $domain Translation domain to use
@return array | [
"Returns",
"flash",
"bag",
"messages",
"for",
"correct",
"type",
"after",
"renaming",
"with",
"Sonata",
"core",
"type",
"."
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/Twig/FlashMessage/FlashManager.php#L111-L116 |
sonata-project/SonataCoreBundle | src/Twig/FlashMessage/FlashManager.php | FlashManager.handle | protected function handle($domain = null)
{
foreach ($this->getTypes() as $type => $values) {
foreach ($values as $value => $options) {
$domainType = $domain ?: $options['domain'];
$this->rename($type, $value, $domainType);
}
}
} | php | protected function handle($domain = null)
{
foreach ($this->getTypes() as $type => $values) {
foreach ($values as $value => $options) {
$domainType = $domain ?: $options['domain'];
$this->rename($type, $value, $domainType);
}
}
} | [
"protected",
"function",
"handle",
"(",
"$",
"domain",
"=",
"null",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getTypes",
"(",
")",
"as",
"$",
"type",
"=>",
"$",
"values",
")",
"{",
"foreach",
"(",
"$",
"values",
"as",
"$",
"value",
"=>",
"$",
... | Handles flash bag types renaming.
@param string $domain | [
"Handles",
"flash",
"bag",
"types",
"renaming",
"."
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/Twig/FlashMessage/FlashManager.php#L133-L141 |
sonata-project/SonataCoreBundle | src/Twig/FlashMessage/FlashManager.php | FlashManager.rename | protected function rename($type, $value, $domain)
{
$flashBag = $this->getSession()->getFlashBag();
foreach ($flashBag->get($value) as $message) {
$message = $this->getTranslator()->trans($message, [], $domain);
$flashBag->add($type, $message);
}
} | php | protected function rename($type, $value, $domain)
{
$flashBag = $this->getSession()->getFlashBag();
foreach ($flashBag->get($value) as $message) {
$message = $this->getTranslator()->trans($message, [], $domain);
$flashBag->add($type, $message);
}
} | [
"protected",
"function",
"rename",
"(",
"$",
"type",
",",
"$",
"value",
",",
"$",
"domain",
")",
"{",
"$",
"flashBag",
"=",
"$",
"this",
"->",
"getSession",
"(",
")",
"->",
"getFlashBag",
"(",
")",
";",
"foreach",
"(",
"$",
"flashBag",
"->",
"get",
... | Process flash message type rename.
@param string $type Sonata core flash message type
@param string $value Original flash message type
@param string $domain Translation domain to use | [
"Process",
"flash",
"message",
"type",
"rename",
"."
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/Twig/FlashMessage/FlashManager.php#L150-L158 |
sonata-project/SonataCoreBundle | src/CoreBundle/Color/Colors.php | Colors.getAll | public static function getAll()
{
return [
self::ALICEBLUE => 'aliceblue',
self::ANTIQUEWHITE => 'antiquewhite',
self::AQUA => 'aqua',
self::AQUAMARINE => 'aquamarine',
self::AZURE => 'azure',
self::BEIGE => 'beige',
self::BISQUE => 'bisque',
self::BLACK => 'black',
self::BLANCHEDALMOND => 'blanchedalmond',
self::BLUE => 'blue',
self::BLUEVIOLET => 'blueviolet',
self::BROWN => 'brown',
self::BURLYWOOD => 'burlywood',
self::CADETBLUE => 'cadetblue',
self::CHARTREUSE => 'chartreuse',
self::CHOCOLATE => 'chocolate',
self::CORAL => 'coral',
self::CORNFLOWERBLUE => 'cornflowerblue',
self::CORNSILK => 'cornsilk',
self::CRIMSON => 'crimson',
self::CYAN => 'cyan',
self::DARKBLUE => 'darkblue',
self::DARKCYAN => 'darkcyan',
self::DARKGOLDENROD => 'darkgoldenrod',
self::DARKGRAY => 'darkgray',
self::DARKGREEN => 'darkgreen',
self::DARKKHAKI => 'darkkhaki',
self::DARKMAGENTA => 'darkmagenta',
self::DARKOLIVEGREEN => 'darkolivegreen',
self::DARKORANGE => 'darkorange',
self::DARKORCHID => 'darkorchid',
self::DARKRED => 'darkred',
self::DARKSALMON => 'darksalmon',
self::DARKSEAGREEN => 'darkseagreen',
self::DARKSLATEBLUE => 'darkslateblue',
self::DARKSLATEGRAY => 'darkslategray',
self::DARKTURQUOISE => 'darkturquoise',
self::DARKVIOLET => 'darkviolet',
self::DEEPPINK => 'deeppink',
self::DEEPSKYBLUE => 'deepskyblue',
self::DIMGRAY => 'dimgray',
self::DODGERBLUE => 'dodgerblue',
self::FIREBRICK => 'firebrick',
self::FLORALWHITE => 'floralwhite',
self::FORESTGREEN => 'forestgreen',
self::FUCHSIA => 'fuchsia',
self::GAINSBORO => 'gainsboro',
self::GHOSTWHITE => 'ghostwhite',
self::GOLD => 'gold',
self::GOLDENROD => 'goldenrod',
self::GRAY => 'gray',
self::GREEN => 'green',
self::GREENYELLOW => 'greenyellow',
self::HONEYDEW => 'honeydew',
self::HOTPINK => 'hotpink',
self::INDIANRED => 'indianred',
self::INDIGO => 'indigo',
self::IVORY => 'ivory',
self::KHAKI => 'khaki',
self::LAVENDER => 'lavender',
self::LAVENDERBLUSH => 'lavenderblush',
self::LAWNGREEN => 'lawngreen',
self::LEMONCHIFFON => 'lemonchiffon',
self::LIGHTBLUE => 'lightblue',
self::LIGHTCORAL => 'lightcoral',
self::LIGHTCYAN => 'lightcyan',
self::LIGHTGOLDENRODYELLOW => 'lightgoldenrodyellow',
self::LIGHTGRAY => 'lightgray',
self::LIGHTGREEN => 'lightgreen',
self::LIGHTPINK => 'lightpink',
self::LIGHTSALMON => 'lightsalmon',
self::LIGHTSEAGREEN => 'lightseagreen',
self::LIGHTSKYBLUE => 'lightskyblue',
self::LIGHTSLATEGRAY => 'lightslategray',
self::LIGHTSTEELBLUE => 'lightsteelblue',
self::LIGHTYELLOW => 'lightyellow',
self::LIME => 'lime',
self::LIMEGREEN => 'limegreen',
self::LINEN => 'linen',
self::MAGENTA => 'magenta',
self::MAROON => 'maroon',
self::MEDIUMAQUAMARINE => 'mediumaquamarine',
self::MEDIUMBLUE => 'mediumblue',
self::MEDIUMORCHID => 'mediumorchid',
self::MEDIUMPURPLE => 'mediumpurple',
self::MEDIUMSEAGREEN => 'mediumseagreen',
self::MEDIUMSLATEBLUE => 'mediumslateblue',
self::MEDIUMSPRINGGREEN => 'mediumspringgreen',
self::MEDIUMTURQUOISE => 'mediumturquoise',
self::MEDIUMVIOLETRED => 'mediumvioletred',
self::MIDNIGHTBLUE => 'midnightblue',
self::MINTCREAM => 'mintcream',
self::MISTYROSE => 'mistyrose',
self::MOCCASIN => 'moccasin',
self::NAVAJOWHITE => 'navajowhite',
self::NAVY => 'navy',
self::OLDLACE => 'oldlace',
self::OLIVE => 'olive',
self::OLIVEDRAB => 'olivedrab',
self::ORANGE => 'orange',
self::ORANGERED => 'orangered',
self::ORCHID => 'orchid',
self::PALEGOLDENROD => 'palegoldenrod',
self::PALEGREEN => 'palegreen',
self::PALETURQUOISE => 'paleturquoise',
self::PALEVIOLETRED => 'palevioletred',
self::PAPAYAWHIP => 'papayawhip',
self::PEACHPUFF => 'peachpuff',
self::PERU => 'peru',
self::PINK => 'pink',
self::PLUM => 'plum',
self::POWDERBLUE => 'powderblue',
self::PURPLE => 'purple',
self::REBECCAPURPLE => 'rebeccapurple',
self::RED => 'red',
self::ROSYBROWN => 'rosybrown',
self::ROYALBLUE => 'royalblue',
self::SADDLEBROWN => 'saddlebrown',
self::SALMON => 'salmon',
self::SANDYBROWN => 'sandybrown',
self::SEAGREEN => 'seagreen',
self::SEASHELL => 'seashell',
self::SIENNA => 'sienna',
self::SILVER => 'silver',
self::SKYBLUE => 'skyblue',
self::SLATEBLUE => 'slateblue',
self::SLATEGRAY => 'slategray',
self::SNOW => 'snow',
self::SPRINGGREEN => 'springgreen',
self::STEELBLUE => 'steelblue',
self::TAN => 'tan',
self::TEAL => 'teal',
self::THISTLE => 'thistle',
self::TOMATO => 'tomato',
self::TURQUOISE => 'turquoise',
self::VIOLET => 'violet',
self::WHEAT => 'wheat',
self::WHITE => 'white',
self::WHITESMOKE => 'whitesmoke',
self::YELLOW => 'yellow',
self::YELLOWGREEN => 'yellowgreen',
];
} | php | public static function getAll()
{
return [
self::ALICEBLUE => 'aliceblue',
self::ANTIQUEWHITE => 'antiquewhite',
self::AQUA => 'aqua',
self::AQUAMARINE => 'aquamarine',
self::AZURE => 'azure',
self::BEIGE => 'beige',
self::BISQUE => 'bisque',
self::BLACK => 'black',
self::BLANCHEDALMOND => 'blanchedalmond',
self::BLUE => 'blue',
self::BLUEVIOLET => 'blueviolet',
self::BROWN => 'brown',
self::BURLYWOOD => 'burlywood',
self::CADETBLUE => 'cadetblue',
self::CHARTREUSE => 'chartreuse',
self::CHOCOLATE => 'chocolate',
self::CORAL => 'coral',
self::CORNFLOWERBLUE => 'cornflowerblue',
self::CORNSILK => 'cornsilk',
self::CRIMSON => 'crimson',
self::CYAN => 'cyan',
self::DARKBLUE => 'darkblue',
self::DARKCYAN => 'darkcyan',
self::DARKGOLDENROD => 'darkgoldenrod',
self::DARKGRAY => 'darkgray',
self::DARKGREEN => 'darkgreen',
self::DARKKHAKI => 'darkkhaki',
self::DARKMAGENTA => 'darkmagenta',
self::DARKOLIVEGREEN => 'darkolivegreen',
self::DARKORANGE => 'darkorange',
self::DARKORCHID => 'darkorchid',
self::DARKRED => 'darkred',
self::DARKSALMON => 'darksalmon',
self::DARKSEAGREEN => 'darkseagreen',
self::DARKSLATEBLUE => 'darkslateblue',
self::DARKSLATEGRAY => 'darkslategray',
self::DARKTURQUOISE => 'darkturquoise',
self::DARKVIOLET => 'darkviolet',
self::DEEPPINK => 'deeppink',
self::DEEPSKYBLUE => 'deepskyblue',
self::DIMGRAY => 'dimgray',
self::DODGERBLUE => 'dodgerblue',
self::FIREBRICK => 'firebrick',
self::FLORALWHITE => 'floralwhite',
self::FORESTGREEN => 'forestgreen',
self::FUCHSIA => 'fuchsia',
self::GAINSBORO => 'gainsboro',
self::GHOSTWHITE => 'ghostwhite',
self::GOLD => 'gold',
self::GOLDENROD => 'goldenrod',
self::GRAY => 'gray',
self::GREEN => 'green',
self::GREENYELLOW => 'greenyellow',
self::HONEYDEW => 'honeydew',
self::HOTPINK => 'hotpink',
self::INDIANRED => 'indianred',
self::INDIGO => 'indigo',
self::IVORY => 'ivory',
self::KHAKI => 'khaki',
self::LAVENDER => 'lavender',
self::LAVENDERBLUSH => 'lavenderblush',
self::LAWNGREEN => 'lawngreen',
self::LEMONCHIFFON => 'lemonchiffon',
self::LIGHTBLUE => 'lightblue',
self::LIGHTCORAL => 'lightcoral',
self::LIGHTCYAN => 'lightcyan',
self::LIGHTGOLDENRODYELLOW => 'lightgoldenrodyellow',
self::LIGHTGRAY => 'lightgray',
self::LIGHTGREEN => 'lightgreen',
self::LIGHTPINK => 'lightpink',
self::LIGHTSALMON => 'lightsalmon',
self::LIGHTSEAGREEN => 'lightseagreen',
self::LIGHTSKYBLUE => 'lightskyblue',
self::LIGHTSLATEGRAY => 'lightslategray',
self::LIGHTSTEELBLUE => 'lightsteelblue',
self::LIGHTYELLOW => 'lightyellow',
self::LIME => 'lime',
self::LIMEGREEN => 'limegreen',
self::LINEN => 'linen',
self::MAGENTA => 'magenta',
self::MAROON => 'maroon',
self::MEDIUMAQUAMARINE => 'mediumaquamarine',
self::MEDIUMBLUE => 'mediumblue',
self::MEDIUMORCHID => 'mediumorchid',
self::MEDIUMPURPLE => 'mediumpurple',
self::MEDIUMSEAGREEN => 'mediumseagreen',
self::MEDIUMSLATEBLUE => 'mediumslateblue',
self::MEDIUMSPRINGGREEN => 'mediumspringgreen',
self::MEDIUMTURQUOISE => 'mediumturquoise',
self::MEDIUMVIOLETRED => 'mediumvioletred',
self::MIDNIGHTBLUE => 'midnightblue',
self::MINTCREAM => 'mintcream',
self::MISTYROSE => 'mistyrose',
self::MOCCASIN => 'moccasin',
self::NAVAJOWHITE => 'navajowhite',
self::NAVY => 'navy',
self::OLDLACE => 'oldlace',
self::OLIVE => 'olive',
self::OLIVEDRAB => 'olivedrab',
self::ORANGE => 'orange',
self::ORANGERED => 'orangered',
self::ORCHID => 'orchid',
self::PALEGOLDENROD => 'palegoldenrod',
self::PALEGREEN => 'palegreen',
self::PALETURQUOISE => 'paleturquoise',
self::PALEVIOLETRED => 'palevioletred',
self::PAPAYAWHIP => 'papayawhip',
self::PEACHPUFF => 'peachpuff',
self::PERU => 'peru',
self::PINK => 'pink',
self::PLUM => 'plum',
self::POWDERBLUE => 'powderblue',
self::PURPLE => 'purple',
self::REBECCAPURPLE => 'rebeccapurple',
self::RED => 'red',
self::ROSYBROWN => 'rosybrown',
self::ROYALBLUE => 'royalblue',
self::SADDLEBROWN => 'saddlebrown',
self::SALMON => 'salmon',
self::SANDYBROWN => 'sandybrown',
self::SEAGREEN => 'seagreen',
self::SEASHELL => 'seashell',
self::SIENNA => 'sienna',
self::SILVER => 'silver',
self::SKYBLUE => 'skyblue',
self::SLATEBLUE => 'slateblue',
self::SLATEGRAY => 'slategray',
self::SNOW => 'snow',
self::SPRINGGREEN => 'springgreen',
self::STEELBLUE => 'steelblue',
self::TAN => 'tan',
self::TEAL => 'teal',
self::THISTLE => 'thistle',
self::TOMATO => 'tomato',
self::TURQUOISE => 'turquoise',
self::VIOLET => 'violet',
self::WHEAT => 'wheat',
self::WHITE => 'white',
self::WHITESMOKE => 'whitesmoke',
self::YELLOW => 'yellow',
self::YELLOWGREEN => 'yellowgreen',
];
} | [
"public",
"static",
"function",
"getAll",
"(",
")",
"{",
"return",
"[",
"self",
"::",
"ALICEBLUE",
"=>",
"'aliceblue'",
",",
"self",
"::",
"ANTIQUEWHITE",
"=>",
"'antiquewhite'",
",",
"self",
"::",
"AQUA",
"=>",
"'aqua'",
",",
"self",
"::",
"AQUAMARINE",
"... | Return the list of colors.
@return array | [
"Return",
"the",
"list",
"of",
"colors",
"."
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/CoreBundle/Color/Colors.php#L180-L325 |
sonata-project/SonataCoreBundle | src/CoreBundle/Exporter/Exporter.php | Exporter.getResponse | public function getResponse($format, $filename, SourceIteratorInterface $source)
{
switch ($format) {
case 'xls':
$writer = new XlsWriter('php://output');
$contentType = 'application/vnd.ms-excel';
break;
case 'xml':
$writer = new XmlWriter('php://output');
$contentType = 'text/xml';
break;
case 'json':
$writer = new JsonWriter('php://output');
$contentType = 'application/json';
break;
case 'csv':
$writer = new CsvWriter('php://output', ',', '"', '\\', true, true);
$contentType = 'text/csv';
break;
default:
throw new \RuntimeException('Invalid format');
}
$callback = static function () use ($source, $writer) {
$handler = Handler::create($source, $writer);
$handler->export();
};
return new StreamedResponse($callback, 200, [
'Content-Type' => $contentType,
'Content-Disposition' => sprintf('attachment; filename="%s"', $filename),
]);
} | php | public function getResponse($format, $filename, SourceIteratorInterface $source)
{
switch ($format) {
case 'xls':
$writer = new XlsWriter('php://output');
$contentType = 'application/vnd.ms-excel';
break;
case 'xml':
$writer = new XmlWriter('php://output');
$contentType = 'text/xml';
break;
case 'json':
$writer = new JsonWriter('php://output');
$contentType = 'application/json';
break;
case 'csv':
$writer = new CsvWriter('php://output', ',', '"', '\\', true, true);
$contentType = 'text/csv';
break;
default:
throw new \RuntimeException('Invalid format');
}
$callback = static function () use ($source, $writer) {
$handler = Handler::create($source, $writer);
$handler->export();
};
return new StreamedResponse($callback, 200, [
'Content-Type' => $contentType,
'Content-Disposition' => sprintf('attachment; filename="%s"', $filename),
]);
} | [
"public",
"function",
"getResponse",
"(",
"$",
"format",
",",
"$",
"filename",
",",
"SourceIteratorInterface",
"$",
"source",
")",
"{",
"switch",
"(",
"$",
"format",
")",
"{",
"case",
"'xls'",
":",
"$",
"writer",
"=",
"new",
"XlsWriter",
"(",
"'php://outpu... | @param string $format
@param string $filename
@param SourceIteratorInterface $source
@throws \RuntimeException
@return StreamedResponse | [
"@param",
"string",
"$format",
"@param",
"string",
"$filename",
"@param",
"SourceIteratorInterface",
"$source"
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/CoreBundle/Exporter/Exporter.php#L44-L80 |
sonata-project/SonataCoreBundle | src/CoreBundle/Form/FormHelper.php | FormHelper.removeFields | public static function removeFields(array $data, Form $form)
{
$diff = array_diff(array_keys($form->all()), array_keys($data));
foreach ($diff as $key) {
$form->remove($key);
}
foreach ($data as $name => $value) {
if (!\is_array($value)) {
continue;
}
self::removeFields($value, $form[$name]);
}
} | php | public static function removeFields(array $data, Form $form)
{
$diff = array_diff(array_keys($form->all()), array_keys($data));
foreach ($diff as $key) {
$form->remove($key);
}
foreach ($data as $name => $value) {
if (!\is_array($value)) {
continue;
}
self::removeFields($value, $form[$name]);
}
} | [
"public",
"static",
"function",
"removeFields",
"(",
"array",
"$",
"data",
",",
"Form",
"$",
"form",
")",
"{",
"$",
"diff",
"=",
"array_diff",
"(",
"array_keys",
"(",
"$",
"form",
"->",
"all",
"(",
")",
")",
",",
"array_keys",
"(",
"$",
"data",
")",
... | This function remove fields available if there are not present in the $data array
The data array might come from $request->request->all().
This can be usefull if you don't want to send all fields will building an api. As missing
fields will be threated like null values. | [
"This",
"function",
"remove",
"fields",
"available",
"if",
"there",
"are",
"not",
"present",
"in",
"the",
"$data",
"array",
"The",
"data",
"array",
"might",
"come",
"from",
"$request",
"-",
">",
"request",
"-",
">",
"all",
"()",
"."
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/CoreBundle/Form/FormHelper.php#L33-L48 |
sonata-project/SonataCoreBundle | src/CoreBundle/Form/Extension/DependencyInjectionExtension.php | DependencyInjectionExtension.findClass | protected static function findClass($mapping, $type)
{
if (strpos($type, '\\')) {
return $type;
}
if (!isset($mapping[$type])) {
return $type;
}
return $mapping[$type];
} | php | protected static function findClass($mapping, $type)
{
if (strpos($type, '\\')) {
return $type;
}
if (!isset($mapping[$type])) {
return $type;
}
return $mapping[$type];
} | [
"protected",
"static",
"function",
"findClass",
"(",
"$",
"mapping",
",",
"$",
"type",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"type",
",",
"'\\\\'",
")",
")",
"{",
"return",
"$",
"type",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"mapping",
"... | @param string $type
@return string | [
"@param",
"string",
"$type"
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/CoreBundle/Form/Extension/DependencyInjectionExtension.php#L185-L196 |
sonata-project/SonataCoreBundle | src/CoreBundle/Twig/Extension/StatusExtension.php | StatusExtension.statusClass | public function statusClass($object, $statusType = null, $default = '')
{
@trigger_error(
'Method "StatusExtension::statusClass()" is deprecated since SonataCoreBundle 3.13.0 and will'.
' be removed in 4.0. Use the StatusRuntime instead.',
E_USER_DEPRECATED
);
/** @var StatusClassRendererInterface $statusService */
foreach ($this->statusServices as $statusService) {
if ($statusService->handlesObject($object, $statusType)) {
return $statusService->getStatusClass($object, $statusType, $default);
}
}
return $default;
} | php | public function statusClass($object, $statusType = null, $default = '')
{
@trigger_error(
'Method "StatusExtension::statusClass()" is deprecated since SonataCoreBundle 3.13.0 and will'.
' be removed in 4.0. Use the StatusRuntime instead.',
E_USER_DEPRECATED
);
/** @var StatusClassRendererInterface $statusService */
foreach ($this->statusServices as $statusService) {
if ($statusService->handlesObject($object, $statusType)) {
return $statusService->getStatusClass($object, $statusType, $default);
}
}
return $default;
} | [
"public",
"function",
"statusClass",
"(",
"$",
"object",
",",
"$",
"statusType",
"=",
"null",
",",
"$",
"default",
"=",
"''",
")",
"{",
"@",
"trigger_error",
"(",
"'Method \"StatusExtension::statusClass()\" is deprecated since SonataCoreBundle 3.13.0 and will'",
".",
"'... | @param mixed $object
@param mixed $statusType
@param string $default
@return string
@deprecated since 3.13.0, to be removed in 4.0. Use the StatusRuntime instead. | [
"@param",
"mixed",
"$object",
"@param",
"mixed",
"$statusType",
"@param",
"string",
"$default"
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/CoreBundle/Twig/Extension/StatusExtension.php#L74-L90 |
sonata-project/SonataCoreBundle | src/Form/Date/MomentFormatConverter.php | MomentFormatConverter.convert | public function convert($format)
{
$size = \strlen($format);
$foundOne = false;
$output = '';
//process the format string letter by letter
for ($i = 0; $i < $size; ++$i) {
//if finds a '
if ("'" === $format[$i]) {
//if the next character are T' forming 'T', send a T to the
//output
if ('T' === $format[$i + 1] && '\'' === $format[$i + 2]) {
$output .= 'T';
$i += 2;
} else {
//if it's no a 'T' then send whatever is inside the '' to
//the output, but send it inside [] (useful for cases like
//the brazilian translation that uses a 'de' in the date)
$output .= '[';
$temp = current(explode("'", substr($format, $i + 1)));
$output .= $temp;
$output .= ']';
$i += \strlen($temp) + 1;
}
} else {
//if no ' is found, then search all the rules, see if any of
//them matchs
$foundOne = false;
foreach (self::$formatConvertRules as $key => $value) {
if (substr($format, $i, \strlen($key)) === $key) {
$output .= $value;
$foundOne = true;
$i += \strlen($key) - 1;
break;
}
}
//if no rule is matched, then just add the character to the
//output
if (!$foundOne) {
$output .= $format[$i];
}
}
}
return $output;
} | php | public function convert($format)
{
$size = \strlen($format);
$foundOne = false;
$output = '';
//process the format string letter by letter
for ($i = 0; $i < $size; ++$i) {
//if finds a '
if ("'" === $format[$i]) {
//if the next character are T' forming 'T', send a T to the
//output
if ('T' === $format[$i + 1] && '\'' === $format[$i + 2]) {
$output .= 'T';
$i += 2;
} else {
//if it's no a 'T' then send whatever is inside the '' to
//the output, but send it inside [] (useful for cases like
//the brazilian translation that uses a 'de' in the date)
$output .= '[';
$temp = current(explode("'", substr($format, $i + 1)));
$output .= $temp;
$output .= ']';
$i += \strlen($temp) + 1;
}
} else {
//if no ' is found, then search all the rules, see if any of
//them matchs
$foundOne = false;
foreach (self::$formatConvertRules as $key => $value) {
if (substr($format, $i, \strlen($key)) === $key) {
$output .= $value;
$foundOne = true;
$i += \strlen($key) - 1;
break;
}
}
//if no rule is matched, then just add the character to the
//output
if (!$foundOne) {
$output .= $format[$i];
}
}
}
return $output;
} | [
"public",
"function",
"convert",
"(",
"$",
"format",
")",
"{",
"$",
"size",
"=",
"\\",
"strlen",
"(",
"$",
"format",
")",
";",
"$",
"foundOne",
"=",
"false",
";",
"$",
"output",
"=",
"''",
";",
"//process the format string letter by letter",
"for",
"(",
... | Returns associated moment.js format.
@param $format PHP Date format
@return string Moment.js date format | [
"Returns",
"associated",
"moment",
".",
"js",
"format",
"."
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/Form/Date/MomentFormatConverter.php#L60-L106 |
sonata-project/SonataCoreBundle | src/CoreBundle/SonataCoreBundle.php | SonataCoreBundle.registerFormMapping | public function registerFormMapping()
{
// symfony
FormHelper::registerFormTypeMapping([
'form' => FormType::class,
'birthday' => BirthdayType::class,
'checkbox' => CheckboxType::class,
'choice' => ChoiceType::class,
'collection' => SymfonyCollectionType::class,
'country' => CountryType::class,
'date' => DateType::class,
'datetime' => DateTimeType::class,
'email' => EmailType::class,
'file' => FileType::class,
'hidden' => HiddenType::class,
'integer' => IntegerType::class,
'language' => LanguageType::class,
'locale' => LocaleType::class,
'money' => MoneyType::class,
'number' => NumberType::class,
'password' => PasswordType::class,
'percent' => PercentType::class,
'radio' => RadioType::class,
'repeated' => RepeatedType::class,
'search' => SearchType::class,
'textarea' => TextareaType::class,
'text' => TextType::class,
'time' => TimeType::class,
'timezone' => TimezoneType::class,
'url' => UrlType::class,
'button' => ButtonType::class,
'submit' => SubmitType::class,
'reset' => ResetType::class,
'currency' => CurrencyType::class,
'entity' => EntityType::class,
]);
// core bundle
FormHelper::registerFormTypeMapping([
'sonata_type_immutable_array' => ImmutableArrayType::class,
'sonata_type_boolean' => BooleanType::class,
'sonata_type_collection' => CollectionType::class,
'sonata_type_translatable_choice' => TranslatableChoiceType::class,
'sonata_type_date_range' => DateRangeType::class,
'sonata_type_datetime_range' => DateTimeRangeType::class,
'sonata_type_date_picker' => DatePickerType::class,
'sonata_type_datetime_picker' => DateTimePickerType::class,
'sonata_type_date_range_picker' => DateRangePickerType::class,
'sonata_type_datetime_range_picker' => DateTimeRangePickerType::class,
'sonata_type_equal' => EqualType::class,
'sonata_type_color' => ColorType::class,
'sonata_type_color_selector' => ColorSelectorType::class,
]);
$formTypes = [
'form.type_extension.form.http_foundation',
'form.type_extension.form.validator',
'form.type_extension.csrf',
'form.type_extension.form.data_collector',
];
if (class_exists(DescriptionFormTypeExtension::class)) {
$formTypes[] = 'nelmio_api_doc.form.extension.description_form_type_extension';
}
FormHelper::registerFormExtensionMapping('form', $formTypes);
FormHelper::registerFormExtensionMapping('repeated', [
'form.type_extension.repeated.validator',
]);
FormHelper::registerFormExtensionMapping('submit', [
'form.type_extension.submit.validator',
]);
if ($this->container && $this->container->hasParameter('sonata.core.form.mapping.type')) {
// from configuration file
FormHelper::registerFormTypeMapping($this->container->getParameter('sonata.core.form.mapping.type'));
foreach ($this->container->getParameter('sonata.core.form.mapping.extension') as $ext => $types) {
FormHelper::registerFormExtensionMapping($ext, $types);
}
}
} | php | public function registerFormMapping()
{
// symfony
FormHelper::registerFormTypeMapping([
'form' => FormType::class,
'birthday' => BirthdayType::class,
'checkbox' => CheckboxType::class,
'choice' => ChoiceType::class,
'collection' => SymfonyCollectionType::class,
'country' => CountryType::class,
'date' => DateType::class,
'datetime' => DateTimeType::class,
'email' => EmailType::class,
'file' => FileType::class,
'hidden' => HiddenType::class,
'integer' => IntegerType::class,
'language' => LanguageType::class,
'locale' => LocaleType::class,
'money' => MoneyType::class,
'number' => NumberType::class,
'password' => PasswordType::class,
'percent' => PercentType::class,
'radio' => RadioType::class,
'repeated' => RepeatedType::class,
'search' => SearchType::class,
'textarea' => TextareaType::class,
'text' => TextType::class,
'time' => TimeType::class,
'timezone' => TimezoneType::class,
'url' => UrlType::class,
'button' => ButtonType::class,
'submit' => SubmitType::class,
'reset' => ResetType::class,
'currency' => CurrencyType::class,
'entity' => EntityType::class,
]);
// core bundle
FormHelper::registerFormTypeMapping([
'sonata_type_immutable_array' => ImmutableArrayType::class,
'sonata_type_boolean' => BooleanType::class,
'sonata_type_collection' => CollectionType::class,
'sonata_type_translatable_choice' => TranslatableChoiceType::class,
'sonata_type_date_range' => DateRangeType::class,
'sonata_type_datetime_range' => DateTimeRangeType::class,
'sonata_type_date_picker' => DatePickerType::class,
'sonata_type_datetime_picker' => DateTimePickerType::class,
'sonata_type_date_range_picker' => DateRangePickerType::class,
'sonata_type_datetime_range_picker' => DateTimeRangePickerType::class,
'sonata_type_equal' => EqualType::class,
'sonata_type_color' => ColorType::class,
'sonata_type_color_selector' => ColorSelectorType::class,
]);
$formTypes = [
'form.type_extension.form.http_foundation',
'form.type_extension.form.validator',
'form.type_extension.csrf',
'form.type_extension.form.data_collector',
];
if (class_exists(DescriptionFormTypeExtension::class)) {
$formTypes[] = 'nelmio_api_doc.form.extension.description_form_type_extension';
}
FormHelper::registerFormExtensionMapping('form', $formTypes);
FormHelper::registerFormExtensionMapping('repeated', [
'form.type_extension.repeated.validator',
]);
FormHelper::registerFormExtensionMapping('submit', [
'form.type_extension.submit.validator',
]);
if ($this->container && $this->container->hasParameter('sonata.core.form.mapping.type')) {
// from configuration file
FormHelper::registerFormTypeMapping($this->container->getParameter('sonata.core.form.mapping.type'));
foreach ($this->container->getParameter('sonata.core.form.mapping.extension') as $ext => $types) {
FormHelper::registerFormExtensionMapping($ext, $types);
}
}
} | [
"public",
"function",
"registerFormMapping",
"(",
")",
"{",
"// symfony",
"FormHelper",
"::",
"registerFormTypeMapping",
"(",
"[",
"'form'",
"=>",
"FormType",
"::",
"class",
",",
"'birthday'",
"=>",
"BirthdayType",
"::",
"class",
",",
"'checkbox'",
"=>",
"Checkbox... | Register form mapping information. | [
"Register",
"form",
"mapping",
"information",
"."
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/CoreBundle/SonataCoreBundle.php#L90-L172 |
sonata-project/SonataCoreBundle | src/CoreBundle/Command/SonataDumpDoctrineMetaCommand.php | SonataDumpDoctrineMetaCommand.dumpMetadata | private function dumpMetadata(array $metadata, InputInterface $input, OutputInterface $output)
{
foreach ($metadata as $name => $meta) {
$output->writeln(sprintf('<info>%s</info>', $name));
foreach ($meta['fields'] as $fieldName => $columnName) {
$output->writeln(sprintf(' <comment>></comment> %s <info>=></info> %s', $fieldName, $columnName));
}
}
$output->writeln('---------------');
$output->writeln('---- END ----');
$output->writeln('---------------');
$output->writeln('');
if ($input->getOption('filename')) {
$directory = \dirname($input->getOption('filename'));
$filename = basename($input->getOption('filename'));
if (empty($directory) || '.' === $directory) {
$directory = getcwd();
}
$adapter = new LocalAdapter($directory, true);
$fileSystem = new Filesystem($adapter);
$success = $fileSystem->write($filename, json_encode($metadata), true);
if ($success) {
$output->writeLn(sprintf('<info>File %s/%s successfully created</info>', $directory, $filename));
} else {
$output->writeLn(sprintf('<error>File %s/%s could not be created</error>', $directory, $filename));
}
}
} | php | private function dumpMetadata(array $metadata, InputInterface $input, OutputInterface $output)
{
foreach ($metadata as $name => $meta) {
$output->writeln(sprintf('<info>%s</info>', $name));
foreach ($meta['fields'] as $fieldName => $columnName) {
$output->writeln(sprintf(' <comment>></comment> %s <info>=></info> %s', $fieldName, $columnName));
}
}
$output->writeln('---------------');
$output->writeln('---- END ----');
$output->writeln('---------------');
$output->writeln('');
if ($input->getOption('filename')) {
$directory = \dirname($input->getOption('filename'));
$filename = basename($input->getOption('filename'));
if (empty($directory) || '.' === $directory) {
$directory = getcwd();
}
$adapter = new LocalAdapter($directory, true);
$fileSystem = new Filesystem($adapter);
$success = $fileSystem->write($filename, json_encode($metadata), true);
if ($success) {
$output->writeLn(sprintf('<info>File %s/%s successfully created</info>', $directory, $filename));
} else {
$output->writeLn(sprintf('<error>File %s/%s could not be created</error>', $directory, $filename));
}
}
} | [
"private",
"function",
"dumpMetadata",
"(",
"array",
"$",
"metadata",
",",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"foreach",
"(",
"$",
"metadata",
"as",
"$",
"name",
"=>",
"$",
"meta",
")",
"{",
"$",
"output",
"-... | Display the list of entities handled by Doctrine and their fields. | [
"Display",
"the",
"list",
"of",
"entities",
"handled",
"by",
"Doctrine",
"and",
"their",
"fields",
"."
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/CoreBundle/Command/SonataDumpDoctrineMetaCommand.php#L102-L134 |
sonata-project/SonataCoreBundle | src/Form/Validator/InlineValidator.php | InlineValidator.getErrorElement | protected function getErrorElement($value)
{
return new ErrorElement(
$value,
$this->constraintValidatorFactory,
$this->context,
$this->context->getGroup()
);
} | php | protected function getErrorElement($value)
{
return new ErrorElement(
$value,
$this->constraintValidatorFactory,
$this->context,
$this->context->getGroup()
);
} | [
"protected",
"function",
"getErrorElement",
"(",
"$",
"value",
")",
"{",
"return",
"new",
"ErrorElement",
"(",
"$",
"value",
",",
"$",
"this",
"->",
"constraintValidatorFactory",
",",
"$",
"this",
"->",
"context",
",",
"$",
"this",
"->",
"context",
"->",
"... | @param mixed $value
@return ErrorElement | [
"@param",
"mixed",
"$value"
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/Form/Validator/InlineValidator.php#L63-L71 |
sonata-project/SonataCoreBundle | src/CoreBundle/DependencyInjection/Configuration.php | Configuration.addFlashMessageSection | private function addFlashMessageSection(ArrayNodeDefinition $node)
{
$node
->children()
->scalarNode('form_type')
->defaultValue('standard')
->validate()
->ifNotInArray($validFormTypes = ['standard', 'horizontal'])
->thenInvalid(sprintf(
'The form_type option value must be one of %s',
$validFormTypesString = implode(', ', $validFormTypes)
))
->end()
->info(sprintf('Must be one of %s', $validFormTypesString))
->end()
->arrayNode('flashmessage')
->useAttributeAsKey('message')
->prototype('array')
->children()
->scalarNode('css_class')->end()
->arrayNode('types')
->useAttributeAsKey('type')
->prototype('array')
->children()
->scalarNode('domain')->defaultValue('SonataCoreBundle')->end()
->end()
->end()
->end()
->end()
->end()
->end()
->end()
;
} | php | private function addFlashMessageSection(ArrayNodeDefinition $node)
{
$node
->children()
->scalarNode('form_type')
->defaultValue('standard')
->validate()
->ifNotInArray($validFormTypes = ['standard', 'horizontal'])
->thenInvalid(sprintf(
'The form_type option value must be one of %s',
$validFormTypesString = implode(', ', $validFormTypes)
))
->end()
->info(sprintf('Must be one of %s', $validFormTypesString))
->end()
->arrayNode('flashmessage')
->useAttributeAsKey('message')
->prototype('array')
->children()
->scalarNode('css_class')->end()
->arrayNode('types')
->useAttributeAsKey('type')
->prototype('array')
->children()
->scalarNode('domain')->defaultValue('SonataCoreBundle')->end()
->end()
->end()
->end()
->end()
->end()
->end()
->end()
;
} | [
"private",
"function",
"addFlashMessageSection",
"(",
"ArrayNodeDefinition",
"$",
"node",
")",
"{",
"$",
"node",
"->",
"children",
"(",
")",
"->",
"scalarNode",
"(",
"'form_type'",
")",
"->",
"defaultValue",
"(",
"'standard'",
")",
"->",
"validate",
"(",
")",
... | Returns configuration for flash messages. | [
"Returns",
"configuration",
"for",
"flash",
"messages",
"."
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/CoreBundle/DependencyInjection/Configuration.php#L79-L112 |
sonata-project/SonataCoreBundle | src/CoreBundle/DependencyInjection/Configuration.php | Configuration.addSerializerFormats | private function addSerializerFormats(ArrayNodeDefinition $node)
{
// NEXT_MAJOR : do not execute this if jms/serializer is missing
$node
->children()
->arrayNode('serializer')
->addDefaultsIfNotSet()
->children()
->arrayNode('formats')
->prototype('scalar')->end()
->defaultValue(['json', 'xml', 'yml'])
->info('Default serializer formats, will be used while getting subscribing methods.')
->end()
->end()
->end()
->end()
;
} | php | private function addSerializerFormats(ArrayNodeDefinition $node)
{
// NEXT_MAJOR : do not execute this if jms/serializer is missing
$node
->children()
->arrayNode('serializer')
->addDefaultsIfNotSet()
->children()
->arrayNode('formats')
->prototype('scalar')->end()
->defaultValue(['json', 'xml', 'yml'])
->info('Default serializer formats, will be used while getting subscribing methods.')
->end()
->end()
->end()
->end()
;
} | [
"private",
"function",
"addSerializerFormats",
"(",
"ArrayNodeDefinition",
"$",
"node",
")",
"{",
"// NEXT_MAJOR : do not execute this if jms/serializer is missing",
"$",
"node",
"->",
"children",
"(",
")",
"->",
"arrayNode",
"(",
"'serializer'",
")",
"->",
"addDefaultsIf... | Returns configuration for serializer formats. | [
"Returns",
"configuration",
"for",
"serializer",
"formats",
"."
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/CoreBundle/DependencyInjection/Configuration.php#L117-L134 |
sonata-project/SonataCoreBundle | src/CoreBundle/DependencyInjection/SonataCoreExtension.php | SonataCoreExtension.registerFlashTypes | public function registerFlashTypes(ContainerBuilder $container, array $config)
{
$mergedConfig = array_merge_recursive($config['flashmessage'], [
'success' => ['types' => [
'success' => ['domain' => 'SonataCoreBundle'],
'sonata_flash_success' => ['domain' => 'SonataAdminBundle'],
'sonata_user_success' => ['domain' => 'SonataUserBundle'],
'fos_user_success' => ['domain' => 'FOSUserBundle'],
]],
'warning' => ['types' => [
'warning' => ['domain' => 'SonataCoreBundle'],
'sonata_flash_info' => ['domain' => 'SonataAdminBundle'],
]],
'danger' => ['types' => [
'error' => ['domain' => 'SonataCoreBundle'],
'sonata_flash_error' => ['domain' => 'SonataAdminBundle'],
'sonata_user_error' => ['domain' => 'SonataUserBundle'],
]],
]);
$types = $cssClasses = [];
foreach ($mergedConfig as $typeKey => $typeConfig) {
$types[$typeKey] = $typeConfig['types'];
$cssClasses[$typeKey] = \array_key_exists('css_class', $typeConfig) ? $typeConfig['css_class'] : $typeKey;
}
$identifier = 'sonata.core.flashmessage.manager';
$definition = $container->getDefinition($identifier);
$definition->replaceArgument(2, $types);
$definition->replaceArgument(3, $cssClasses);
$container->setDefinition($identifier, $definition);
} | php | public function registerFlashTypes(ContainerBuilder $container, array $config)
{
$mergedConfig = array_merge_recursive($config['flashmessage'], [
'success' => ['types' => [
'success' => ['domain' => 'SonataCoreBundle'],
'sonata_flash_success' => ['domain' => 'SonataAdminBundle'],
'sonata_user_success' => ['domain' => 'SonataUserBundle'],
'fos_user_success' => ['domain' => 'FOSUserBundle'],
]],
'warning' => ['types' => [
'warning' => ['domain' => 'SonataCoreBundle'],
'sonata_flash_info' => ['domain' => 'SonataAdminBundle'],
]],
'danger' => ['types' => [
'error' => ['domain' => 'SonataCoreBundle'],
'sonata_flash_error' => ['domain' => 'SonataAdminBundle'],
'sonata_user_error' => ['domain' => 'SonataUserBundle'],
]],
]);
$types = $cssClasses = [];
foreach ($mergedConfig as $typeKey => $typeConfig) {
$types[$typeKey] = $typeConfig['types'];
$cssClasses[$typeKey] = \array_key_exists('css_class', $typeConfig) ? $typeConfig['css_class'] : $typeKey;
}
$identifier = 'sonata.core.flashmessage.manager';
$definition = $container->getDefinition($identifier);
$definition->replaceArgument(2, $types);
$definition->replaceArgument(3, $cssClasses);
$container->setDefinition($identifier, $definition);
} | [
"public",
"function",
"registerFlashTypes",
"(",
"ContainerBuilder",
"$",
"container",
",",
"array",
"$",
"config",
")",
"{",
"$",
"mergedConfig",
"=",
"array_merge_recursive",
"(",
"$",
"config",
"[",
"'flashmessage'",
"]",
",",
"[",
"'success'",
"=>",
"[",
"... | Registers flash message types defined in configuration to flash manager. | [
"Registers",
"flash",
"message",
"types",
"defined",
"in",
"configuration",
"to",
"flash",
"manager",
"."
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/CoreBundle/DependencyInjection/SonataCoreExtension.php#L159-L193 |
sonata-project/SonataCoreBundle | src/Twig/Extension/StatusRuntime.php | StatusRuntime.statusClass | public function statusClass($object, $statusType = null, $default = '')
{
foreach ($this->statusServices as $statusService) {
\assert($statusService instanceof StatusClassRendererInterface);
if ($statusService->handlesObject($object, $statusType)) {
return $statusService->getStatusClass($object, $statusType, $default);
}
}
return $default;
} | php | public function statusClass($object, $statusType = null, $default = '')
{
foreach ($this->statusServices as $statusService) {
\assert($statusService instanceof StatusClassRendererInterface);
if ($statusService->handlesObject($object, $statusType)) {
return $statusService->getStatusClass($object, $statusType, $default);
}
}
return $default;
} | [
"public",
"function",
"statusClass",
"(",
"$",
"object",
",",
"$",
"statusType",
"=",
"null",
",",
"$",
"default",
"=",
"''",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"statusServices",
"as",
"$",
"statusService",
")",
"{",
"\\",
"assert",
"(",
"$",... | @param mixed $object
@param mixed $statusType
@param string $default
@return string | [
"@param",
"mixed",
"$object",
"@param",
"mixed",
"$statusType",
"@param",
"string",
"$default"
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/Twig/Extension/StatusRuntime.php#L44-L55 |
sonata-project/SonataCoreBundle | src/Form/Type/BasePickerType.php | BasePickerType.configureOptions | public function configureOptions(OptionsResolver $resolver)
{
$resolver->setNormalizer('format', function (Options $options, $format) {
if (isset($options['date_format']) && \is_string($options['date_format'])) {
return $options['date_format'];
}
if (\is_int($format)) {
$timeFormat = \IntlDateFormatter::NONE;
if ($options['dp_pick_time']) {
$timeFormat = $options['dp_use_seconds'] ?
DateTimeType::DEFAULT_TIME_FORMAT :
\IntlDateFormatter::SHORT;
}
$intlDateFormatter = new \IntlDateFormatter(
$this->locale,
$format,
$timeFormat,
null,
\IntlDateFormatter::GREGORIAN
);
return $intlDateFormatter->getPattern();
}
return $format;
});
} | php | public function configureOptions(OptionsResolver $resolver)
{
$resolver->setNormalizer('format', function (Options $options, $format) {
if (isset($options['date_format']) && \is_string($options['date_format'])) {
return $options['date_format'];
}
if (\is_int($format)) {
$timeFormat = \IntlDateFormatter::NONE;
if ($options['dp_pick_time']) {
$timeFormat = $options['dp_use_seconds'] ?
DateTimeType::DEFAULT_TIME_FORMAT :
\IntlDateFormatter::SHORT;
}
$intlDateFormatter = new \IntlDateFormatter(
$this->locale,
$format,
$timeFormat,
null,
\IntlDateFormatter::GREGORIAN
);
return $intlDateFormatter->getPattern();
}
return $format;
});
} | [
"public",
"function",
"configureOptions",
"(",
"OptionsResolver",
"$",
"resolver",
")",
"{",
"$",
"resolver",
"->",
"setNormalizer",
"(",
"'format'",
",",
"function",
"(",
"Options",
"$",
"options",
",",
"$",
"format",
")",
"{",
"if",
"(",
"isset",
"(",
"$... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/Form/Type/BasePickerType.php#L75-L102 |
sonata-project/SonataCoreBundle | src/Form/Type/BasePickerType.php | BasePickerType.getCommonDefaults | protected function getCommonDefaults()
{
return [
'widget' => 'single_text',
'datepicker_use_button' => true,
'dp_pick_time' => true,
'dp_pick_date' => true,
'dp_use_current' => true,
'dp_min_date' => '1/1/1900',
'dp_max_date' => null,
'dp_show_today' => true,
'dp_language' => $this->locale,
'dp_default_date' => '',
'dp_disabled_dates' => [],
'dp_enabled_dates' => [],
'dp_icons' => [
'time' => 'fa fa-clock-o',
'date' => 'fa fa-calendar',
'up' => 'fa fa-chevron-up',
'down' => 'fa fa-chevron-down',
],
'dp_use_strict' => false,
'dp_side_by_side' => false,
'dp_days_of_week_disabled' => [],
'dp_collapse' => true,
'dp_calendar_weeks' => false,
'dp_view_mode' => 'days',
'dp_min_view_mode' => 'days',
];
} | php | protected function getCommonDefaults()
{
return [
'widget' => 'single_text',
'datepicker_use_button' => true,
'dp_pick_time' => true,
'dp_pick_date' => true,
'dp_use_current' => true,
'dp_min_date' => '1/1/1900',
'dp_max_date' => null,
'dp_show_today' => true,
'dp_language' => $this->locale,
'dp_default_date' => '',
'dp_disabled_dates' => [],
'dp_enabled_dates' => [],
'dp_icons' => [
'time' => 'fa fa-clock-o',
'date' => 'fa fa-calendar',
'up' => 'fa fa-chevron-up',
'down' => 'fa fa-chevron-down',
],
'dp_use_strict' => false,
'dp_side_by_side' => false,
'dp_days_of_week_disabled' => [],
'dp_collapse' => true,
'dp_calendar_weeks' => false,
'dp_view_mode' => 'days',
'dp_min_view_mode' => 'days',
];
} | [
"protected",
"function",
"getCommonDefaults",
"(",
")",
"{",
"return",
"[",
"'widget'",
"=>",
"'single_text'",
",",
"'datepicker_use_button'",
"=>",
"true",
",",
"'dp_pick_time'",
"=>",
"true",
",",
"'dp_pick_date'",
"=>",
"true",
",",
"'dp_use_current'",
"=>",
"t... | Gets base default options for the date pickers.
@return array | [
"Gets",
"base",
"default",
"options",
"for",
"the",
"date",
"pickers",
"."
] | train | https://github.com/sonata-project/SonataCoreBundle/blob/0bae37d1a123e27856c31634a17eed51294c8752/src/Form/Type/BasePickerType.php#L144-L173 |
reactphp/stream | src/ReadableResourceStream.php | ReadableResourceStream.isLegacyPipe | private function isLegacyPipe($resource)
{
if (\PHP_VERSION_ID < 50428 || (\PHP_VERSION_ID >= 50500 && \PHP_VERSION_ID < 50512)) {
$meta = \stream_get_meta_data($resource);
if (isset($meta['stream_type']) && $meta['stream_type'] === 'STDIO') {
return true;
}
}
return false;
} | php | private function isLegacyPipe($resource)
{
if (\PHP_VERSION_ID < 50428 || (\PHP_VERSION_ID >= 50500 && \PHP_VERSION_ID < 50512)) {
$meta = \stream_get_meta_data($resource);
if (isset($meta['stream_type']) && $meta['stream_type'] === 'STDIO') {
return true;
}
}
return false;
} | [
"private",
"function",
"isLegacyPipe",
"(",
"$",
"resource",
")",
"{",
"if",
"(",
"\\",
"PHP_VERSION_ID",
"<",
"50428",
"||",
"(",
"\\",
"PHP_VERSION_ID",
">=",
"50500",
"&&",
"\\",
"PHP_VERSION_ID",
"<",
"50512",
")",
")",
"{",
"$",
"meta",
"=",
"\\",
... | Returns whether this is a pipe resource in a legacy environment
This works around a legacy PHP bug (#61019) that was fixed in PHP 5.4.28+
and PHP 5.5.12+ and newer.
@param resource $resource
@return bool
@link https://github.com/reactphp/child-process/issues/40
@codeCoverageIgnore | [
"Returns",
"whether",
"this",
"is",
"a",
"pipe",
"resource",
"in",
"a",
"legacy",
"environment"
] | train | https://github.com/reactphp/stream/blob/50426855f7a77ddf43b9266c22320df5bf6c6ce6/src/ReadableResourceStream.php#L166-L176 |
reactphp/stream | src/Util.php | Util.pipe | public static function pipe(ReadableStreamInterface $source, WritableStreamInterface $dest, array $options = array())
{
// source not readable => NO-OP
if (!$source->isReadable()) {
return $dest;
}
// destination not writable => just pause() source
if (!$dest->isWritable()) {
$source->pause();
return $dest;
}
$dest->emit('pipe', array($source));
// forward all source data events as $dest->write()
$source->on('data', $dataer = function ($data) use ($source, $dest) {
$feedMore = $dest->write($data);
if (false === $feedMore) {
$source->pause();
}
});
$dest->on('close', function () use ($source, $dataer) {
$source->removeListener('data', $dataer);
$source->pause();
});
// forward destination drain as $source->resume()
$dest->on('drain', $drainer = function () use ($source) {
$source->resume();
});
$source->on('close', function () use ($dest, $drainer) {
$dest->removeListener('drain', $drainer);
});
// forward end event from source as $dest->end()
$end = isset($options['end']) ? $options['end'] : true;
if ($end) {
$source->on('end', $ender = function () use ($dest) {
$dest->end();
});
$dest->on('close', function () use ($source, $ender) {
$source->removeListener('end', $ender);
});
}
return $dest;
} | php | public static function pipe(ReadableStreamInterface $source, WritableStreamInterface $dest, array $options = array())
{
// source not readable => NO-OP
if (!$source->isReadable()) {
return $dest;
}
// destination not writable => just pause() source
if (!$dest->isWritable()) {
$source->pause();
return $dest;
}
$dest->emit('pipe', array($source));
// forward all source data events as $dest->write()
$source->on('data', $dataer = function ($data) use ($source, $dest) {
$feedMore = $dest->write($data);
if (false === $feedMore) {
$source->pause();
}
});
$dest->on('close', function () use ($source, $dataer) {
$source->removeListener('data', $dataer);
$source->pause();
});
// forward destination drain as $source->resume()
$dest->on('drain', $drainer = function () use ($source) {
$source->resume();
});
$source->on('close', function () use ($dest, $drainer) {
$dest->removeListener('drain', $drainer);
});
// forward end event from source as $dest->end()
$end = isset($options['end']) ? $options['end'] : true;
if ($end) {
$source->on('end', $ender = function () use ($dest) {
$dest->end();
});
$dest->on('close', function () use ($source, $ender) {
$source->removeListener('end', $ender);
});
}
return $dest;
} | [
"public",
"static",
"function",
"pipe",
"(",
"ReadableStreamInterface",
"$",
"source",
",",
"WritableStreamInterface",
"$",
"dest",
",",
"array",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"// source not readable => NO-OP",
"if",
"(",
"!",
"$",
"source",
... | Pipes all the data from the given $source into the $dest
@param ReadableStreamInterface $source
@param WritableStreamInterface $dest
@param array $options
@return WritableStreamInterface $dest stream as-is
@see ReadableStreamInterface::pipe() for more details | [
"Pipes",
"all",
"the",
"data",
"from",
"the",
"given",
"$source",
"into",
"the",
"$dest"
] | train | https://github.com/reactphp/stream/blob/50426855f7a77ddf43b9266c22320df5bf6c6ce6/src/Util.php#L16-L65 |
rcrowe/TwigBridge | src/Extension/Loader/Loader.php | Loader.parseCallable | protected function parseCallable($method, $callable)
{
$options = [];
if (is_array($callable)) {
$options = $callable;
if (isset($options['callback'])) {
$callable = $options['callback'];
unset($options['callback']);
} else {
$callable = $method;
}
}
// Support Laravel style class@method syntax
if (is_string($callable)) {
// Check for numeric index
if (!is_string($method)) {
$method = $callable;
}
if (strpos($callable, '@') !== false) {
$callable = explode('@', $callable, 2);
}
}
return [$method, $callable, $options];
} | php | protected function parseCallable($method, $callable)
{
$options = [];
if (is_array($callable)) {
$options = $callable;
if (isset($options['callback'])) {
$callable = $options['callback'];
unset($options['callback']);
} else {
$callable = $method;
}
}
// Support Laravel style class@method syntax
if (is_string($callable)) {
// Check for numeric index
if (!is_string($method)) {
$method = $callable;
}
if (strpos($callable, '@') !== false) {
$callable = explode('@', $callable, 2);
}
}
return [$method, $callable, $options];
} | [
"protected",
"function",
"parseCallable",
"(",
"$",
"method",
",",
"$",
"callable",
")",
"{",
"$",
"options",
"=",
"[",
"]",
";",
"if",
"(",
"is_array",
"(",
"$",
"callable",
")",
")",
"{",
"$",
"options",
"=",
"$",
"callable",
";",
"if",
"(",
"iss... | Parse callable & options.
@param int|string $method
@param string|array $callable
@return array | [
"Parse",
"callable",
"&",
"options",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Extension/Loader/Loader.php#L44-L72 |
rcrowe/TwigBridge | src/Extension/Loader/Functions.php | Functions.getFunctions | public function getFunctions()
{
$load = $this->config->get('twigbridge.extensions.functions', []);
$functions = [];
foreach ($load as $method => $callable) {
list($method, $callable, $options) = $this->parseCallable($method, $callable);
$function = new TwigFunction(
$method,
function () use ($callable) {
return call_user_func_array($callable, func_get_args());
},
$options
);
$functions[] = $function;
}
return $functions;
} | php | public function getFunctions()
{
$load = $this->config->get('twigbridge.extensions.functions', []);
$functions = [];
foreach ($load as $method => $callable) {
list($method, $callable, $options) = $this->parseCallable($method, $callable);
$function = new TwigFunction(
$method,
function () use ($callable) {
return call_user_func_array($callable, func_get_args());
},
$options
);
$functions[] = $function;
}
return $functions;
} | [
"public",
"function",
"getFunctions",
"(",
")",
"{",
"$",
"load",
"=",
"$",
"this",
"->",
"config",
"->",
"get",
"(",
"'twigbridge.extensions.functions'",
",",
"[",
"]",
")",
";",
"$",
"functions",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"load",
"as",... | {@inheritDoc} | [
"{"
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Extension/Loader/Functions.php#L35-L55 |
rcrowe/TwigBridge | src/Extension/Laravel/Session.php | Session.getFunctions | public function getFunctions()
{
return [
new TwigFunction('session', [$this->session, 'get']),
new TwigFunction('csrf_token', [$this->session, 'token'], ['is_safe' => ['html']]),
new TwigFunction('csrf_field', 'csrf_field', ['is_safe' => ['html']]),
new TwigFunction('method_field', 'method_field', ['is_safe' => ['html']]),
new TwigFunction('session_get', [$this->session, 'get']),
new TwigFunction('session_pull', [$this->session, 'pull']),
new TwigFunction('session_has', [$this->session, 'has']),
];
} | php | public function getFunctions()
{
return [
new TwigFunction('session', [$this->session, 'get']),
new TwigFunction('csrf_token', [$this->session, 'token'], ['is_safe' => ['html']]),
new TwigFunction('csrf_field', 'csrf_field', ['is_safe' => ['html']]),
new TwigFunction('method_field', 'method_field', ['is_safe' => ['html']]),
new TwigFunction('session_get', [$this->session, 'get']),
new TwigFunction('session_pull', [$this->session, 'pull']),
new TwigFunction('session_has', [$this->session, 'has']),
];
} | [
"public",
"function",
"getFunctions",
"(",
")",
"{",
"return",
"[",
"new",
"TwigFunction",
"(",
"'session'",
",",
"[",
"$",
"this",
"->",
"session",
",",
"'get'",
"]",
")",
",",
"new",
"TwigFunction",
"(",
"'csrf_token'",
",",
"[",
"$",
"this",
"->",
"... | {@inheritDoc} | [
"{"
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Extension/Laravel/Session.php#L49-L60 |
rcrowe/TwigBridge | src/Extension/Loader/Facades.php | Facades.getGlobals | public function getGlobals()
{
$load = $this->config->get('twigbridge.extensions.facades', []);
$globals = [];
foreach ($load as $facade => $options) {
list($facade, $callable, $options) = $this->parseCallable($facade, $options);
$globals[$facade] = new Caller($callable, $options);
}
return $globals;
} | php | public function getGlobals()
{
$load = $this->config->get('twigbridge.extensions.facades', []);
$globals = [];
foreach ($load as $facade => $options) {
list($facade, $callable, $options) = $this->parseCallable($facade, $options);
$globals[$facade] = new Caller($callable, $options);
}
return $globals;
} | [
"public",
"function",
"getGlobals",
"(",
")",
"{",
"$",
"load",
"=",
"$",
"this",
"->",
"config",
"->",
"get",
"(",
"'twigbridge.extensions.facades'",
",",
"[",
"]",
")",
";",
"$",
"globals",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"load",
"as",
"$"... | {@inheritDoc} | [
"{"
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Extension/Loader/Facades.php#L44-L56 |
rcrowe/TwigBridge | src/Extension/Laravel/Url.php | Url.getFunctions | public function getFunctions()
{
return [
new TwigFunction('asset', [$this->url, 'asset'], ['is_safe' => ['html']]),
new TwigFunction('action', [$this->url, 'action'], ['is_safe' => ['html']]),
new TwigFunction('url', [$this, 'url'], ['is_safe' => ['html']]),
new TwigFunction('route', [$this->url, 'route'], ['is_safe' => ['html']]),
new TwigFunction('route_has', [$this->router, 'has'], ['is_safe' => ['html']]),
new TwigFunction('secure_url', [$this->url, 'secure'], ['is_safe' => ['html']]),
new TwigFunction('secure_asset', [$this->url, 'secureAsset'], ['is_safe' => ['html']]),
new TwigFunction(
'url_*',
function ($name) {
$arguments = array_slice(func_get_args(), 1);
$name = IlluminateStr::camel($name);
return call_user_func_array([$this->url, $name], $arguments);
}
),
];
} | php | public function getFunctions()
{
return [
new TwigFunction('asset', [$this->url, 'asset'], ['is_safe' => ['html']]),
new TwigFunction('action', [$this->url, 'action'], ['is_safe' => ['html']]),
new TwigFunction('url', [$this, 'url'], ['is_safe' => ['html']]),
new TwigFunction('route', [$this->url, 'route'], ['is_safe' => ['html']]),
new TwigFunction('route_has', [$this->router, 'has'], ['is_safe' => ['html']]),
new TwigFunction('secure_url', [$this->url, 'secure'], ['is_safe' => ['html']]),
new TwigFunction('secure_asset', [$this->url, 'secureAsset'], ['is_safe' => ['html']]),
new TwigFunction(
'url_*',
function ($name) {
$arguments = array_slice(func_get_args(), 1);
$name = IlluminateStr::camel($name);
return call_user_func_array([$this->url, $name], $arguments);
}
),
];
} | [
"public",
"function",
"getFunctions",
"(",
")",
"{",
"return",
"[",
"new",
"TwigFunction",
"(",
"'asset'",
",",
"[",
"$",
"this",
"->",
"url",
",",
"'asset'",
"]",
",",
"[",
"'is_safe'",
"=>",
"[",
"'html'",
"]",
"]",
")",
",",
"new",
"TwigFunction",
... | {@inheritDoc} | [
"{"
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Extension/Laravel/Url.php#L58-L78 |
rcrowe/TwigBridge | src/Engine/Twig.php | Twig.get | public function get($path, array $data = [])
{
$data = array_merge($this->globalData, $data);
try {
$content = $this->compiler->load($path)->render($data);
} catch (Error $ex) {
$this->handleTwigError($ex);
}
return $content;
} | php | public function get($path, array $data = [])
{
$data = array_merge($this->globalData, $data);
try {
$content = $this->compiler->load($path)->render($data);
} catch (Error $ex) {
$this->handleTwigError($ex);
}
return $content;
} | [
"public",
"function",
"get",
"(",
"$",
"path",
",",
"array",
"$",
"data",
"=",
"[",
"]",
")",
"{",
"$",
"data",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"globalData",
",",
"$",
"data",
")",
";",
"try",
"{",
"$",
"content",
"=",
"$",
"this",
... | Get the evaluated contents of the view.
@param string $path Full file path to Twig template.
@param array $data
@throws Error|\ErrorException When unable to load the requested path.
@return string | [
"Get",
"the",
"evaluated",
"contents",
"of",
"the",
"view",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Engine/Twig.php#L86-L97 |
rcrowe/TwigBridge | src/Engine/Twig.php | Twig.handleTwigError | protected function handleTwigError(Error $ex)
{
$context = $ex->getSourceContext();
if (null === $context) {
throw $ex;
}
$templateFile = $context->getPath();
$templateLine = $ex->getTemplateLine();
if ($templateFile && file_exists($templateFile)) {
$file = $templateFile;
} elseif ($templateFile) {
// Attempt to locate full path to file
try {
$file = $this->loader->findTemplate($templateFile);
} catch (LoaderError $exception) {
// Unable to load template
}
}
if (isset($file)) {
$ex = new ErrorException($ex->getMessage(), 0, 1, $file, $templateLine, $ex);
}
throw $ex;
} | php | protected function handleTwigError(Error $ex)
{
$context = $ex->getSourceContext();
if (null === $context) {
throw $ex;
}
$templateFile = $context->getPath();
$templateLine = $ex->getTemplateLine();
if ($templateFile && file_exists($templateFile)) {
$file = $templateFile;
} elseif ($templateFile) {
// Attempt to locate full path to file
try {
$file = $this->loader->findTemplate($templateFile);
} catch (LoaderError $exception) {
// Unable to load template
}
}
if (isset($file)) {
$ex = new ErrorException($ex->getMessage(), 0, 1, $file, $templateLine, $ex);
}
throw $ex;
} | [
"protected",
"function",
"handleTwigError",
"(",
"Error",
"$",
"ex",
")",
"{",
"$",
"context",
"=",
"$",
"ex",
"->",
"getSourceContext",
"(",
")",
";",
"if",
"(",
"null",
"===",
"$",
"context",
")",
"{",
"throw",
"$",
"ex",
";",
"}",
"$",
"templateFi... | Handle a TwigError exception.
@param Error $ex
@throws Error|\ErrorException | [
"Handle",
"a",
"TwigError",
"exception",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Engine/Twig.php#L106-L133 |
rcrowe/TwigBridge | src/Extension/Bridge/Former.php | Former.getFunctions | public function getFunctions()
{
return [
new TwigFunction(
'former_*',
function ($name) {
$arguments = array_slice(func_get_args(), 1);
return call_user_func_array([$this->former, $name], $arguments);
}, ['is_safe' => ['html']]
),
];
} | php | public function getFunctions()
{
return [
new TwigFunction(
'former_*',
function ($name) {
$arguments = array_slice(func_get_args(), 1);
return call_user_func_array([$this->former, $name], $arguments);
}, ['is_safe' => ['html']]
),
];
} | [
"public",
"function",
"getFunctions",
"(",
")",
"{",
"return",
"[",
"new",
"TwigFunction",
"(",
"'former_*'",
",",
"function",
"(",
"$",
"name",
")",
"{",
"$",
"arguments",
"=",
"array_slice",
"(",
"func_get_args",
"(",
")",
",",
"1",
")",
";",
"return",... | {@inheritDoc} | [
"{"
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Extension/Bridge/Former.php#L50-L61 |
rcrowe/TwigBridge | src/Extension/Laravel/Auth.php | Auth.getFunctions | public function getFunctions()
{
return [
new TwigFunction('auth_check', [$this->auth, 'check']),
new TwigFunction('auth_guest', [$this->auth, 'guest']),
new TwigFunction('auth_user', [$this->auth, 'user']),
new TwigFunction('auth_guard', [$this->auth, 'guard']),
];
} | php | public function getFunctions()
{
return [
new TwigFunction('auth_check', [$this->auth, 'check']),
new TwigFunction('auth_guest', [$this->auth, 'guest']),
new TwigFunction('auth_user', [$this->auth, 'user']),
new TwigFunction('auth_guard', [$this->auth, 'guard']),
];
} | [
"public",
"function",
"getFunctions",
"(",
")",
"{",
"return",
"[",
"new",
"TwigFunction",
"(",
"'auth_check'",
",",
"[",
"$",
"this",
"->",
"auth",
",",
"'check'",
"]",
")",
",",
"new",
"TwigFunction",
"(",
"'auth_guest'",
",",
"[",
"$",
"this",
"->",
... | {@inheritDoc} | [
"{"
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Extension/Laravel/Auth.php#L49-L57 |
rcrowe/TwigBridge | src/Command/Lint.php | Lint.getFinder | public function getFinder(array $paths)
{
$finder = (empty($this->finder)) ? Finder::create() : $this->finder;
return $finder->files()->in($paths)->name('*.'.$this->laravel['twig.extension']);
} | php | public function getFinder(array $paths)
{
$finder = (empty($this->finder)) ? Finder::create() : $this->finder;
return $finder->files()->in($paths)->name('*.'.$this->laravel['twig.extension']);
} | [
"public",
"function",
"getFinder",
"(",
"array",
"$",
"paths",
")",
"{",
"$",
"finder",
"=",
"(",
"empty",
"(",
"$",
"this",
"->",
"finder",
")",
")",
"?",
"Finder",
"::",
"create",
"(",
")",
":",
"$",
"this",
"->",
"finder",
";",
"return",
"$",
... | Get a finder instance of Twig files in the specified directories.
@param array $paths Paths to search for files in.
@return \Symfony\Component\Finder\Finder | [
"Get",
"a",
"finder",
"instance",
"of",
"Twig",
"files",
"in",
"the",
"specified",
"directories",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Command/Lint.php#L60-L65 |
rcrowe/TwigBridge | src/Command/Lint.php | Lint.handle | public function handle()
{
$this->twig = $this->laravel['twig'];
$format = $this->option('format');
// Check STDIN for the template
if (ftell(STDIN) === 0) {
// Read template in
$template = '';
while (!feof(STDIN)) {
$template .= fread(STDIN, 1024);
}
return $this->display([$this->validate($template)], $format);
}
$files = $this->getFiles($this->argument('filename'), $this->option('file'), $this->option('directory'));
$details = [];
foreach ($files as $file) {
try {
$template = $this->getContents($file);
} catch (LoaderError $e) {
throw new RuntimeException(sprintf('File or directory "%s" is not readable', $file));
}
$details[] = $this->validate($template, $file);
}
return $this->display($details, $format);
} | php | public function handle()
{
$this->twig = $this->laravel['twig'];
$format = $this->option('format');
// Check STDIN for the template
if (ftell(STDIN) === 0) {
// Read template in
$template = '';
while (!feof(STDIN)) {
$template .= fread(STDIN, 1024);
}
return $this->display([$this->validate($template)], $format);
}
$files = $this->getFiles($this->argument('filename'), $this->option('file'), $this->option('directory'));
$details = [];
foreach ($files as $file) {
try {
$template = $this->getContents($file);
} catch (LoaderError $e) {
throw new RuntimeException(sprintf('File or directory "%s" is not readable', $file));
}
$details[] = $this->validate($template, $file);
}
return $this->display($details, $format);
} | [
"public",
"function",
"handle",
"(",
")",
"{",
"$",
"this",
"->",
"twig",
"=",
"$",
"this",
"->",
"laravel",
"[",
"'twig'",
"]",
";",
"$",
"format",
"=",
"$",
"this",
"->",
"option",
"(",
"'format'",
")",
";",
"// Check STDIN for the template",
"if",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Command/Lint.php#L82-L113 |
rcrowe/TwigBridge | src/Command/Lint.php | Lint.getFiles | protected function getFiles($filename, array $files, array $directories)
{
// Get files from passed in options
$search = $files;
$paths = $this->laravel['view']->getFinder()->getPaths();
if (!empty($filename)) {
$search[] = $filename;
}
if (!empty($directories)) {
$search_directories = [];
foreach ($directories as $directory) {
foreach ($paths as $path) {
if (is_dir($path.'/'.$directory)) {
$search_directories[] = $path.'/'.$directory;
}
}
}
if (!empty($search_directories)) {
// Get those files from the search directory
foreach ($this->getFinder($search_directories) as $file) {
$search[] = $file->getRealPath();
}
}
}
// If no files passed, use the view paths
if (empty($search)) {
foreach ($this->getFinder($paths) as $file) {
$search[] = $file->getRealPath();
}
}
return $search;
} | php | protected function getFiles($filename, array $files, array $directories)
{
// Get files from passed in options
$search = $files;
$paths = $this->laravel['view']->getFinder()->getPaths();
if (!empty($filename)) {
$search[] = $filename;
}
if (!empty($directories)) {
$search_directories = [];
foreach ($directories as $directory) {
foreach ($paths as $path) {
if (is_dir($path.'/'.$directory)) {
$search_directories[] = $path.'/'.$directory;
}
}
}
if (!empty($search_directories)) {
// Get those files from the search directory
foreach ($this->getFinder($search_directories) as $file) {
$search[] = $file->getRealPath();
}
}
}
// If no files passed, use the view paths
if (empty($search)) {
foreach ($this->getFinder($paths) as $file) {
$search[] = $file->getRealPath();
}
}
return $search;
} | [
"protected",
"function",
"getFiles",
"(",
"$",
"filename",
",",
"array",
"$",
"files",
",",
"array",
"$",
"directories",
")",
"{",
"// Get files from passed in options",
"$",
"search",
"=",
"$",
"files",
";",
"$",
"paths",
"=",
"$",
"this",
"->",
"laravel",
... | Gets an array of files to lint.
@param string $filename Single file to check.
@param array $files Array of files to check.
@param array $directories Array of directories to get the files from.
@return array | [
"Gets",
"an",
"array",
"of",
"files",
"to",
"lint",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Command/Lint.php#L124-L161 |
rcrowe/TwigBridge | src/Command/Lint.php | Lint.validate | protected function validate($template, $file = null)
{
try {
$this->twig->parse($this->twig->tokenize($template, $file));
} catch (Error $e) {
return [
'template' => $template,
'file' => $file,
'valid' => false,
'exception' => $e,
];
}
return [
'template' => $template,
'file' => $file,
'valid' => true,
];
} | php | protected function validate($template, $file = null)
{
try {
$this->twig->parse($this->twig->tokenize($template, $file));
} catch (Error $e) {
return [
'template' => $template,
'file' => $file,
'valid' => false,
'exception' => $e,
];
}
return [
'template' => $template,
'file' => $file,
'valid' => true,
];
} | [
"protected",
"function",
"validate",
"(",
"$",
"template",
",",
"$",
"file",
"=",
"null",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"twig",
"->",
"parse",
"(",
"$",
"this",
"->",
"twig",
"->",
"tokenize",
"(",
"$",
"template",
",",
"$",
"file",
")",... | Validate the template.
@param string $template Twig template.
@param string $file Filename of the template.
@return array | [
"Validate",
"the",
"template",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Command/Lint.php#L183-L201 |
rcrowe/TwigBridge | src/Command/Lint.php | Lint.displayText | protected function displayText(array $details, $verbose = false)
{
$errors = 0;
foreach ($details as $info) {
if ($info['valid'] && $verbose) {
$file = ($info['file']) ? ' in '.$info['file'] : '';
$this->line('<info>OK</info>'.$file);
} elseif (!$info['valid']) {
$errors++;
$this->renderException($info);
}
}
// Output total number of successful files
$success = count($details) - $errors;
$total = count($details);
$this->comment(sprintf('%d/%d valid files', $success, $total));
return min($errors, 1);
} | php | protected function displayText(array $details, $verbose = false)
{
$errors = 0;
foreach ($details as $info) {
if ($info['valid'] && $verbose) {
$file = ($info['file']) ? ' in '.$info['file'] : '';
$this->line('<info>OK</info>'.$file);
} elseif (!$info['valid']) {
$errors++;
$this->renderException($info);
}
}
// Output total number of successful files
$success = count($details) - $errors;
$total = count($details);
$this->comment(sprintf('%d/%d valid files', $success, $total));
return min($errors, 1);
} | [
"protected",
"function",
"displayText",
"(",
"array",
"$",
"details",
",",
"$",
"verbose",
"=",
"false",
")",
"{",
"$",
"errors",
"=",
"0",
";",
"foreach",
"(",
"$",
"details",
"as",
"$",
"info",
")",
"{",
"if",
"(",
"$",
"info",
"[",
"'valid'",
"]... | Output the results as text.
@param array $details Validation results from all linted files.
@param bool $verbose
@return int | [
"Output",
"the",
"results",
"as",
"text",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Command/Lint.php#L237-L258 |
rcrowe/TwigBridge | src/Command/Lint.php | Lint.displayJson | protected function displayJson(array $details)
{
$errors = 0;
array_walk(
$details,
function (&$info) use (&$errors) {
$info['file'] = (string) $info['file'];
unset($info['template']);
if (!$info['valid']) {
$info['message'] = $info['exception']->getMessage();
unset($info['exception']);
$errors++;
}
}
);
$this->line(json_encode($details, JSON_PRETTY_PRINT));
return min($errors, 1);
} | php | protected function displayJson(array $details)
{
$errors = 0;
array_walk(
$details,
function (&$info) use (&$errors) {
$info['file'] = (string) $info['file'];
unset($info['template']);
if (!$info['valid']) {
$info['message'] = $info['exception']->getMessage();
unset($info['exception']);
$errors++;
}
}
);
$this->line(json_encode($details, JSON_PRETTY_PRINT));
return min($errors, 1);
} | [
"protected",
"function",
"displayJson",
"(",
"array",
"$",
"details",
")",
"{",
"$",
"errors",
"=",
"0",
";",
"array_walk",
"(",
"$",
"details",
",",
"function",
"(",
"&",
"$",
"info",
")",
"use",
"(",
"&",
"$",
"errors",
")",
"{",
"$",
"info",
"["... | Output the results as json.
@param array $details Validation results from all linted files.
@return int | [
"Output",
"the",
"results",
"as",
"json",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Command/Lint.php#L267-L288 |
rcrowe/TwigBridge | src/Command/Lint.php | Lint.renderException | protected function renderException(array $info)
{
$file = $info['file'];
$exception = $info['exception'];
$line = $exception->getTemplateLine();
$lines = $this->getContext($info['template'], $line);
if ($file) {
$this->line(sprintf('<error>Fail</error> in %s (line %s)', $file, $line));
} else {
$this->line(sprintf('<error>Fail</error> (line %s)', $line));
}
foreach ($lines as $no => $code) {
$this->line(
sprintf(
"%s %-6s %s",
$no == $line ? '<error>>></error>' : ' ',
$no,
$code
)
);
if ($no == $line) {
$this->line(sprintf('<error>>> %s</error> ', $exception->getRawMessage()));
}
}
} | php | protected function renderException(array $info)
{
$file = $info['file'];
$exception = $info['exception'];
$line = $exception->getTemplateLine();
$lines = $this->getContext($info['template'], $line);
if ($file) {
$this->line(sprintf('<error>Fail</error> in %s (line %s)', $file, $line));
} else {
$this->line(sprintf('<error>Fail</error> (line %s)', $line));
}
foreach ($lines as $no => $code) {
$this->line(
sprintf(
"%s %-6s %s",
$no == $line ? '<error>>></error>' : ' ',
$no,
$code
)
);
if ($no == $line) {
$this->line(sprintf('<error>>> %s</error> ', $exception->getRawMessage()));
}
}
} | [
"protected",
"function",
"renderException",
"(",
"array",
"$",
"info",
")",
"{",
"$",
"file",
"=",
"$",
"info",
"[",
"'file'",
"]",
";",
"$",
"exception",
"=",
"$",
"info",
"[",
"'exception'",
"]",
";",
"$",
"line",
"=",
"$",
"exception",
"->",
"getT... | Output the error to the console.
@param array Details for the file that failed to be linted.
@return void | [
"Output",
"the",
"error",
"to",
"the",
"console",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Command/Lint.php#L297-L325 |
rcrowe/TwigBridge | src/Bridge.php | Bridge.lint | public function lint($file)
{
$template = $this->app['twig.loader.viewfinder']->getSourceContext($file);
if (!$template) {
throw new InvalidArgumentException('Unable to find file: '.$file);
}
try {
$this->parse($this->tokenize($template, $file));
} catch (Error $e) {
return false;
}
return true;
} | php | public function lint($file)
{
$template = $this->app['twig.loader.viewfinder']->getSourceContext($file);
if (!$template) {
throw new InvalidArgumentException('Unable to find file: '.$file);
}
try {
$this->parse($this->tokenize($template, $file));
} catch (Error $e) {
return false;
}
return true;
} | [
"public",
"function",
"lint",
"(",
"$",
"file",
")",
"{",
"$",
"template",
"=",
"$",
"this",
"->",
"app",
"[",
"'twig.loader.viewfinder'",
"]",
"->",
"getSourceContext",
"(",
"$",
"file",
")",
";",
"if",
"(",
"!",
"$",
"template",
")",
"{",
"throw",
... | Lint (check) the syntax of a file on the view paths.
@param string $file File to check. Supports dot-syntax.
@return bool Whether the file passed or not. | [
"Lint",
"(",
"check",
")",
"the",
"syntax",
"of",
"a",
"file",
"on",
"the",
"view",
"paths",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Bridge.php#L89-L104 |
rcrowe/TwigBridge | src/Bridge.php | Bridge.mergeShared | public function mergeShared(array $context)
{
// we don't use array_merge as the context being generally
// bigger than globals, this code is faster.
foreach ($this->app['view']->getShared() as $key => $value) {
if (!array_key_exists($key, $context)) {
$context[$key] = $value;
}
}
return $context;
} | php | public function mergeShared(array $context)
{
// we don't use array_merge as the context being generally
// bigger than globals, this code is faster.
foreach ($this->app['view']->getShared() as $key => $value) {
if (!array_key_exists($key, $context)) {
$context[$key] = $value;
}
}
return $context;
} | [
"public",
"function",
"mergeShared",
"(",
"array",
"$",
"context",
")",
"{",
"// we don't use array_merge as the context being generally",
"// bigger than globals, this code is faster.",
"foreach",
"(",
"$",
"this",
"->",
"app",
"[",
"'view'",
"]",
"->",
"getShared",
"(",... | Merges a context with the shared variables, same as mergeGlobals()
@param array $context An array representing the context
@return array The context merged with the globals | [
"Merges",
"a",
"context",
"with",
"the",
"shared",
"variables",
"same",
"as",
"mergeGlobals",
"()"
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Bridge.php#L113-L124 |
rcrowe/TwigBridge | src/Bridge.php | Bridge.normalizeName | protected function normalizeName($name)
{
$extension = '.' . $this->app['twig.extension'];
$length = strlen($extension);
if (substr($name, -$length, $length) === $extension) {
$name = substr($name, 0, -$length);
}
// Normalize namespace and delimiters
$delimiter = ViewFinderInterface::HINT_PATH_DELIMITER;
if (strpos($name, $delimiter) === false) {
return str_replace('/', '.', $name);
}
list($namespace, $name) = explode($delimiter, $name);
return $namespace.$delimiter.str_replace('/', '.', $name);
} | php | protected function normalizeName($name)
{
$extension = '.' . $this->app['twig.extension'];
$length = strlen($extension);
if (substr($name, -$length, $length) === $extension) {
$name = substr($name, 0, -$length);
}
// Normalize namespace and delimiters
$delimiter = ViewFinderInterface::HINT_PATH_DELIMITER;
if (strpos($name, $delimiter) === false) {
return str_replace('/', '.', $name);
}
list($namespace, $name) = explode($delimiter, $name);
return $namespace.$delimiter.str_replace('/', '.', $name);
} | [
"protected",
"function",
"normalizeName",
"(",
"$",
"name",
")",
"{",
"$",
"extension",
"=",
"'.'",
".",
"$",
"this",
"->",
"app",
"[",
"'twig.extension'",
"]",
";",
"$",
"length",
"=",
"strlen",
"(",
"$",
"extension",
")",
";",
"if",
"(",
"substr",
... | Normalize a view name.
@param string $name
@return string | [
"Normalize",
"a",
"view",
"name",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Bridge.php#L133-L151 |
rcrowe/TwigBridge | src/Extension/Laravel/Str.php | Str.getFunctions | public function getFunctions()
{
return [
new TwigFunction(
'str_*',
function ($name) {
$arguments = array_slice(func_get_args(), 1);
$name = IlluminateStr::camel($name);
return call_user_func_array([$this->callback, $name], $arguments);
}
),
];
} | php | public function getFunctions()
{
return [
new TwigFunction(
'str_*',
function ($name) {
$arguments = array_slice(func_get_args(), 1);
$name = IlluminateStr::camel($name);
return call_user_func_array([$this->callback, $name], $arguments);
}
),
];
} | [
"public",
"function",
"getFunctions",
"(",
")",
"{",
"return",
"[",
"new",
"TwigFunction",
"(",
"'str_*'",
",",
"function",
"(",
"$",
"name",
")",
"{",
"$",
"arguments",
"=",
"array_slice",
"(",
"func_get_args",
"(",
")",
",",
"1",
")",
";",
"$",
"name... | {@inheritDoc} | [
"{"
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Extension/Laravel/Str.php#L62-L75 |
rcrowe/TwigBridge | src/Extension/Laravel/Str.php | Str.getFilters | public function getFilters()
{
return [
new TwigFilter('camel_case', [$this->callback, 'camel']),
new TwigFilter('snake_case', [$this->callback, 'snake']),
new TwigFilter('studly_case', [$this->callback, 'studly']),
new TwigFilter(
'str_*',
function ($name) {
$arguments = array_slice(func_get_args(), 1);
$name = IlluminateStr::camel($name);
return call_user_func_array([$this->callback, $name], $arguments);
}
),
];
} | php | public function getFilters()
{
return [
new TwigFilter('camel_case', [$this->callback, 'camel']),
new TwigFilter('snake_case', [$this->callback, 'snake']),
new TwigFilter('studly_case', [$this->callback, 'studly']),
new TwigFilter(
'str_*',
function ($name) {
$arguments = array_slice(func_get_args(), 1);
$name = IlluminateStr::camel($name);
return call_user_func_array([$this->callback, $name], $arguments);
}
),
];
} | [
"public",
"function",
"getFilters",
"(",
")",
"{",
"return",
"[",
"new",
"TwigFilter",
"(",
"'camel_case'",
",",
"[",
"$",
"this",
"->",
"callback",
",",
"'camel'",
"]",
")",
",",
"new",
"TwigFilter",
"(",
"'snake_case'",
",",
"[",
"$",
"this",
"->",
"... | {@inheritDoc} | [
"{"
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Extension/Laravel/Str.php#L80-L96 |
rcrowe/TwigBridge | src/Extension/Laravel/Input.php | Input.getFunctions | public function getFunctions()
{
return [
new TwigFunction('input_get', [$this->request, 'input']),
new TwigFunction('input_old', [$this->request, 'old']),
new TwigFunction('input_has', [$this->request, 'has']),
new TwigFunction('old', [$this->request, 'old']),
];
} | php | public function getFunctions()
{
return [
new TwigFunction('input_get', [$this->request, 'input']),
new TwigFunction('input_old', [$this->request, 'old']),
new TwigFunction('input_has', [$this->request, 'has']),
new TwigFunction('old', [$this->request, 'old']),
];
} | [
"public",
"function",
"getFunctions",
"(",
")",
"{",
"return",
"[",
"new",
"TwigFunction",
"(",
"'input_get'",
",",
"[",
"$",
"this",
"->",
"request",
",",
"'input'",
"]",
")",
",",
"new",
"TwigFunction",
"(",
"'input_old'",
",",
"[",
"$",
"this",
"->",
... | {@inheritDoc} | [
"{"
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Extension/Laravel/Input.php#L49-L57 |
rcrowe/TwigBridge | src/Twig/Template.php | Template.display | public function display(array $context, array $blocks = [])
{
if (!isset($context['__env'])) {
$context = $this->env->mergeShared($context);
}
if ($this->shouldFireEvents()) {
$context = $this->fireEvents($context);
}
parent::display($context, $blocks);
} | php | public function display(array $context, array $blocks = [])
{
if (!isset($context['__env'])) {
$context = $this->env->mergeShared($context);
}
if ($this->shouldFireEvents()) {
$context = $this->fireEvents($context);
}
parent::display($context, $blocks);
} | [
"public",
"function",
"display",
"(",
"array",
"$",
"context",
",",
"array",
"$",
"blocks",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"context",
"[",
"'__env'",
"]",
")",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"env",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Twig/Template.php#L31-L42 |
rcrowe/TwigBridge | src/Twig/Template.php | Template.fireEvents | public function fireEvents($context)
{
if (!isset($context['__env'])) {
return $context;
}
/** @var \Illuminate\View\Factory $factory */
$env = $context['__env'];
$viewName = $this->name ?: $this->getTemplateName();
$view = new View(
$env,
$env->getEngineResolver()->resolve('twig'),
$viewName,
null,
$context
);
$env->callCreator($view);
$env->callComposer($view);
return $view->getData();
} | php | public function fireEvents($context)
{
if (!isset($context['__env'])) {
return $context;
}
/** @var \Illuminate\View\Factory $factory */
$env = $context['__env'];
$viewName = $this->name ?: $this->getTemplateName();
$view = new View(
$env,
$env->getEngineResolver()->resolve('twig'),
$viewName,
null,
$context
);
$env->callCreator($view);
$env->callComposer($view);
return $view->getData();
} | [
"public",
"function",
"fireEvents",
"(",
"$",
"context",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"context",
"[",
"'__env'",
"]",
")",
")",
"{",
"return",
"$",
"context",
";",
"}",
"/** @var \\Illuminate\\View\\Factory $factory */",
"$",
"env",
"=",
"$... | Fire the creator/composer events and return the modified context.
@param $context Old context.
@return array New context if __env is passed in, else the passed in context is returned. | [
"Fire",
"the",
"creator",
"/",
"composer",
"events",
"and",
"return",
"the",
"modified",
"context",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Twig/Template.php#L51-L71 |
rcrowe/TwigBridge | src/Command/Clean.php | Clean.handle | public function handle()
{
$twig = $this->laravel['twig'];
$files = $this->laravel['files'];
$cacheDir = $twig->getCache();
$files->deleteDirectory($cacheDir);
if ($files->exists($cacheDir)) {
$this->error('Twig cache failed to be cleaned');
} else {
$this->info('Twig cache cleaned');
}
} | php | public function handle()
{
$twig = $this->laravel['twig'];
$files = $this->laravel['files'];
$cacheDir = $twig->getCache();
$files->deleteDirectory($cacheDir);
if ($files->exists($cacheDir)) {
$this->error('Twig cache failed to be cleaned');
} else {
$this->info('Twig cache cleaned');
}
} | [
"public",
"function",
"handle",
"(",
")",
"{",
"$",
"twig",
"=",
"$",
"this",
"->",
"laravel",
"[",
"'twig'",
"]",
";",
"$",
"files",
"=",
"$",
"this",
"->",
"laravel",
"[",
"'files'",
"]",
";",
"$",
"cacheDir",
"=",
"$",
"twig",
"->",
"getCache",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Command/Clean.php#L36-L49 |
rcrowe/TwigBridge | src/Extension/Laravel/Html.php | Html.getFunctions | public function getFunctions()
{
return [
new TwigFunction('link_to', [$this->html, 'link'], ['is_safe' => ['html']]),
new TwigFunction('link_to_asset', [$this->html, 'linkAsset'], ['is_safe' => ['html']]),
new TwigFunction('link_to_route', [$this->html, 'linkRoute'], ['is_safe' => ['html']]),
new TwigFunction('link_to_action', [$this->html, 'linkAction'], ['is_safe' => ['html']]),
new TwigFunction(
'html_*',
function ($name) {
$arguments = array_slice(func_get_args(), 1);
$name = IlluminateStr::camel($name);
return call_user_func_array([$this->html, $name], $arguments);
},
[
'is_safe' => ['html'],
]
),
];
} | php | public function getFunctions()
{
return [
new TwigFunction('link_to', [$this->html, 'link'], ['is_safe' => ['html']]),
new TwigFunction('link_to_asset', [$this->html, 'linkAsset'], ['is_safe' => ['html']]),
new TwigFunction('link_to_route', [$this->html, 'linkRoute'], ['is_safe' => ['html']]),
new TwigFunction('link_to_action', [$this->html, 'linkAction'], ['is_safe' => ['html']]),
new TwigFunction(
'html_*',
function ($name) {
$arguments = array_slice(func_get_args(), 1);
$name = IlluminateStr::camel($name);
return call_user_func_array([$this->html, $name], $arguments);
},
[
'is_safe' => ['html'],
]
),
];
} | [
"public",
"function",
"getFunctions",
"(",
")",
"{",
"return",
"[",
"new",
"TwigFunction",
"(",
"'link_to'",
",",
"[",
"$",
"this",
"->",
"html",
",",
"'link'",
"]",
",",
"[",
"'is_safe'",
"=>",
"[",
"'html'",
"]",
"]",
")",
",",
"new",
"TwigFunction",... | {@inheritDoc} | [
"{"
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Extension/Laravel/Html.php#L50-L70 |
rcrowe/TwigBridge | src/Engine/Compiler.php | Compiler.isExpired | public function isExpired($path)
{
$time = filemtime($this->getCompiledPath($path));
return $this->twig->isTemplateFresh($path, $time);
} | php | public function isExpired($path)
{
$time = filemtime($this->getCompiledPath($path));
return $this->twig->isTemplateFresh($path, $time);
} | [
"public",
"function",
"isExpired",
"(",
"$",
"path",
")",
"{",
"$",
"time",
"=",
"filemtime",
"(",
"$",
"this",
"->",
"getCompiledPath",
"(",
"$",
"path",
")",
")",
";",
"return",
"$",
"this",
"->",
"twig",
"->",
"isTemplateFresh",
"(",
"$",
"path",
... | Twig handles this for us. Here to satisfy interface.
{@inheritdoc} | [
"Twig",
"handles",
"this",
"for",
"us",
".",
"Here",
"to",
"satisfy",
"interface",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Engine/Compiler.php#L66-L71 |
rcrowe/TwigBridge | src/Engine/Compiler.php | Compiler.load | public function load($path)
{
// Load template
try {
$template = $this->twig->loadTemplate($path);
} catch (LoaderError $e) {
throw new InvalidArgumentException("Error loading $path: ". $e->getMessage(), $e->getCode(), $e);
}
if ($template instanceof Template) {
// Events are already fired by the View Environment
$template->setFiredEvents(true);
}
return $template;
} | php | public function load($path)
{
// Load template
try {
$template = $this->twig->loadTemplate($path);
} catch (LoaderError $e) {
throw new InvalidArgumentException("Error loading $path: ". $e->getMessage(), $e->getCode(), $e);
}
if ($template instanceof Template) {
// Events are already fired by the View Environment
$template->setFiredEvents(true);
}
return $template;
} | [
"public",
"function",
"load",
"(",
"$",
"path",
")",
"{",
"// Load template",
"try",
"{",
"$",
"template",
"=",
"$",
"this",
"->",
"twig",
"->",
"loadTemplate",
"(",
"$",
"path",
")",
";",
"}",
"catch",
"(",
"LoaderError",
"$",
"e",
")",
"{",
"throw"... | Compile the view at the given path.
@param string $path
@throws \InvalidArgumentException
@return string \TwigBridge\Twig\Template | [
"Compile",
"the",
"view",
"at",
"the",
"given",
"path",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Engine/Compiler.php#L95-L110 |
rcrowe/TwigBridge | src/ServiceProvider.php | ServiceProvider.register | public function register()
{
$this->registerCommands();
$this->registerOptions();
$this->registerLoaders();
$this->registerEngine();
$this->registerAliases();
} | php | public function register()
{
$this->registerCommands();
$this->registerOptions();
$this->registerLoaders();
$this->registerEngine();
$this->registerAliases();
} | [
"public",
"function",
"register",
"(",
")",
"{",
"$",
"this",
"->",
"registerCommands",
"(",
")",
";",
"$",
"this",
"->",
"registerOptions",
"(",
")",
";",
"$",
"this",
"->",
"registerLoaders",
"(",
")",
";",
"$",
"this",
"->",
"registerEngine",
"(",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/ServiceProvider.php#L39-L46 |
rcrowe/TwigBridge | src/ServiceProvider.php | ServiceProvider.registerCommands | protected function registerCommands()
{
$this->app->bindIf('command.twig', function () {
return new Command\TwigBridge;
});
$this->app->bindIf('command.twig.clean', function () {
return new Command\Clean;
});
$this->app->bindIf('command.twig.lint', function () {
return new Command\Lint;
});
$this->commands(
'command.twig',
'command.twig.clean',
'command.twig.lint'
);
} | php | protected function registerCommands()
{
$this->app->bindIf('command.twig', function () {
return new Command\TwigBridge;
});
$this->app->bindIf('command.twig.clean', function () {
return new Command\Clean;
});
$this->app->bindIf('command.twig.lint', function () {
return new Command\Lint;
});
$this->commands(
'command.twig',
'command.twig.clean',
'command.twig.lint'
);
} | [
"protected",
"function",
"registerCommands",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"bindIf",
"(",
"'command.twig'",
",",
"function",
"(",
")",
"{",
"return",
"new",
"Command",
"\\",
"TwigBridge",
";",
"}",
")",
";",
"$",
"this",
"->",
"app",
"... | Register console command bindings.
@return void | [
"Register",
"console",
"command",
"bindings",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/ServiceProvider.php#L114-L133 |
rcrowe/TwigBridge | src/ServiceProvider.php | ServiceProvider.registerOptions | protected function registerOptions()
{
$this->app->bindIf('twig.extension', function () {
return $this->app['config']->get('twigbridge.twig.extension');
});
$this->app->bindIf('twig.options', function () {
$options = $this->app['config']->get('twigbridge.twig.environment', []);
// Check whether we have the cache path set
if (!isset($options['cache']) || is_null($options['cache'])) {
// No cache path set for Twig, lets set to the Laravel views storage folder
$options['cache'] = storage_path('framework/views/twig');
}
return $options;
});
$this->app->bindIf('twig.extensions', function () {
$load = $this->app['config']->get('twigbridge.extensions.enabled', []);
// Is debug enabled?
// If so enable debug extension
$options = $this->app['twig.options'];
$isDebug = (bool) (isset($options['debug'])) ? $options['debug'] : false;
if ($isDebug) {
array_unshift($load, DebugExtension::class);
}
return $load;
});
$this->app->bindIf('twig.lexer', function () {
return null;
});
} | php | protected function registerOptions()
{
$this->app->bindIf('twig.extension', function () {
return $this->app['config']->get('twigbridge.twig.extension');
});
$this->app->bindIf('twig.options', function () {
$options = $this->app['config']->get('twigbridge.twig.environment', []);
// Check whether we have the cache path set
if (!isset($options['cache']) || is_null($options['cache'])) {
// No cache path set for Twig, lets set to the Laravel views storage folder
$options['cache'] = storage_path('framework/views/twig');
}
return $options;
});
$this->app->bindIf('twig.extensions', function () {
$load = $this->app['config']->get('twigbridge.extensions.enabled', []);
// Is debug enabled?
// If so enable debug extension
$options = $this->app['twig.options'];
$isDebug = (bool) (isset($options['debug'])) ? $options['debug'] : false;
if ($isDebug) {
array_unshift($load, DebugExtension::class);
}
return $load;
});
$this->app->bindIf('twig.lexer', function () {
return null;
});
} | [
"protected",
"function",
"registerOptions",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"bindIf",
"(",
"'twig.extension'",
",",
"function",
"(",
")",
"{",
"return",
"$",
"this",
"->",
"app",
"[",
"'config'",
"]",
"->",
"get",
"(",
"'twigbridge.twig.exte... | Register Twig config option bindings.
@return void | [
"Register",
"Twig",
"config",
"option",
"bindings",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/ServiceProvider.php#L140-L176 |
rcrowe/TwigBridge | src/ServiceProvider.php | ServiceProvider.registerLoaders | protected function registerLoaders()
{
// The array used in the ArrayLoader
$this->app->bindIf('twig.templates', function () {
return [];
});
$this->app->bindIf('twig.loader.array', function ($app) {
return new ArrayLoader($app['twig.templates']);
});
$this->app->bindIf('twig.loader.viewfinder', function () {
return new Twig\Loader(
$this->app['files'],
$this->app['view']->getFinder(),
$this->app['twig.extension']
);
});
$this->app->bindIf(
'twig.loader',
function () {
return new ChainLoader([
$this->app['twig.loader.array'],
$this->app['twig.loader.viewfinder'],
]);
},
true
);
} | php | protected function registerLoaders()
{
// The array used in the ArrayLoader
$this->app->bindIf('twig.templates', function () {
return [];
});
$this->app->bindIf('twig.loader.array', function ($app) {
return new ArrayLoader($app['twig.templates']);
});
$this->app->bindIf('twig.loader.viewfinder', function () {
return new Twig\Loader(
$this->app['files'],
$this->app['view']->getFinder(),
$this->app['twig.extension']
);
});
$this->app->bindIf(
'twig.loader',
function () {
return new ChainLoader([
$this->app['twig.loader.array'],
$this->app['twig.loader.viewfinder'],
]);
},
true
);
} | [
"protected",
"function",
"registerLoaders",
"(",
")",
"{",
"// The array used in the ArrayLoader",
"$",
"this",
"->",
"app",
"->",
"bindIf",
"(",
"'twig.templates'",
",",
"function",
"(",
")",
"{",
"return",
"[",
"]",
";",
"}",
")",
";",
"$",
"this",
"->",
... | Register Twig loader bindings.
@return void | [
"Register",
"Twig",
"loader",
"bindings",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/ServiceProvider.php#L183-L212 |
rcrowe/TwigBridge | src/ServiceProvider.php | ServiceProvider.registerEngine | protected function registerEngine()
{
$this->app->bindIf(
'twig',
function () {
$extensions = $this->app['twig.extensions'];
$lexer = $this->app['twig.lexer'];
$twig = new Bridge(
$this->app['twig.loader'],
$this->app['twig.options'],
$this->app
);
// Instantiate and add extensions
foreach ($extensions as $extension) {
// Get an instance of the extension
// Support for string, closure and an object
if (is_string($extension)) {
try {
$extension = $this->app->make($extension);
} catch (\Exception $e) {
throw new InvalidArgumentException(
"Cannot instantiate Twig extension '$extension': " . $e->getMessage()
);
}
} elseif (is_callable($extension)) {
$extension = $extension($this->app, $twig);
} elseif (!is_a($extension, ExtensionInterface::class)) {
throw new InvalidArgumentException('Incorrect extension type');
}
$twig->addExtension($extension);
}
// Set lexer
if (is_a($lexer, Lexer::class)) {
$twig->setLexer($lexer);
}
return $twig;
},
true
);
$this->app->alias('twig', Twig_Environment::class);
$this->app->alias('twig', Bridge::class);
$this->app->bindIf('twig.compiler', function () {
return new Engine\Compiler($this->app['twig']);
});
$this->app->bindIf('twig.engine', function () {
return new Engine\Twig(
$this->app['twig.compiler'],
$this->app['twig.loader.viewfinder'],
$this->app['config']->get('twigbridge.twig.globals', [])
);
});
} | php | protected function registerEngine()
{
$this->app->bindIf(
'twig',
function () {
$extensions = $this->app['twig.extensions'];
$lexer = $this->app['twig.lexer'];
$twig = new Bridge(
$this->app['twig.loader'],
$this->app['twig.options'],
$this->app
);
// Instantiate and add extensions
foreach ($extensions as $extension) {
// Get an instance of the extension
// Support for string, closure and an object
if (is_string($extension)) {
try {
$extension = $this->app->make($extension);
} catch (\Exception $e) {
throw new InvalidArgumentException(
"Cannot instantiate Twig extension '$extension': " . $e->getMessage()
);
}
} elseif (is_callable($extension)) {
$extension = $extension($this->app, $twig);
} elseif (!is_a($extension, ExtensionInterface::class)) {
throw new InvalidArgumentException('Incorrect extension type');
}
$twig->addExtension($extension);
}
// Set lexer
if (is_a($lexer, Lexer::class)) {
$twig->setLexer($lexer);
}
return $twig;
},
true
);
$this->app->alias('twig', Twig_Environment::class);
$this->app->alias('twig', Bridge::class);
$this->app->bindIf('twig.compiler', function () {
return new Engine\Compiler($this->app['twig']);
});
$this->app->bindIf('twig.engine', function () {
return new Engine\Twig(
$this->app['twig.compiler'],
$this->app['twig.loader.viewfinder'],
$this->app['config']->get('twigbridge.twig.globals', [])
);
});
} | [
"protected",
"function",
"registerEngine",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"bindIf",
"(",
"'twig'",
",",
"function",
"(",
")",
"{",
"$",
"extensions",
"=",
"$",
"this",
"->",
"app",
"[",
"'twig.extensions'",
"]",
";",
"$",
"lexer",
"=",
... | Register Twig engine bindings.
@return void | [
"Register",
"Twig",
"engine",
"bindings",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/ServiceProvider.php#L219-L277 |
rcrowe/TwigBridge | src/Twig/Loader.php | Loader.findTemplate | public function findTemplate($name)
{
if ($this->files->exists($name)) {
return $name;
}
$name = $this->normalizeName($name);
if (isset($this->cache[$name])) {
return $this->cache[$name];
}
try {
$this->cache[$name] = $this->finder->find($name);
} catch (InvalidArgumentException $ex) {
throw new LoaderError($ex->getMessage());
}
return $this->cache[$name];
} | php | public function findTemplate($name)
{
if ($this->files->exists($name)) {
return $name;
}
$name = $this->normalizeName($name);
if (isset($this->cache[$name])) {
return $this->cache[$name];
}
try {
$this->cache[$name] = $this->finder->find($name);
} catch (InvalidArgumentException $ex) {
throw new LoaderError($ex->getMessage());
}
return $this->cache[$name];
} | [
"public",
"function",
"findTemplate",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"files",
"->",
"exists",
"(",
"$",
"name",
")",
")",
"{",
"return",
"$",
"name",
";",
"}",
"$",
"name",
"=",
"$",
"this",
"->",
"normalizeName",
"(",
... | Return path to template without the need for the extension.
@param string $name Template file name or path.
@throws LoaderError
@return string Path to template | [
"Return",
"path",
"to",
"template",
"without",
"the",
"need",
"for",
"the",
"extension",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Twig/Loader.php#L66-L85 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.