_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q246100 | PaginationParams.getNeighbours | validation | public function getNeighbours($namespace, $callback, $id)
{
$list = $this->getList($namespace, $callback);
$list->setCurrent($id);
return [
$list->getPrevious(),
$list->getNext()
];
} | php | {
"resource": ""
} |
q246101 | MongoQueue.push | validation | public function push(JobInterface $job, array $options = [])
{
$envelope = $this->createEnvelope($job, $options);
$result = $this->mongoCollection->insertOne($envelope);
$job->setId((string) $result->getInsertedId());
} | php | {
"resource": ""
} |
q246102 | MongoQueue.pushLazy | validation | public function pushLazy($service, $payload = null, array $options = [])
{
$manager = $this->getJobPluginManager();
$serviceOptions = [];
if (is_array($service)) {
$serviceOptions = $service['options'] ?? $service[1] ?? [];
$service = $service['name'] ?? $service[0] ?? null;
}
if (!$manager->has($service) && !class_exists($service)) {
throw new \UnexpectedValueException(sprintf(
'Service name "%s" is not a known job service or existent class',
$service
));
}
$lazyOptions = [
'name' => $service,
'options' => $serviceOptions,
'content' => $payload,
];
$job = $this->getJobPluginManager()->build('lazy', $lazyOptions);
$this->push($job, $options);
} | php | {
"resource": ""
} |
q246103 | MongoQueue.createEnvelope | validation | private function createEnvelope(JobInterface $job, array $options = [])
{
$scheduled = $this->parseOptionsToDateTime($options);
$tried = isset($options['tried']) ? (int) $options['tried'] : null;
$message = isset($options['message']) ? $options['message'] : null;
$trace = isset($options['trace']) ? $options['trace'] : null;
$envelope = [
'queue' => $this->getName(),
'status' => self::STATUS_PENDING,
'tried' => $tried,
'message' => $message,
'trace' => $trace,
'created' => $this->dateTimeToUTCDateTime($this->now),
'data' => $this->serializeJob($job),
'scheduled' => $this->dateTimeToUTCDateTime($scheduled),
'priority' => isset($options['priority']) ? $options['priority'] : self::DEFAULT_PRIORITY,
];
return $envelope;
} | php | {
"resource": ""
} |
q246104 | MongoQueue.retry | validation | public function retry(JobInterface $job, array $options = [])
{
$tried = $job->getMetadata('mongoqueue.tries', 0) + 1;
$job->setMetaData('mongoqueue.tries', $tried);
$options['tried'] = $tried;
$envelope = $this->createEnvelope($job, $options);
unset($envelope['created']);
$this->mongoCollection->findOneAndUpdate(
[
'_id' => new \MongoDB\BSON\ObjectID($job->getId())
],
[
'$set' => $envelope
]
);
} | php | {
"resource": ""
} |
q246105 | MongoQueue.pop | validation | public function pop(array $options = [])
{
$time = microtime(true);
$micro = sprintf("%06d", ($time - floor($time)) * 1000000);
$this->now = new \DateTime(
date('Y-m-d H:i:s.' . $micro, $time),
new \DateTimeZone(date_default_timezone_get())
);
$now = $this->dateTimeToUTCDateTime($this->now);
$envelope = $this->mongoCollection->findOneAndUpdate(
[
'queue' => $this->getName(),
'status' => self::STATUS_PENDING,
'scheduled' => ['$lte' => $now],
],
[
'$set' => [
'status' => self::STATUS_RUNNING,
'executed' => $now,
],
],
[
'sort' => ['priority' => 1, 'scheduled' => 1],
'returnDocument' => \MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
]
);
if (!$envelope) {
return null;
}
return $this->unserializeJob($envelope['data'], ['__id__' => $envelope['_id']]);
} | php | {
"resource": ""
} |
q246106 | MongoQueue.listing | validation | public function listing(array $options = [])
{
$filter = [ 'queue' => $this->getName() ];
if (isset($options['status'])) {
$filter['status'] = $options['status'];
}
$opt = [ 'sort' => [ 'scheduled' => 1, 'priority' => 1] ];
if (isset($options['limit'])) {
$opt['limit'] = $options['limit'];
}
$cursor = $this->mongoCollection->find($filter, $opt);
$jobs = $cursor->toArray();
foreach ($jobs as &$envelope) {
$envelope['job'] = $this->unserializeJob($envelope['data'], ['__id__' => $envelope['_id']]);
}
return $jobs;
} | php | {
"resource": ""
} |
q246107 | MongoQueue.delete | validation | public function delete(JobInterface $job, array $options = [])
{
$result = $this->mongoCollection->deleteOne(['_id' => $job->getId()]);
return (bool) $result->getDeletedCount();
} | php | {
"resource": ""
} |
q246108 | MongoQueue.fail | validation | public function fail(JobInterface $job, array $options = [])
{
$envelope = $this->createEnvelope($job, $options);
unset($envelope['created']);
unset($envelope['scheduled']);
$envelope['status'] = self::STATUS_FAILED;
$this->mongoCollection->findOneAndUpdate(
[
'_id' => new \MongoDB\BSON\ObjectId($job->getId())
],
[
'$set' => $envelope
]
);
} | php | {
"resource": ""
} |
q246109 | MongoQueue.parseOptionsToDateTime | validation | protected function parseOptionsToDateTime($options)
{
$time = microtime(true);
$micro = sprintf("%06d", ($time - floor($time)) * 1000000);
$this->now = new \DateTime(date('Y-m-d H:i:s.' . $micro, $time), new \DateTimeZone(date_default_timezone_get()));
$scheduled = isset($options['scheduled']) ? Utils::createDateTime($options['scheduled']) : clone ($this->now);
if (isset($options['delay'])) {
$delay = Utils::createDateInterval($options['delay']);
$scheduled->add($delay);
}
return $scheduled;
} | php | {
"resource": ""
} |
q246110 | DateFormatHelperFactory.createService | validation | public function createService(ServiceLocatorInterface $serviceLocator)
{
$helper = new DateFormat();
$helper->setLocale(Locale::DEFAULT_LOCALE);
return $helper;
} | php | {
"resource": ""
} |
q246111 | PurgeController.entityToString | validation | private function entityToString(EntityInterface $entity)
{
if (method_exists($entity, '__toString')) {
return $entity->__toString();
}
$str = get_class($entity);
if ($entity instanceof \Core\Entity\IdentifiableEntityInterface) {
$str .= '( ' . $entity->getId() . ' )';
}
return $str;
} | php | {
"resource": ""
} |
q246112 | EntityEraserEvents.setEventPrototype | validation | public function setEventPrototype(EventInterface $prototype)
{
if (!$prototype instanceof DependencyResultEvent) {
throw new \InvalidArgumentException('This event manager only accepts events of the type ' . DependencyResultEvent::class);
}
parent::setEventPrototype($prototype);
} | php | {
"resource": ""
} |
q246113 | EntityEraserEvents.triggerListeners | validation | protected function triggerListeners(EventInterface $event, callable $callback = null)
{
if (!$event instanceof DependencyResultEvent) {
throw new \InvalidArgumentException('This event manager only accepts events of the type ' . DependencyResultEvent::class);
}
$results = parent::triggerListeners($event, $callback);
$dependencies = $event->getDependencyResultCollection();
foreach ($results as $result) {
if (null !== $result) {
try {
$dependencies->add($result);
}
/* silently ignore all invalid results */
catch (\UnexpectedValueException $e) {
} catch (\InvalidArgumentException $e) {
}
}
}
return $results;
} | php | {
"resource": ""
} |
q246114 | SummaryFormButtonsFieldset.init | validation | public function init()
{
$this->setName('buttons');
if (!isset($this->options['render_summary'])) {
$this->options['render_summary'] = false;
}
$this->setAttribute('class', 'text-right');
$this->add(
array(
//'type' => 'Button',
'type' => 'Core/Spinner-Submit',
'name' => 'submit',
'options' => array(
'label' => /*@translate*/ 'Save',
),
'attributes' => array(
'id' => 'submit',
'type' => 'submit',
'value' => 'Save',
'class' => 'sf-submit btn btn-primary btn-xs'
),
)
);
$this->add(
array(
'type' => 'Button',
'name' => 'cancel',
'options' => array(
'label' => /*@translate*/ 'Cancel',
),
'attributes' => array(
'id' => 'cancel',
'type' => 'reset',
'value' => 'Cancel',
'class' => 'sf-cancel btn btn-default btn-xs'
),
)
);
} | php | {
"resource": ""
} |
q246115 | SummaryFormButtonsFieldset.setFormId | validation | public function setFormId($formId)
{
$this->formId = $formId . '-';
foreach ($this as $button) {
$button->setAttribute('id', $this->formId . $button->getAttribute('id'));
}
return $this;
} | php | {
"resource": ""
} |
q246116 | MetaDataProviderTrait.getMetaData | validation | public function getMetaData($key = null, $default = null)
{
if (null === $key) {
return $this->metaData;
}
return $this->hasMetaData($key) ? $this->metaData[$key] : $default;
} | php | {
"resource": ""
} |
q246117 | AbstractAdminAwareVoter.vote | validation | public function vote(TokenInterface $token, $object, array $attributes)
{
// ignore checks for switch user
if (in_array('ROLE_PREVIOUS_ADMIN', $attributes)) {
return VoterInterface::ACCESS_ABSTAIN;
}
/**
* Admin users should see content no matter the scheduled dates
* Since you can set the decision strategy to unanimous, you want to grant this explicitly
*/
if (!is_null($object) && $this->supportsClass(get_class($object)) && sizeof($token->getRoles())) {
/** @var \Symfony\Component\Security\Core\Role\Role $role */
foreach ($token->getRoles() as $role) {
if (in_array($role->getRole(), array('ROLE_ADMIN', 'ROLE_SUPER_ADMIN'))) {
return VoterInterface::ACCESS_GRANTED;
}
}
}
return VoterInterface::ACCESS_ABSTAIN;
} | php | {
"resource": ""
} |
q246118 | ClearCacheService.factory | validation | public static function factory(ContainerInterface $container)
{
/* @var \Zend\ModuleManager\ModuleManager $manager */
$config = $container->get('ApplicationConfig');
$options = new ListenerOptions($config['module_listener_options']);
return new static($options);
} | php | {
"resource": ""
} |
q246119 | FileEntity.setUser | validation | public function setUser(UserInterface $user)
{
if ($this->user) {
$this->getPermissions()->revoke($this->user, Permissions::PERMISSION_ALL, false);
}
$this->user = $user;
$this->getPermissions()->grant($user, Permissions::PERMISSION_ALL);
return $this;
} | php | {
"resource": ""
} |
q246120 | FileEntity.getPrettySize | validation | public function getPrettySize()
{
$size = $this->getLength();
if ($size >= 1073741824) {
return round($size / 1073741824, 2) . ' GB';
}
if ($size >= 1048576) {
return round($size / 1048576, 2) . ' MB';
}
if ($size >= 1024) {
return round($size / 1024, 2) . ' kB';
}
return (string)$size;
} | php | {
"resource": ""
} |
q246121 | FileEntity.getResource | validation | public function getResource()
{
if ($this->file instanceof \Doctrine\MongoDB\GridFSFile) {
return $this->file->getMongoGridFSFile()->getResource();
}
return null;
} | php | {
"resource": ""
} |
q246122 | FileEntity.getContent | validation | public function getContent()
{
if ($this->file instanceof \Doctrine\MongoDB\GridFSFile) {
return $this->file->getMongoGridFSFile()->getBytes();
}
return null;
} | php | {
"resource": ""
} |
q246123 | FileEntity.getPermissions | validation | public function getPermissions()
{
if (!$this->permissions) {
$perms = new Permissions();
if ($this->user instanceof UserInterface) {
$perms->grant($this->user, PermissionsInterface::PERMISSION_ALL);
}
$this->setPermissions($perms);
}
return $this->permissions;
} | php | {
"resource": ""
} |
q246124 | LanguageAwareAliasingStrategy.generatePublicAlias | validation | public function generatePublicAlias($subject, $currentAlias = '')
{
$alias = $this->strategyWrapper->generatePublicAlias($subject, $currentAlias);
if ($alias !== null && method_exists($subject, 'getLanguage')) {
if (in_array($subject->getLanguage(), $this->localesToPrefix)) {
$alias = sprintf('%s%s%s', $this->basePath, $subject->getLanguage(), $alias);
}
}
return $alias;
} | php | {
"resource": ""
} |
q246125 | DependencyResultEvent.addDependencies | validation | public function addDependencies($name, $entities = null, array $options = null)
{
return $this->dependencyResultCollection->add($name, $entities, $options);
} | php | {
"resource": ""
} |
q246126 | EntityHydrator.setExcludeMethods | validation | public function setExcludeMethods($methods)
{
if (is_string($methods)) {
$methods = array($methods);
}
foreach ($methods as $method) {
$this->addFilter($method, new MethodMatchFilter($method), FilterComposite::CONDITION_AND);
}
} | php | {
"resource": ""
} |
q246127 | Proxy.plugin | validation | public function plugin($plugin, $options = null)
{
$renderer = $this->getView();
if (!method_exists($renderer, 'getHelperPluginManager')) {
return true === $options ? false : new HelperProxy(false);
}
/* @var \Zend\View\HelperPluginManager $manager */
$manager = $renderer->getHelperPluginManager();
$hasPlugin = $manager->has($plugin);
if (true === $options) {
return $hasPlugin;
}
if ($hasPlugin) {
$pluginInstance = $manager->get($plugin, $options);
} else {
$pluginInstance = false;
}
return new HelperProxy($pluginInstance);
} | php | {
"resource": ""
} |
q246128 | AttachableEntityManager.createAttachedEntity | validation | public function createAttachedEntity($entityClass, $values = [], $key = null)
{
if (is_string($values)) {
$key = $values;
$values = [];
}
$entity = $this->repositories->getRepository($entityClass)->create($values);
$this->addAttachedEntity($entity, $key);
return $entity;
} | php | {
"resource": ""
} |
q246129 | PageController.gotoAction | validation | public function gotoAction(Request $r)
{
return $this->redirect(
$this->get('zicht_url.provider')->url($this->getPageManager()->findForView($r->get('id')))
);
} | php | {
"resource": ""
} |
q246130 | PageController.viewAction | validation | public function viewAction(Request $request, $id)
{
/** @var $pageManager \Zicht\Bundle\PageBundle\Manager\PageManager */
$pageManager = $this->getPageManager();
$page = $pageManager->findForView($id);
if (null !== ($validator = $this->getViewActionValidator())) {
$validator->validate($page);
}
if ($page instanceof ControllerPageInterface) {
return $this->forward(
$page->getController(),
(array)$page->getControllerParameters()
+ array(
'parameters' => $request->query->all(),
'_locale' => $request->attributes->get('_locale'),
'_internal_url' => $request->attributes->get('_internal_url'),
),
$request->query->all()
);
}
return $this->renderPage($page);
} | php | {
"resource": ""
} |
q246131 | PageController.renderPage | validation | public function renderPage(PageInterface $page, $vars = array())
{
return $this->render(
$this->getPageManager()->getTemplate($page),
$vars + array(
'page' => $page,
'id' => $page->getId(),
)
);
} | php | {
"resource": ""
} |
q246132 | EntitySnapshot.getTarget | validation | protected function getTarget($generateInstance = true)
{
$serviceLocator = $this->getServicelocator();
// set the actual options
$this->getGenerator();
$target = null;
if (array_key_exists('target', $this->options)) {
$target = $this->options['target'];
if (is_string($target)) {
if ($serviceLocator->has($target)) {
$target = $serviceLocator->get($target);
if ($generateInstance) {
$target = get_class($target);
}
} else {
if ($generateInstance) {
$target = new $target;
}
}
}
}
return $target;
} | php | {
"resource": ""
} |
q246133 | EntitySnapshot.getGenerator | validation | protected function getGenerator()
{
if (isset($this->generator)) {
return $this->generator;
}
if ($this->entity instanceof SnapshotGeneratorProviderInterface) {
$serviceLocator = $this->getServicelocator();
// the snapshotgenerator is a service defined by the name of the entity
// this is the highest means, all subsequent means just add what is not set
$className = get_class($this->entity);
if ($serviceLocator->has('snapshotgenerator' . $className)) {
$generator = $this->serviceLocator->get('snapshotgenerator' . $className);
if (is_array($generator)) {
$this->options = ArrayUtils::merge($generator, $this->options);
$generator = null;
}
}
// the snapshotgenerator is provided by the entity
// this can either be a generator-entity of a array with options
if (!isset($generator)) {
$generator = $this->entity->getSnapshotGenerator();
if (is_array($generator)) {
$this->options = ArrayUtils::merge($generator, $this->options);
if (array_key_exists('generator', $generator)) {
$generator = $this->options['generator'];
unset($this->options['generator']);
} else {
$generator = null;
}
}
if (is_string($generator)) {
$generator = $serviceLocator->get($generator);
}
}
// the last possibility to get a generator
if (!isset($generator)) {
// defaultGenerator
$generator = new SnapshotGenerator();
}
// *** filling the options
// hydrator
// can be a class, but if it's a string, consider it to be an hydrator in the hydratormanager
if (array_key_exists('hydrator', $this->options)) {
$hydrator = $this->options['hydrator'];
if (is_string($hydrator) && !empty($hydrator)) {
$hydrator = $serviceLocator->get('HydratorManager')->get($hydrator);
}
$generator->setHydrator($hydrator);
}
// exclude
// add the elements, that should not be transferred
if (array_key_exists('exclude', $this->options)) {
// it is very likely that the hydrator is set by the snapshot-class,
// so we have to asume, that may know the hydrator
$hydrator = $generator->getHydrator();
$exclude = $this->options['exclude'];
if (is_array($exclude)) {
$hydrator->setExcludeMethods($exclude);
}
}
$generator->setSource($this->entity);
$this->generator = $generator;
}
return $this->generator;
} | php | {
"resource": ""
} |
q246134 | EntitySnapshot.array_compare | validation | protected function array_compare($array1, $array2, $maxDepth = 2)
{
$result = array();
$arraykeys = array_unique(array_merge(array_keys($array1), array_keys($array2)));
foreach ($arraykeys as $key) {
if (!empty($key) && is_string($key) && $key[0] != "\0" && substr($key, 0, 8) != 'Doctrine') {
if (array_key_exists($key, $array1) && !array_key_exists($key, $array2)) {
$result[$key] = array($array1[$key], '');
}
if (!array_key_exists($key, $array1) && array_key_exists($key, $array2)) {
$result[$key] = array('', $array2[$key]);
}
if (array_key_exists($key, $array1) && array_key_exists($key, $array2)) {
$subResult = null;
if (is_array($array1[$key]) && is_array($array2[$key])) {
if (0 < $maxDepth) {
$subResult = $this->array_compare($array1[$key], $array2[$key], $maxDepth - 1);
}
} elseif (is_object($array1[$key]) && is_object($array2[$key])) {
if (0 < $maxDepth) {
$hydrator = new EntityHydrator();
$a1 = $hydrator->extract($array1[$key]);
$a2 = $hydrator->extract($array2[$key]);
$subResult = $this->array_compare($a1, $a2, $maxDepth - 1);
}
} else {
if ($array1[$key] != $array2[$key]) {
$result[$key] = array( $array1[$key], $array2[$key]);
}
}
if (!empty($subResult)) {
foreach ($subResult as $subKey => $subValue) {
if (!empty($subKey) && is_string($subKey)) {
$result[$key . '.' . $subKey] = $subValue;
}
}
}
}
}
}
return $result;
} | php | {
"resource": ""
} |
q246135 | Alert.end | validation | public function end()
{
if (!$this->captureLock) {
throw new \RuntimeException('Cannot end capture, there is no capture running.');
}
$type = $this->captureType;
$content = ob_get_clean();
$options = $this->captureOptions;
$this->captureLock = false;
$this->captureType = null;
$this->captureOptions = null;
return $this->render($type, $content, $options);
} | php | {
"resource": ""
} |
q246136 | Alert.render | validation | public function render($type = null, $content = true, array $options = array())
{
if (is_array($type)) {
$options = $type;
$type = self::TYPE_INFO;
$content = true;
} elseif (is_array($content)) {
$options = $content;
$content = true;
}
if (true === $content) {
return $this->start($type, $options);
}
$id = isset($options['id']) ? ' id="' . $options['id'] . '"' : '';
$class = isset($options['class']) ? ' ' . $options['class'] : '';
if ((isset($options['dismissable']) && $options['dismissable'])
|| !isset($options['dismissable'])
) {
$class .= ' alert-dismissable';
$content = '<button type="button" class="close" data-dismiss="alert">×</button>'
. '<span class="notification-content">' . $content . '</span>';
}
$target = array_key_exists('target', $options)?' target="' . $options['target'] . '"':'';
$markup = '<div ' . $id . ' class="alert alert-' . $type . $class . '" ' . $target . '>' . $content . '</div>' . PHP_EOL;
return $markup;
} | php | {
"resource": ""
} |
q246137 | Alert.start | validation | public function start($type = self::TYPE_INFO, array $options = array())
{
if ($this->captureLock) {
throw new \RuntimeException('Cannot start capture, there is already a capture running.');
}
$this->captureLock = true;
$this->captureType = $type;
$this->captureOptions = $options;
ob_start();
return $this;
} | php | {
"resource": ""
} |
q246138 | Application.getConfigDir | validation | public static function getConfigDir()
{
if (is_null(static::$configDir)) {
$configDir = '';
$dirs = [
// path/to/module/test/sandbox/config directories
__DIR__.'/../../../../*/sandbox/config',
// path/to/yawik-standard/config
__DIR__.'/../../../config',
];
foreach ($dirs as $dir) {
foreach (glob($dir) as $testDir) {
$configDir = realpath($testDir);
break;
}
if (is_dir($configDir)) {
break;
}
}
if (!is_dir($configDir)) {
throw new InvalidArgumentException('Can not determine which config directory to be used.');
}
static::$configDir = $configDir;
}
return static::$configDir;
} | php | {
"resource": ""
} |
q246139 | Application.checkCache | validation | private static function checkCache(array $configuration)
{
$config = $configuration['module_listener_options'];
$options = new ListenerOptions($config);
$cache = new ClearCacheService($options);
$cache->checkCache();
} | php | {
"resource": ""
} |
q246140 | Application.setupCliServerEnv | validation | public static function setupCliServerEnv()
{
$parseUrl = parse_url(substr($_SERVER["REQUEST_URI"], 1));
$route = isset($parseUrl['path']) ? $parseUrl['path']:null;
if (is_file(__DIR__ . '/' . $route)) {
if (substr($route, -4) == ".php") {
require __DIR__ . '/' . $route; // Include requested script files
exit;
}
return false; // Serve file as is
} else { // Fallback to index.php
$_GET["q"] = $route; // Try to emulate the behaviour of a .htaccess here.
}
return true;
} | php | {
"resource": ""
} |
q246141 | Application.loadDotEnv | validation | public static function loadDotEnv()
{
$dotenv = new Dotenv();
if (is_file(getcwd().'/.env.dist')) {
$dotenv->load(getcwd().'/.env.dist');
}
if (is_file($file = getcwd().'/.env')) {
$dotenv->load($file);
}
if (false === getenv('TIMEZONE')) {
putenv('TIMEZONE=Europe/Berlin');
}
date_default_timezone_set(getenv('TIMEZONE'));
} | php | {
"resource": ""
} |
q246142 | Application.loadConfig | validation | public static function loadConfig($configuration = [])
{
$configDir = static::getConfigDir();
if (empty($configuration)) {
$configFile = $configDir.'/config.php';
// @codeCoverageIgnoreStart
if (!is_file($configFile)) {
throw new InvalidArgumentException(sprintf(
'Can not load config file "%s". Please be sure that this file exists and readable',
$configFile
));
}
// @codeCoverageIgnoreEnd
$configuration = include $configFile;
}
$isCli = php_sapi_name() === 'cli';
// load modules
$modules = $configuration['modules'];
$modules = static::generateModuleConfiguration($modules);
$yawikConfig = $configDir.'/autoload/yawik.config.global.php';
$installMode = false;
if (!$isCli && !file_exists($yawikConfig)) {
$modules = static::generateModuleConfiguration(['Install']);
$installMode = true;
} elseif (in_array('Install', $modules)) {
$modules = array_diff($modules, ['Install']);
}
static::$env = $env = getenv('APPLICATION_ENV') ?: 'production';
$defaults = [
'module_listener_options' => [
'module_paths' => [
'./module',
'./vendor',
'./modules'
],
// What configuration files should be autoloaded
'config_glob_paths' => [
sprintf($configDir.'/autoload/{,*.}{global,%s,local}.php', $env)
],
// Use the $env value to determine the state of the flag
// caching disabled during install mode
'config_cache_enabled' => ($env == 'production'),
// Use the $env value to determine the state of the flag
'module_map_cache_enabled' => ($env == 'production'),
'module_map_cache_key' => 'module_map',
// Use the $env value to determine the state of the flag
'check_dependencies' => ($env != 'production'),
'cache_dir' => getcwd()."/var/cache",
],
];
$envConfig = [];
$envConfigFile = $configDir.'/config.'.$env.'.php';
if (file_exists($envConfigFile)) {
if (is_readable($envConfigFile)) {
$envConfig = include $envConfigFile;
} else {
\trigger_error(
sprintf('Environment config file "%s" is not readable.', $envConfigFile),
E_USER_NOTICE
);
}
}
// configuration file always win
$configuration = ArrayUtils::merge($defaults, $configuration);
// environment config always win
$configuration = ArrayUtils::merge($configuration, $envConfig);
$configuration['modules'] = $modules;
// force disabled cache when in install mode
if ($installMode) {
$configuration['module_listener_options']['config_cache_enabled'] = false;
$configuration['module_listener_options']['module_map_cache_enabled'] = false;
}
// setup docker environment
if (getenv('DOCKER_ENV')=='yes') {
$configuration = ArrayUtils::merge($configuration, static::getDockerEnv($configuration));
}
return $configuration;
} | php | {
"resource": ""
} |
q246143 | Application.getDockerEnv | validation | private static function getDockerEnv($configuration)
{
// add doctrine hydrator
$cacheDir = $configuration['module_listener_options']['cache_dir'].'/docker';
$configDir = static::getConfigDir();
$hydratorDir = $cacheDir.'/Doctrine/Hydrator';
$proxyDir = $cacheDir.'/Doctrine/Proxy';
if (!is_dir($hydratorDir)) {
mkdir($hydratorDir, 0777, true);
}
if (!is_dir($proxyDir)) {
mkdir($proxyDir, 0777, true);
}
return [
'module_listener_options' => [
'cache_dir' => $cacheDir,
'config_glob_paths' => [
$configDir.'/autoload/*.docker.php',
]
],
'doctrine' => [
'configuration' => [
'odm_default' => [
'hydrator_dir' => $hydratorDir,
'proxy_dir' => $proxyDir,
]
]
]
];
} | php | {
"resource": ""
} |
q246144 | SelectFactory.createService | validation | public function createService(ServiceLocatorInterface $serviceLocator)
{
/* @var \Zend\ServiceManager\AbstractPluginManager $serviceLocator */
$select = $this($serviceLocator, self::class, $this->options);
$this->options = [];
return $select;
} | php | {
"resource": ""
} |
q246145 | SelectFactory.createValueOptions | validation | protected function createValueOptions(NodeInterface $node, $allowSelectNodes = false, $isRoot=true)
{
$key = $isRoot ? $node->getValue() : $node->getValueWithParents();
$name = $node->getName();
if ($node->hasChildren()) {
$leafOptions = [];
if ($allowSelectNodes && !$isRoot) {
$leafOptions[$key] = $name;
$key = "$key-group";
}
foreach ($node->getChildren() as $child) {
$leafOptions += $this->createValueOptions($child, $allowSelectNodes, false);
}
$value = [
'label' => $name,
'options' => $leafOptions
];
} else {
$value = $name;
}
return [$key => $value];
} | php | {
"resource": ""
} |
q246146 | Config.getByKey | validation | public function getByKey($key = null)
{
if (!array_key_exists($key, $this->applicationMap)) {
$this->applicationMap[$key] = array();
$config = $this->serviceManager->get('Config');
$appConfig = $this->serviceManager->get('ApplicationConfig');
foreach ($appConfig['modules'] as $module) {
if (array_key_exists($module, $config)) {
if (array_key_exists($key, $config[$module])) {
// The strtolower is essential for later retrieving
// namespaces in the repositories
// anyway, it's easier to agree everything should be lowercase
$this->applicationMap[$key][strtolower($module)] = $config[$module][$key];
}
}
}
}
return $this->applicationMap[$key];
} | php | {
"resource": ""
} |
q246147 | ContentController.indexAction | validation | public function indexAction()
{
$view = $this->params('view');
$view = 'content/' . $view;
$viewModel = new ViewModel();
$viewModel->setTemplate($view);
/* @var $request Request */
$request = $this->getRequest();
if ($request->isXmlHttpRequest()) {
$viewModel->setTerminal(true);
}
return $viewModel;
} | php | {
"resource": ""
} |
q246148 | AjaxRouteListener.onRoute | validation | public function onRoute(MvcEvent $event)
{
/* @var \Zend\Http\PhpEnvironment\Request $request */
$request = $event->getRequest();
$ajax = $request->getQuery()->get('ajax');
if (!$request->isXmlHttpRequest() || !$ajax) {
/* no ajax request or required parameter not present */
return;
}
/* @var \Zend\Http\PhpEnvironment\Response $response */
/* @var AjaxEvent $ajaxEvent */
$response = $event->getResponse();
$ajaxEvent = $this->ajaxEventManager->getEvent($ajax, $this);
$ajaxEvent->setRequest($request);
$ajaxEvent->setResponse($response);
$results = $this->ajaxEventManager->triggerEventUntil(function ($r) {
return null !== $r;
}, $ajaxEvent);
$result = $results->last() ?: $ajaxEvent->getResult();
if (!$result) {
throw new \UnexpectedValueException('No listener returned anything. Do not know what to do...');
}
/* Convert arrays or traversable objects to JSON string. */
if (is_array($result) || $result instanceof \Traversable) {
$result = Json::encode($result, true, ['enableJsonExprFinder' => true]);
}
$contentType = $ajaxEvent->getContentType();
$response->getHeaders()->addHeaderLine('Content-Type', $contentType);
$response->setContent($result);
return $response;
} | php | {
"resource": ""
} |
q246149 | SummaryForm.render | validation | public function render(SummaryFormInterface $form, $layout = Form::LAYOUT_HORIZONTAL, $parameter = array())
{
$renderer = $this->getView();
$renderer->headscript()->appendFile($renderer->basepath('modules/Core/js/jquery.summary-form.js'));
$label = $form->getLabel();
$labelContent = $label ? '<div class="sf-headline"><h3>' . $this->getView()->translate($label) . '</h3></div>' : '';
$formContent = $this->renderForm($form, $layout, $parameter);
$summaryContent = $this->renderSummary($form);
$formContent = sprintf(
'<div class="sf-form"><div class="panel panel-info"><div class="panel-body">%s</div></div></div>
<div class="sf-summary">%s</div>
',
$formContent,
$summaryContent
);
if ($form instanceof DescriptionAwareFormInterface && $form->isDescriptionsEnabled()) {
$this->getView()->headscript()->appendFile(
$this->getView()->basepath('modules/Core/js/forms.descriptions.js')
);
if ($desc = $form->getOption('description', '')) {
$translator = $this->getTranslator();
$textDomain = $this->getTranslatorTextDomain();
$desc = $translator->translate($desc, $textDomain);
}
$formContent = sprintf(
'<div class="daf-form-container row">
<div class="daf-form col-md-8">%s</div>
<div class="daf-desc col-md-4">
<div class="daf-desc-content alert alert-info">%s</div>
</div>
</div>',
$formContent,
$desc
);
}
$markup = '<div id="sf-%s" class="sf-container" data-display-mode="%s">'
. '%s'
. '%s'
. '</div>';
$id = str_replace('.', '-', $form->getAttribute('name'));
$content = sprintf(
$markup,
$id,
$form->getDisplayMode(),
$labelContent,
$formContent
);
return $content;
} | php | {
"resource": ""
} |
q246150 | SummaryForm.renderForm | validation | public function renderForm(SummaryFormInterface $form, $layout = Form::LAYOUT_HORIZONTAL, $parameter = array())
{
/* @var $form SummaryFormInterface|\Core\Form\SummaryForm */
$renderer = $this->getView(); /* @var $renderer \Zend\View\Renderer\PhpRenderer */
$formHelper = $renderer->plugin('form'); /* @var $formHelper \Core\Form\View\Helper\Form */
$fieldset = $form->getBaseFieldset();
$resetPartial = false;
if ($fieldset instanceof ViewPartialProviderInterface) {
$origPartial = $fieldset->getViewPartial();
$partial = "$origPartial.form";
if ($renderer->resolver($partial)) {
$fieldset->setViewPartial($partial);
$resetPartial = true;
}
}
$markup = $formHelper->renderBare($form, $layout, $parameter);
if ($resetPartial) {
/** @noinspection PhpUndefinedVariableInspection */
$fieldset->setViewPartial($origPartial);
}
return $markup;
} | php | {
"resource": ""
} |
q246151 | SummaryForm.renderSummary | validation | public function renderSummary(SummaryFormInterface $form)
{
$form->prepare();
$baseFieldset = $form->getBaseFieldset();
if (!isset($baseFieldset)) {
throw new \InvalidArgumentException('For the Form ' . get_class($form) . ' there is no Basefieldset');
}
$dataAttributesMarkup = '';
foreach ($form->getAttributes() as $dataKey => $dataValue) {
if (preg_match('/^data-/', $dataKey)) {
$dataAttributesMarkup .= sprintf(' %s="%s"', $dataKey, $dataValue);
}
}
$markup = '<div class="panel panel-default" style="min-height: 100px;"' . $dataAttributesMarkup . '>
<div class="panel-body"><div class="sf-controls">%s</div>%s</div></div>';
$view = $this->getView();
$buttonMarkup = false === $form->getOption('editable')
? ''
: '<button type="button" class="btn btn-default btn-xs sf-edit">'
. '<span class="yk-icon yk-icon-edit"></span> '
. $view->translate('Edit')
. '</button>';
if (($controlButtons = $form->getOption('control_buttons')) !== null) {
$buttonMarkup .= PHP_EOL . implode(PHP_EOL, array_map(function (array $buttonSpec) use ($view) {
return '<button type="button" class="btn btn-default btn-xs' . (isset($buttonSpec['class']) ? ' ' . $buttonSpec['class'] : '') . '">'
. (isset($buttonSpec['icon']) ? '<span class="yk-icon yk-icon-' . $buttonSpec['icon'] . '"></span> ' : '')
. $view->translate($buttonSpec['label'])
. '</button>';
}, $controlButtons));
}
$elementMarkup = $this->renderSummaryElement($baseFieldset);
return sprintf($markup, $buttonMarkup, $elementMarkup);
} | php | {
"resource": ""
} |
q246152 | DefaultNavigationFactory.injectComponents | validation | protected function injectComponents(
array $pages,
$routeMatch = null,
$router = null,
$request = null
) {
if ($routeMatch) {
/* @var RouteMatch|MvcRouter\RouteMatch $routeMatch */
$routeName = $routeMatch->getMatchedRouteName();
foreach ($pages as &$page) {
if (isset($page['active_on']) && in_array($routeName, (array) $page['active_on'])) {
$page['active'] = true;
}
}
}
return parent::injectComponents($pages, $routeMatch, $router, $request);
} | php | {
"resource": ""
} |
q246153 | HTMLTemplateMessage.setVariables | validation | public function setVariables($variables, $overwrite = false)
{
if (!is_array($variables) && !$variables instanceof \Traversable) {
throw new \InvalidArgumentException(
sprintf(
'%s: expects an array, or Traversable argument; received "%s"',
__METHOD__,
(is_object($variables) ? get_class($variables) : gettype($variables))
)
);
}
if ($overwrite) {
if (is_object($variables) && !$variables instanceof \ArrayAccess) {
$variables = ArrayUtils::iteratorToArray($variables);
}
$this->variables = $variables;
return $this;
}
foreach ($variables as $key => $value) {
$this->setVariable($key, $value);
}
return $this;
} | php | {
"resource": ""
} |
q246154 | DependencyResultCollection.add | validation | public function add($name, $entities = null, array $options = null)
{
if ($name instanceof DependencyResult) {
return $this->addResult($name);
}
if ($name instanceof \Traversable) {
return $this->addTraversable($name);
}
if (is_array($name)) {
return $this->addArray($name);
}
if (null === $entities) {
throw new \UnexpectedValueException('$entities must not be null.');
}
return $this->addArray([
'name' => $name,
'entities' => $entities,
'options' => $options,
]);
} | php | {
"resource": ""
} |
q246155 | DependencyResultCollection.addTraversable | validation | private function addTraversable(\Traversable $result)
{
/*
* Since we only know, that $result is an instance of \Traversable
* (and thus, usable in a foreach), we cannot relay on methods like first()
* which are defined in the \Iterable interface.
* We must use a foreach to get the first item.
*
* Because PHP does not unset the loop variable, this works.
*/
foreach ($result as $item) {
break;
}
/* @var null|object|mixed $item */
if (!$item instanceof EntityInterface) {
throw new \InvalidArgumentException('Traversable objects must be a non-empty collection of Entity instances.');
}
$name = get_class($item);
return $this->addArray([
'name' => $name,
'entities' => $result,
]);
} | php | {
"resource": ""
} |
q246156 | DependencyResultCollection.addArray | validation | private function addArray(array $result)
{
if (1 < count($result) && !isset($result['name']) && !is_string($result[0])) {
foreach ($result as $r) {
if (is_array($r)) {
$this->add($r);
} else {
return $this->addTraversable(new \ArrayIterator($result));
}
}
return $this;
}
if (is_string($result[0])) {
$result = [
'name' => $result[0],
'entities' => isset($result[1]) ? $result[1] : null,
'options' => isset($result[2]) && is_array($result[2])
? $result[2]
: [
'description' => isset($result[2]) ? $result[2] : null,
'viewScript' => isset($result[3]) ? $result[3] : null,
],
];
}
if (!isset($result['name']) || !isset($result['entities'])) {
throw new \UnexpectedValueException('Array must have the keys "name" and "entities".');
}
if (!count($result['entities'])) {
throw new \UnexpectedValueException('Entities must be non-empty.');
}
$result = new DependencyResult($result['name'], $result['entities'], isset($result['options']) ? $result['options'] : null);
return $this->addResult($result);
} | php | {
"resource": ""
} |
q246157 | Node.setValue | validation | public function setValue($value)
{
if (!$value) {
if (!$this->getName()) {
throw new \InvalidArgumentException('Value must not be empty.');
}
$value = self::filterValue($this->getName());
}
$this->value = (string) $value;
return $this;
} | php | {
"resource": ""
} |
q246158 | Form.setParams | validation | public function setParams(array $params)
{
foreach ($params as $key => $value) {
$this->setParam($key, $value);
}
return $this;
} | php | {
"resource": ""
} |
q246159 | Form.setParam | validation | public function setParam($key, $value)
{
if ($this->has($key)) {
$this->get($key)->setValue($value);
} else {
$this->add(
[
'type' => 'hidden',
'name' => $key,
'attributes' => [
'value' => $value
]
]
);
}
return $this;
} | php | {
"resource": ""
} |
q246160 | Form.attachInputFilterDefaults | validation | public function attachInputFilterDefaults(InputFilterInterface $inputFilter, FieldsetInterface $fieldset)
{
parent::attachInputFilterDefaults($inputFilter, $fieldset);
/* @var $inputFilter \Zend\InputFilter\InputFilter */
foreach ($inputFilter->getInputs() as $name => $input) {
if (!$input instanceof InputFilterInterface) {
/* @var $input \Zend\InputFilter\Input */
$required = $input->isRequired();
$inputExists = $fieldset->has($name);
if (!$inputExists && $required) {
$fieldsetName = '';
if ($fieldset->hasAttribute('name')) {
$fieldsetName = 'in Fieldset "' . $fieldset->getAttribute('name') . '" ';
}
throw new \RuntimeException('input for "' . $name . '" ' . $fieldsetName . 'is required but a input-field with this name is not defined');
}
}
}
} | php | {
"resource": ""
} |
q246161 | WizardContainer.setForm | validation | public function setForm($key, $spec, $enabled = true)
{
if (is_object($spec)) {
if (!$spec instanceof Container) {
throw new \InvalidArgumentException('Tab container must be of the type \Core\Form\Container');
}
if (!$spec->getLabel()) {
throw new \InvalidArgumentException('Container instances must have a label.');
}
}
if (is_array($spec)) {
if (!isset($spec['type'])) {
$spec['type'] = 'Core/Container';
}
/*
* For convenience, forms may be specified outside the options array.
* But in order to be passed through to the form element manager,
* we must move it to the options.
*/
if (!isset($spec['options']['forms']) && isset($spec['forms'])) {
$spec['options']['forms'] = $spec['forms'];
unset($spec['forms']);
}
}
return parent::setForm($key, $spec, $enabled);
} | php | {
"resource": ""
} |
q246162 | ContentItemMatrix.region | validation | public function region($region, $reset = false)
{
$this->currentRegion = $region;
if ($reset) {
$this->matrix[$this->currentRegion] = [];
}
return $this;
} | php | {
"resource": ""
} |
q246163 | ContentItemMatrix.removeRegion | validation | public function removeRegion($region)
{
if (array_key_exists($region, $this->matrix)) {
unset($this->matrix[$region]);
}
return $this;
} | php | {
"resource": ""
} |
q246164 | ContentItemMatrix.removeTypeFromRegion | validation | public function removeTypeFromRegion($type, $region)
{
if (array_key_exists($region, $this->matrix)) {
array_walk(
$this->matrix[ $region ],
function ($value, $idx, $matrix) use ($type, $region) {
$class = explode('\\', $value);
$className = array_pop($class);
if ($className === $type) {
unset($matrix[ $region ][ $idx ]);
}
},
$this->matrix
);
}
return $this;
} | php | {
"resource": ""
} |
q246165 | ContentItemMatrix.type | validation | public function type($className)
{
if (!class_exists($className)) {
throw new \InvalidArgumentException(
sprintf(
'Class %s is non-existent or could not be loaded',
$className
)
);
}
$this->matrix[$this->currentRegion][] = $className;
return $this;
} | php | {
"resource": ""
} |
q246166 | ContentItemMatrix.getTypes | validation | public function getTypes($region = null)
{
if (null === $region) {
$ret = [];
foreach ($this->matrix as $types) {
$ret = array_merge($ret, $types);
}
return array_values(array_unique($ret));
}
return $this->matrix[$region];
} | php | {
"resource": ""
} |
q246167 | ContentItemMatrix.getRegions | validation | public function getRegions($type = null)
{
if (null === $type) {
return array_keys($this->matrix);
}
$regions = [];
foreach ($this->matrix as $region => $types) {
if (in_array($type, $types)) {
$regions[] = $region;
}
}
return $regions;
} | php | {
"resource": ""
} |
q246168 | DeferredListenerAggregate.setListeners | validation | public function setListeners(array $specs)
{
foreach ($specs as $spec) {
if (!isset($spec['event']) || !isset($spec['service'])) {
throw new \DomainException('Listener specification must be an array with the keys "event" and "service".');
}
$method = isset($spec['method']) ? $spec['method'] : null;
$priority = isset($spec['priority']) ? $spec['priority'] : 0;
$this->setListener($spec['event'], $spec['service'], $method, $priority);
}
return $this;
} | php | {
"resource": ""
} |
q246169 | DeferredListenerAggregate.setListener | validation | public function setListener($event, $service, $method = null, $priority = 0)
{
if (is_int($method)) {
$priority = $method;
$method = null;
}
$name = uniqid();
$this->listenerSpecs[$name] = [
'event' => $event,
'service' => $service,
'method' => $method,
'priority' => $priority,
'instance' => null,
];
return $this;
} | php | {
"resource": ""
} |
q246170 | DeferredListenerAggregate.attach | validation | public function attach(EventManagerInterface $events, $priority = 1)
{
foreach ($this->listenerSpecs as $name => $spec) {
$this->listeners[] = $events->attach($spec['event'], array($this, "do$name"), $spec['priority']);
}
} | php | {
"resource": ""
} |
q246171 | DeferredListenerAggregate.detach | validation | public function detach(EventManagerInterface $events)
{
foreach ($this->listeners as $i => $listener) {
if ($events->detach($listener)) {
unset($this->listeners[$i]);
}
}
return empty($this->listeners);
} | php | {
"resource": ""
} |
q246172 | AbstractLeafs.updateValues | validation | public function updateValues()
{
$values = [];
/* @var NodeInterface $item */
foreach ($this->getItems() as $item) {
if (!is_null($item)) {
$values[] = $item->getValueWithParents();
}
}
$this->values = $values;
} | php | {
"resource": ""
} |
q246173 | NotificationListener.renderJSON | validation | public function renderJSON(MvcEvent $event)
{
if (!$this->hasRunned) {
$valueToPlainStati = array(1 => 'error', 2 => 'error', 3 => 'error', 4 => 'error', 5 => 'success', 6 => 'info', 7 => 'info');
$viewModel = $event->getViewModel();
if ($viewModel instanceof JsonModel) {
if (!empty($this->notifications)) {
$jsonNotifications = $viewModel->getVariable('notifications', array());
foreach ($this->notifications as $notification) {
$status = 'info';
if (array_key_exists($notification->getPriority(), $valueToPlainStati)) {
$status = $valueToPlainStati[$notification->getPriority()];
}
$jsonNotifications[] = array(
'text' => $notification->getNotification(),
'status' => $status
);
}
$viewModel->setVariable('notifications', $jsonNotifications);
}
$this->hasRunned = true;
}
}
return;
} | php | {
"resource": ""
} |
q246174 | EntityEraser.loadEntities | validation | public function loadEntities($entity, $id = null)
{
$params = $this->options;
$params['id'] = $id;
$params['repositories'] = $this->repositories;
$event = $this->loadEntitiesEvents->getEvent($entity, $this, $params);
$responses = $this->loadEntitiesEvents->triggerEventUntil(
function ($response) {
return (is_array($response) || $response instanceof \Traversable) && count($response);
},
$event
);
$entities = $responses->last();
return $entities;
} | php | {
"resource": ""
} |
q246175 | EntityEraser.erase | validation | public function erase(EntityInterface $entity)
{
$dependencies = $this->triggerEvent(DependencyResultEvent::DELETE, $entity);
foreach ($dependencies as $result) {
if ($result->isDelete()) {
foreach ($result->getEntities() as $dependendEntity) {
$this->repositories->remove($dependendEntity);
}
}
}
$this->repositories->remove($entity);
return $dependencies;
} | php | {
"resource": ""
} |
q246176 | EntityEraser.triggerEvent | validation | private function triggerEvent($name, EntityInterface $entity)
{
$params = $this->options;
$params['entity'] = $entity;
$params['repositories'] = $this->repositories;
/* @var DependencyResultEvent $event */
$event = $this->entityEraserEvents->getEvent($name, $this, $params);
$this->entityEraserEvents->triggerEvent($event);
$dependencies = $event->getDependencyResultCollection();
return $dependencies;
} | php | {
"resource": ""
} |
q246177 | AbstractUpdatePermissionsSubscriber.getEntities | validation | protected function getEntities($args)
{
$dm = $args->getDocumentManager();
$resource = $args->getDocument();
$repositoryName = $this->getRepositoryName();
$resourceId = $resource->getPermissionsResourceId();
$repository = $dm->getRepository($repositoryName);
$criteria = array(
'permissions.assigned.' . $resourceId => array(
'$exists' => true
)
);
$entities = $repository->findBy($criteria);
return $entities;
} | php | {
"resource": ""
} |
q246178 | OptionsAbstractFactory.createNestedOptions | validation | protected function createNestedOptions($className, $options)
{
$class = new $className();
foreach ($options as $key => $spec) {
if (is_array($spec) && array_key_exists('__class__', $spec)) {
$nestedClassName = $spec['__class__'];
unset($spec['__class__']);
$spec = $this->createNestedOptions($nestedClassName, $spec);
}
$class->{$key} = $spec;
}
return $class;
} | php | {
"resource": ""
} |
q246179 | OptionsAbstractFactory.getOptionsConfig | validation | protected function getOptionsConfig($fullName)
{
if (array_key_exists($fullName, $this->optionsConfig)) {
return $this->optionsConfig[$fullName];
}
return false;
} | php | {
"resource": ""
} |
q246180 | FileUpload.setAllowedTypes | validation | public function setAllowedTypes($types)
{
if (is_array($types)) {
$types = implode(',', $types);
}
return $this->setAttribute('data-allowedtypes', $types);
} | php | {
"resource": ""
} |
q246181 | FileUpload.setIsMultiple | validation | public function setIsMultiple($flag)
{
$this->isMultiple = (bool) $flag;
if ($flag) {
$this->setAttribute('multiple', true);
} else {
$this->removeAttribute('multiple');
}
return $this;
} | php | {
"resource": ""
} |
q246182 | FileUpload.getAllowedTypes | validation | public function getAllowedTypes($asArray = false)
{
$types = $this->getAttribute('data-allowedtypes');
if ($asArray) {
return explode(',', $types);
}
return $types;
} | php | {
"resource": ""
} |
q246183 | FileUpload.fileCountValidationCallback | validation | public function fileCountValidationCallback()
{
if ($this->form && ($object = $this->form->getObject())) {
if ($this->getMaxFileCount() - 1 < count($object)) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q246184 | BaseForm.addBaseFieldset | validation | protected function addBaseFieldset()
{
if (null === $this->baseFieldset) {
return;
}
$fs = $this->baseFieldset;
if (!is_array($fs)) {
$fs = array(
'type' => $fs,
);
}
if (!isset($fs['options']['use_as_base_fieldset'])) {
$fs['options']['use_as_base_fieldset'] = true;
}
$this->add($fs);
} | php | {
"resource": ""
} |
q246185 | Permissions.grant | validation | public function grant($resource, $permission = null, $build = true)
{
if (is_array($resource)) {
foreach ($resource as $r) {
$this->grant($r, $permission, false);
}
if ($build) {
$this->build();
}
return $this;
}
//new \Doctrine\ODM\MongoDB\
true === $permission
|| (null === $permission && $resource instanceof PermissionsResourceInterface)
|| $this->checkPermission($permission);
$resourceId = $this->getResourceId($resource);
if (true === $permission) {
$permission = $this->getFrom($resource);
}
if (self::PERMISSION_NONE == $permission) {
if ($resource instanceof PermissionsResourceInterface) {
$refs = $this->getResources();
if ($refs->contains($resource)) {
$refs->removeElement($resource);
}
}
unset($this->assigned[$resourceId]);
} else {
if ($resource instanceof PermissionsResourceInterface) {
$spec = $resource->getPermissionsUserIds($this->type);
if (!is_array($spec) || !count($spec)) {
$spec = array();
} elseif (is_numeric(key($spec))) {
$spec = array($permission => $spec);
}
} else {
$spec = array($permission => $resource instanceof UserInterface ? array($resource->getId()) : array($resource));
}
$this->assigned[$resourceId] = $spec;
if ($resource instanceof PermissionsResourceInterface) {
try {
$refs = $this->getResources();
if (!$refs->contains($resource)) {
$refs->add($resource);
}
} catch (\Exception $e) {
};
}
}
if ($build) {
$this->build();
}
$this->hasChanged = true;
return $this;
} | php | {
"resource": ""
} |
q246186 | Permissions.revoke | validation | public function revoke($resource, $permission = null, $build = true)
{
if (self::PERMISSION_NONE == $permission || !$this->isAssigned($resource)) {
return $this;
}
if (self::PERMISSION_CHANGE == $permission) {
return $this->grant($resource, self::PERMISSION_VIEW, $build);
}
return $this->grant($resource, self::PERMISSION_NONE, $build);
} | php | {
"resource": ""
} |
q246187 | Permissions.build | validation | public function build()
{
$view = $change = array();
foreach ($this->assigned as $resourceId => $spec) {
/* This is needed to convert old permissions to the new spec format
* introduced in 0.18
* TODO: Remove this line some versions later.
*/
// @codeCoverageIgnoreStart
if (isset($spec['permission'])) {
$spec = array($spec['permission'] => $spec['users']);
$this->assigned[$resourceId] = $spec;
}
// @codeCoverageIgnoreEnd
foreach ($spec as $perm => $userIds) {
if (self::PERMISSION_ALL == $perm || self::PERMISSION_CHANGE == $perm) {
$change = array_merge($change, $userIds);
}
$view = array_merge($view, $userIds);
}
}
$this->change = array_unique($change);
$this->view = array_unique($view);
return $this;
} | php | {
"resource": ""
} |
q246188 | Permissions.checkPermission | validation | protected function checkPermission($permission)
{
$perms = array(
self::PERMISSION_ALL,
self::PERMISSION_CHANGE,
self::PERMISSION_NONE,
self::PERMISSION_VIEW,
);
if (!in_array($permission, $perms)) {
throw new \InvalidArgumentException(
'Invalid permission. Must be one of ' . implode(', ', $perms)
);
}
} | php | {
"resource": ""
} |
q246189 | DraftableEntityAwareTrait.findDraftsBy | validation | public function findDraftsBy(array $criteria, array $sort = null, $limit = null, $skip = null)
{
$criteria['isDraft'] = true;
/** @noinspection PhpUndefinedClassInspection */
/** @noinspection PhpUndefinedMethodInspection */
return parent::findBy($criteria, $sort, $limit, $skip);
} | php | {
"resource": ""
} |
q246190 | DraftableEntityAwareTrait.createQueryBuilder | validation | public function createQueryBuilder($findDrafts = false)
{
/* @var \Doctrine\MongoDB\Query\Builder $qb */
/** @noinspection PhpUndefinedClassInspection */
/** @noinspection PhpUndefinedMethodInspection */
$qb = parent::createQueryBuilder();
if (null !== $findDrafts) {
$qb->field('isDraft')->equals($findDrafts);
}
return $qb;
} | php | {
"resource": ""
} |
q246191 | DraftableEntityAwareTrait.createDraft | validation | public function createDraft(array $data = null, $persist = false)
{
$data['isDraft'] = true;
return $this->create($data, $persist);
} | php | {
"resource": ""
} |
q246192 | MissingOptionException.getTargetFQCN | validation | public function getTargetFQCN()
{
return is_object($this->target) ? get_class($this->target) : (string) $this->target;
} | php | {
"resource": ""
} |
q246193 | AbstractRatingEntity.checkRatingValue | validation | protected function checkRatingValue($rating, $throwException = true)
{
if (!is_int($rating) || static::RATING_EXCELLENT < $rating || static::RATING_NONE > $rating) {
if ($throwException) {
throw new \InvalidArgumentException(sprintf('%s is not a valid rating value.', $rating));
}
return false;
}
return true;
} | php | {
"resource": ""
} |
q246194 | HelperProxy.call | validation | public function call($method, $args = [], $expect = self::EXPECT_SELF)
{
if (!is_array($args)) {
$expect = $args;
$args = [];
}
if (!$this->helper) {
return $this->expected($expect);
}
return call_user_func_array([$this->helper, $method], $args);
} | php | {
"resource": ""
} |
q246195 | InjectHeadscriptInitializer.initialize | validation | public function initialize($instance, ServiceLocatorInterface $serviceLocator)
{
/* @var $serviceLocator \Zend\Form\FormElementManager\FormElementManagerV3Polyfill */
if (!$instance instanceof HeadscriptProviderInterface) {
return;
}
$scripts = $instance->getHeadscripts();
if (!is_array($scripts) || empty($scripts)) {
return;
}
/* @var $basepath \Zend\View\Helper\BasePath
* @var $headscript \Zend\View\Helper\HeadScript */
$services = $serviceLocator;
$helpers = $services->get('ViewHelperManager');
$basepath = $helpers->get('basepath');
$headscript = $helpers->get('headscript');
foreach ($scripts as $script) {
$headscript->appendFile($basepath($script));
}
} | php | {
"resource": ""
} |
q246196 | InsertFile.listenToRenderer | validation | public function listenToRenderer()
{
if ($this->ListenersUnaware) {
// set a listener at the end of the Rendering-Process
// to announce what files have been inserted
$this->ListenersUnaware = false;
$view = $this->serviceManager->get('View');
$viewEvents = $view->getEventManager();
// rendering ist over
// get the attached Files very early
// before any other postprocessing has started
$viewEvents->attach(ViewEvent::EVENT_RESPONSE, array($this, 'anounceAttachedFiles'), 1000);
}
} | php | {
"resource": ""
} |
q246197 | ProxyDecorator.proxy | validation | protected function proxy()
{
$args = func_get_args();
$method = array_shift($args);
$callback = array($this->object, $method);
if (!is_callable($callback)) {
throw new \BadMethodCallException(
sprintf(
'Cannot proxy "%s" to "%s": Unknown method.',
$method,
get_class($this->object)
)
);
}
$return = call_user_func_array($callback, $args);
if ($return === $this->object) {
// Return this decorator instead of the wrapped entity.
$return = $this;
}
return $return;
} | php | {
"resource": ""
} |
q246198 | AbstractUpdateFilesPermissionsSubscriber.onFlush | validation | public function onFlush(OnFlushEventArgs $args)
{
$dm = $args->getDocumentManager();
$uow = $dm->getUnitOfWork();
$filter = function ($element) {
return $element instanceof $this->targetDocument
&& $element instanceof PermissionsAwareInterface
&& $element->getPermissions()->hasChanged();
};
$inserts = array_filter($uow->getScheduledDocumentInsertions(), $filter);
$updates = array_filter($uow->getScheduledDocumentUpdates(), $filter);
$this->process($inserts, $dm, $uow, true);
$this->process($updates, $dm, $uow);
} | php | {
"resource": ""
} |
q246199 | XmlRenderListener.attach | validation | public function attach(EventManagerInterface $events, $priority = 1)
{
$callback = array($this, 'injectXmlTemplate');
/*
* We need to hack a little, because injectViewModelListener is attached to the
* shared event manager and triggered in Controller, we need to attach to the
* EVENT_DISPATCH event in the shared manager, to be sure that this listener is
* run before injectViewModelListener
*/
$this->sharedListeners[] = $events->getSharedManager()->attach(
'Zend\Stdlib\DispatchableInterface',
MvcEvent::EVENT_DISPATCH,
$callback,
-96
);
$this->listeners[] = $events->attach(MvcEvent::EVENT_DISPATCH_ERROR, $callback, -96);
$this->listeners[] = $events->attach(MvcEvent::EVENT_RENDER_ERROR, $callback, -96);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.