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 |
|---|---|---|---|---|---|---|---|---|---|---|
fingo/laravel-session-fallback | src/SessionFallback.php | SessionFallback.createDriver | protected function createDriver($driver)
{
try {
return parent::createDriver($driver);
} catch (Exception $e) {
if ($newDriver = $this->nextDriver($driver)) {
return $this->createDriver($newDriver);
}
throw $e;
}
} | php | protected function createDriver($driver)
{
try {
return parent::createDriver($driver);
} catch (Exception $e) {
if ($newDriver = $this->nextDriver($driver)) {
return $this->createDriver($newDriver);
}
throw $e;
}
} | [
"protected",
"function",
"createDriver",
"(",
"$",
"driver",
")",
"{",
"try",
"{",
"return",
"parent",
"::",
"createDriver",
"(",
"$",
"driver",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"if",
"(",
"$",
"newDriver",
"=",
"$",
"thi... | Create a new driver instance.
@param string $driver
@return mixed
@throws \InvalidArgumentException
@throws Exception | [
"Create",
"a",
"new",
"driver",
"instance",
"."
] | train | https://github.com/fingo/laravel-session-fallback/blob/0fb4f9adf33137ca1c1ceee3733fe0f700f598dd/src/SessionFallback.php#L35-L45 |
fingo/laravel-session-fallback | src/SessionFallback.php | SessionFallback.createCacheHandler | protected function createCacheHandler($driver)
{
$handler = parent::createCacheHandler($driver);
if (!$this->validateCacheHandler($driver, $handler)) {
throw new \UnexpectedValueException('Wrong cache driver found');
}
return $handler;
} | php | protected function createCacheHandler($driver)
{
$handler = parent::createCacheHandler($driver);
if (!$this->validateCacheHandler($driver, $handler)) {
throw new \UnexpectedValueException('Wrong cache driver found');
}
return $handler;
} | [
"protected",
"function",
"createCacheHandler",
"(",
"$",
"driver",
")",
"{",
"$",
"handler",
"=",
"parent",
"::",
"createCacheHandler",
"(",
"$",
"driver",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"validateCacheHandler",
"(",
"$",
"driver",
",",
"$",
... | Create the cache based session handler instance.
@param string $driver
@return \Illuminate\Session\CacheBasedSessionHandler | [
"Create",
"the",
"cache",
"based",
"session",
"handler",
"instance",
"."
] | train | https://github.com/fingo/laravel-session-fallback/blob/0fb4f9adf33137ca1c1ceee3733fe0f700f598dd/src/SessionFallback.php#L53-L60 |
fingo/laravel-session-fallback | src/SessionFallback.php | SessionFallback.createRedisDriver | protected function createRedisDriver()
{
$handler = $this->createCacheHandler('redis');
if (!is_a($handler->getCache()->getStore(), RedisStore::class)) {
throw new \UnexpectedValueException('Wrong cache driver found');
}
$handler->getCache()->getStore()->getRedis()->ping();
$handler->getCache()->getStore()->setConnection($this->app['config']['session.connection']);
return $this->buildSession($handler);
} | php | protected function createRedisDriver()
{
$handler = $this->createCacheHandler('redis');
if (!is_a($handler->getCache()->getStore(), RedisStore::class)) {
throw new \UnexpectedValueException('Wrong cache driver found');
}
$handler->getCache()->getStore()->getRedis()->ping();
$handler->getCache()->getStore()->setConnection($this->app['config']['session.connection']);
return $this->buildSession($handler);
} | [
"protected",
"function",
"createRedisDriver",
"(",
")",
"{",
"$",
"handler",
"=",
"$",
"this",
"->",
"createCacheHandler",
"(",
"'redis'",
")",
";",
"if",
"(",
"!",
"is_a",
"(",
"$",
"handler",
"->",
"getCache",
"(",
")",
"->",
"getStore",
"(",
")",
",... | Create an instance of the Redis session driver.
@return \Illuminate\Session\Store | [
"Create",
"an",
"instance",
"of",
"the",
"Redis",
"session",
"driver",
"."
] | train | https://github.com/fingo/laravel-session-fallback/blob/0fb4f9adf33137ca1c1ceee3733fe0f700f598dd/src/SessionFallback.php#L68-L77 |
fingo/laravel-session-fallback | src/SessionFallback.php | SessionFallback.createDatabaseDriver | protected function createDatabaseDriver()
{
$connection = $this->getDatabaseConnection();
$connection->getReadPdo();
$table = $this->app['config']['session.table'];
return $this->buildSession(new DatabaseSessionHandler($connection, $table, $this->app));
} | php | protected function createDatabaseDriver()
{
$connection = $this->getDatabaseConnection();
$connection->getReadPdo();
$table = $this->app['config']['session.table'];
return $this->buildSession(new DatabaseSessionHandler($connection, $table, $this->app));
} | [
"protected",
"function",
"createDatabaseDriver",
"(",
")",
"{",
"$",
"connection",
"=",
"$",
"this",
"->",
"getDatabaseConnection",
"(",
")",
";",
"$",
"connection",
"->",
"getReadPdo",
"(",
")",
";",
"$",
"table",
"=",
"$",
"this",
"->",
"app",
"[",
"'c... | Get next driver name based on fallback order
@return \Illuminate\Session\Store | [
"Get",
"next",
"driver",
"name",
"based",
"on",
"fallback",
"order"
] | train | https://github.com/fingo/laravel-session-fallback/blob/0fb4f9adf33137ca1c1ceee3733fe0f700f598dd/src/SessionFallback.php#L98-L105 |
fingo/laravel-session-fallback | src/SessionFallback.php | SessionFallback.validateCacheHandler | public function validateCacheHandler($driver, $handler)
{
$store = $handler->getCache()->getStore();
return static::$expectedStores[$driver] !== get_class($store);
} | php | public function validateCacheHandler($driver, $handler)
{
$store = $handler->getCache()->getStore();
return static::$expectedStores[$driver] !== get_class($store);
} | [
"public",
"function",
"validateCacheHandler",
"(",
"$",
"driver",
",",
"$",
"handler",
")",
"{",
"$",
"store",
"=",
"$",
"handler",
"->",
"getCache",
"(",
")",
"->",
"getStore",
"(",
")",
";",
"return",
"static",
"::",
"$",
"expectedStores",
"[",
"$",
... | Check if session has right store
@param $driver
@param $handler
@return bool | [
"Check",
"if",
"session",
"has",
"right",
"store"
] | train | https://github.com/fingo/laravel-session-fallback/blob/0fb4f9adf33137ca1c1ceee3733fe0f700f598dd/src/SessionFallback.php#L114-L118 |
makinacorpus/drupal-ucms | ucms_layout/src/Admin/ThemeRegionsForm.php | ThemeRegionsForm.buildForm | public function buildForm(array $form, FormStateInterface $form_state, $theme = null)
{
if (!$theme) {
return $form;
}
$form['#theme_key'] = $theme;
$all = system_region_list($theme);
$enabled = $this->contextManager->getThemeRegionConfig($theme);
$form['regions'] = [
'#type' => 'item',
'#title' => $this->t("Enable regions"),
'#tree' => true,
//'#collapsible' => false,
'#description' => t("Disable all regions if you do not with layouts to be usable with this theme."),
];
foreach ($all as $key => $label) {
$form['regions'][$key] = [
'#type' => 'select',
'#title' => $label,
'#options' => [
ContextManager::CONTEXT_NONE => $this->t("Disabled"),
ContextManager::CONTEXT_PAGE => $this->t("Page context"),
ContextManager::CONTEXT_SITE => $this->t("Site context"),
],
'#default_value' => isset($enabled[$key]) ? $enabled[$key] : ContextManager::CONTEXT_NONE,
];
}
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Save configuration')
];
return $form;
} | php | public function buildForm(array $form, FormStateInterface $form_state, $theme = null)
{
if (!$theme) {
return $form;
}
$form['#theme_key'] = $theme;
$all = system_region_list($theme);
$enabled = $this->contextManager->getThemeRegionConfig($theme);
$form['regions'] = [
'#type' => 'item',
'#title' => $this->t("Enable regions"),
'#tree' => true,
//'#collapsible' => false,
'#description' => t("Disable all regions if you do not with layouts to be usable with this theme."),
];
foreach ($all as $key => $label) {
$form['regions'][$key] = [
'#type' => 'select',
'#title' => $label,
'#options' => [
ContextManager::CONTEXT_NONE => $this->t("Disabled"),
ContextManager::CONTEXT_PAGE => $this->t("Page context"),
ContextManager::CONTEXT_SITE => $this->t("Site context"),
],
'#default_value' => isset($enabled[$key]) ? $enabled[$key] : ContextManager::CONTEXT_NONE,
];
}
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Save configuration')
];
return $form;
} | [
"public",
"function",
"buildForm",
"(",
"array",
"$",
"form",
",",
"FormStateInterface",
"$",
"form_state",
",",
"$",
"theme",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"theme",
")",
"{",
"return",
"$",
"form",
";",
"}",
"$",
"form",
"[",
"'#theme_... | {@inheritdoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_layout/src/Admin/ThemeRegionsForm.php#L48-L87 |
makinacorpus/drupal-ucms | ucms_layout/src/Admin/ThemeRegionsForm.php | ThemeRegionsForm.submitForm | public function submitForm(array &$form, FormStateInterface $form_state)
{
// Save enabled regions only.
$enabled = array_filter($form_state->getValue('regions'));
variable_set('ucms_layout_regions_' . $form['#theme_key'], $enabled);
drupal_set_message($this->t('The configuration options have been saved.'));
} | php | public function submitForm(array &$form, FormStateInterface $form_state)
{
// Save enabled regions only.
$enabled = array_filter($form_state->getValue('regions'));
variable_set('ucms_layout_regions_' . $form['#theme_key'], $enabled);
drupal_set_message($this->t('The configuration options have been saved.'));
} | [
"public",
"function",
"submitForm",
"(",
"array",
"&",
"$",
"form",
",",
"FormStateInterface",
"$",
"form_state",
")",
"{",
"// Save enabled regions only.",
"$",
"enabled",
"=",
"array_filter",
"(",
"$",
"form_state",
"->",
"getValue",
"(",
"'regions'",
")",
")"... | {@inheritdoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_layout/src/Admin/ThemeRegionsForm.php#L92-L98 |
qloog/yaf-library | src/Rpc/Client/Json/Inner.php | Inner.doRequest | protected function doRequest($reqParams)
{
Log::debug('RPC json inner request params', $reqParams);
if ($this->method == 'GET') {
$res = (new Client())->get($this->url, ['params' => json_encode($reqParams)]);
} else {
$res = (new Client())->post($this->url, [], ['params' => json_encode($reqParams)]);
}
Log::debug('RPC json inner request result', ['result' => $res]);
if ($res->code() != 200) {
Log::warning('RPC error', ['url' => $this->url, 'params' => $reqParams, 'result' => $res]);
throw new \Exception('RPC request failed');
}
return json_decode($res, true);
} | php | protected function doRequest($reqParams)
{
Log::debug('RPC json inner request params', $reqParams);
if ($this->method == 'GET') {
$res = (new Client())->get($this->url, ['params' => json_encode($reqParams)]);
} else {
$res = (new Client())->post($this->url, [], ['params' => json_encode($reqParams)]);
}
Log::debug('RPC json inner request result', ['result' => $res]);
if ($res->code() != 200) {
Log::warning('RPC error', ['url' => $this->url, 'params' => $reqParams, 'result' => $res]);
throw new \Exception('RPC request failed');
}
return json_decode($res, true);
} | [
"protected",
"function",
"doRequest",
"(",
"$",
"reqParams",
")",
"{",
"Log",
"::",
"debug",
"(",
"'RPC json inner request params'",
",",
"$",
"reqParams",
")",
";",
"if",
"(",
"$",
"this",
"->",
"method",
"==",
"'GET'",
")",
"{",
"$",
"res",
"=",
"(",
... | 发起RPC请求
@param $reqParams
@return \PHPCasts\Http\Response|null
@throws \Exception | [
"发起RPC请求"
] | train | https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Rpc/Client/Json/Inner.php#L61-L80 |
qloog/yaf-library | src/Rpc/Client/Json/Inner.php | Inner.parseRPCResult | protected function parseRPCResult($res)
{
$rpcRes = $res['data'];
if (!empty($rpcRes['output'])) {
echo $rpcRes['output'];
}
if (!empty($rpcRes['exception'])) {
$exception = new \Exception($rpcRes['exception']['msg'], $rpcRes['exception']['code']);
$file = new \ReflectionProperty($exception, 'file');
$file->setAccessible(true);
$file->setValue($exception, $rpcRes['exception']['file']);
$line = new \ReflectionProperty($exception, 'line');
$line->setAccessible(true);
$line->setValue($exception, $rpcRes['exception']['line']);
throw $exception;
}
if (isset($rpcRes['status']) && $rpcRes['status'] != 200) {
return false;
}
return isset($rpcRes['return']) ? $rpcRes['return'] : null;
} | php | protected function parseRPCResult($res)
{
$rpcRes = $res['data'];
if (!empty($rpcRes['output'])) {
echo $rpcRes['output'];
}
if (!empty($rpcRes['exception'])) {
$exception = new \Exception($rpcRes['exception']['msg'], $rpcRes['exception']['code']);
$file = new \ReflectionProperty($exception, 'file');
$file->setAccessible(true);
$file->setValue($exception, $rpcRes['exception']['file']);
$line = new \ReflectionProperty($exception, 'line');
$line->setAccessible(true);
$line->setValue($exception, $rpcRes['exception']['line']);
throw $exception;
}
if (isset($rpcRes['status']) && $rpcRes['status'] != 200) {
return false;
}
return isset($rpcRes['return']) ? $rpcRes['return'] : null;
} | [
"protected",
"function",
"parseRPCResult",
"(",
"$",
"res",
")",
"{",
"$",
"rpcRes",
"=",
"$",
"res",
"[",
"'data'",
"]",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"rpcRes",
"[",
"'output'",
"]",
")",
")",
"{",
"echo",
"$",
"rpcRes",
"[",
"'output'",... | 解析RPC请求结果
@param $res
@return bool|null
@throws \Exception | [
"解析RPC请求结果"
] | train | https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Rpc/Client/Json/Inner.php#L90-L117 |
makinacorpus/drupal-ucms | ucms_site/src/Form/NodeSetHome.php | NodeSetHome.buildForm | public function buildForm(array $form, FormStateInterface $form_state, $node = null)
{
if (!$node) {
$this->logger('form')->critical("There is no node!");
return $form;
}
$form_state->setTemporaryValue('node', $node);
$form['actions']['#type'] = 'actions';
$form['actions']['continue'] = [
'#type' => 'submit',
'#value' => $this->t("Set as home page"),
];
if (isset($_GET['destination'])) {
$form['actions']['cancel'] = [
'#markup' => l(
$this->t("Cancel"),
$_GET['destination'],
['attributes' => ['class' => ['btn', 'btn-danger']]]
),
];
}
return $form;
} | php | public function buildForm(array $form, FormStateInterface $form_state, $node = null)
{
if (!$node) {
$this->logger('form')->critical("There is no node!");
return $form;
}
$form_state->setTemporaryValue('node', $node);
$form['actions']['#type'] = 'actions';
$form['actions']['continue'] = [
'#type' => 'submit',
'#value' => $this->t("Set as home page"),
];
if (isset($_GET['destination'])) {
$form['actions']['cancel'] = [
'#markup' => l(
$this->t("Cancel"),
$_GET['destination'],
['attributes' => ['class' => ['btn', 'btn-danger']]]
),
];
}
return $form;
} | [
"public",
"function",
"buildForm",
"(",
"array",
"$",
"form",
",",
"FormStateInterface",
"$",
"form_state",
",",
"$",
"node",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"node",
")",
"{",
"$",
"this",
"->",
"logger",
"(",
"'form'",
")",
"->",
"critic... | {@inheritdoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Form/NodeSetHome.php#L46-L71 |
makinacorpus/drupal-ucms | ucms_site/src/Form/NodeSetHome.php | NodeSetHome.submitForm | public function submitForm(array &$form, FormStateInterface $form_state)
{
$node = &$form_state->getTemporaryValue('node');
$site = $this->siteManager->getContext();
$site->home_nid = $node->id();
$this->siteManager->getStorage()->save($site, ['home_nid']);
$form_state->setRedirect('node/' . $node->nid);
} | php | public function submitForm(array &$form, FormStateInterface $form_state)
{
$node = &$form_state->getTemporaryValue('node');
$site = $this->siteManager->getContext();
$site->home_nid = $node->id();
$this->siteManager->getStorage()->save($site, ['home_nid']);
$form_state->setRedirect('node/' . $node->nid);
} | [
"public",
"function",
"submitForm",
"(",
"array",
"&",
"$",
"form",
",",
"FormStateInterface",
"$",
"form_state",
")",
"{",
"$",
"node",
"=",
"&",
"$",
"form_state",
"->",
"getTemporaryValue",
"(",
"'node'",
")",
";",
"$",
"site",
"=",
"$",
"this",
"->",... | Step B form submit | [
"Step",
"B",
"form",
"submit"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Form/NodeSetHome.php#L76-L85 |
accompli/accompli | src/DependencyInjection/ConfigurationServiceRegistrationCompilerPass.php | ConfigurationServiceRegistrationCompilerPass.process | public function process(ContainerBuilder $container)
{
$configuration = $container->get('configuration', ContainerInterface::NULL_ON_INVALID_REFERENCE);
if ($configuration instanceof ConfigurationInterface) {
$this->registerService($container, 'deployment_strategy', $configuration->getDeploymentStrategyClass());
$connectionManager = $container->get('connection_manager', ContainerInterface::NULL_ON_INVALID_REFERENCE);
if ($connectionManager instanceof ConnectionManagerInterface) {
foreach ($configuration->getDeploymentConnectionClasses() as $connectionType => $connectionAdapterClass) {
$connectionManager->registerConnectionAdapter($connectionType, $connectionAdapterClass);
}
}
}
} | php | public function process(ContainerBuilder $container)
{
$configuration = $container->get('configuration', ContainerInterface::NULL_ON_INVALID_REFERENCE);
if ($configuration instanceof ConfigurationInterface) {
$this->registerService($container, 'deployment_strategy', $configuration->getDeploymentStrategyClass());
$connectionManager = $container->get('connection_manager', ContainerInterface::NULL_ON_INVALID_REFERENCE);
if ($connectionManager instanceof ConnectionManagerInterface) {
foreach ($configuration->getDeploymentConnectionClasses() as $connectionType => $connectionAdapterClass) {
$connectionManager->registerConnectionAdapter($connectionType, $connectionAdapterClass);
}
}
}
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"configuration",
"=",
"$",
"container",
"->",
"get",
"(",
"'configuration'",
",",
"ContainerInterface",
"::",
"NULL_ON_INVALID_REFERENCE",
")",
";",
"if",
"(",
"$",
"confi... | Adds deployment classes, defined in the configuration service, as services.
@param ContainerBuilder $container | [
"Adds",
"deployment",
"classes",
"defined",
"in",
"the",
"configuration",
"service",
"as",
"services",
"."
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/DependencyInjection/ConfigurationServiceRegistrationCompilerPass.php#L23-L36 |
accompli/accompli | src/DependencyInjection/ConfigurationServiceRegistrationCompilerPass.php | ConfigurationServiceRegistrationCompilerPass.registerService | private function registerService(ContainerBuilder $container, $serviceId, $serviceClass)
{
if (class_exists($serviceClass)) {
$container->register($serviceId, $serviceClass);
}
} | php | private function registerService(ContainerBuilder $container, $serviceId, $serviceClass)
{
if (class_exists($serviceClass)) {
$container->register($serviceId, $serviceClass);
}
} | [
"private",
"function",
"registerService",
"(",
"ContainerBuilder",
"$",
"container",
",",
"$",
"serviceId",
",",
"$",
"serviceClass",
")",
"{",
"if",
"(",
"class_exists",
"(",
"$",
"serviceClass",
")",
")",
"{",
"$",
"container",
"->",
"register",
"(",
"$",
... | Registers a service with the service container when the class exists.
@param ContainerBuilder $container
@param string $serviceId
@param string $serviceClass | [
"Registers",
"a",
"service",
"with",
"the",
"service",
"container",
"when",
"the",
"class",
"exists",
"."
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/DependencyInjection/ConfigurationServiceRegistrationCompilerPass.php#L45-L50 |
oasmobile/php-aws-wrappers | src/AwsWrappers/S3Client.php | S3Client.getPresignedUri | public function getPresignedUri($path, $expires = '+30 minutes')
{
if (preg_match('#^s3://(.*?)/(.*)$#', $path, $matches)) {
$bucket = $matches[1];
$path = $matches[2];
}
else {
throw new \InvalidArgumentException("path should be a full path starting with s3://");
}
$path = ltrim($path, "/");
$path = preg_replace('#/+#', '/', $path);
$cmd = $this->getCommand(
'GetObject',
[
"Bucket" => $bucket,
"Key" => $path,
]
);
$req = $this->createPresignedRequest($cmd, $expires);
return strval($req->getUri());
} | php | public function getPresignedUri($path, $expires = '+30 minutes')
{
if (preg_match('#^s3://(.*?)/(.*)$#', $path, $matches)) {
$bucket = $matches[1];
$path = $matches[2];
}
else {
throw new \InvalidArgumentException("path should be a full path starting with s3://");
}
$path = ltrim($path, "/");
$path = preg_replace('#/+#', '/', $path);
$cmd = $this->getCommand(
'GetObject',
[
"Bucket" => $bucket,
"Key" => $path,
]
);
$req = $this->createPresignedRequest($cmd, $expires);
return strval($req->getUri());
} | [
"public",
"function",
"getPresignedUri",
"(",
"$",
"path",
",",
"$",
"expires",
"=",
"'+30 minutes'",
")",
"{",
"if",
"(",
"preg_match",
"(",
"'#^s3://(.*?)/(.*)$#'",
",",
"$",
"path",
",",
"$",
"matches",
")",
")",
"{",
"$",
"bucket",
"=",
"$",
"matches... | @NOTE: presigned URL will not work in AWS China
@param $path
@param string $expires
@return string | [
"@NOTE",
":",
"presigned",
"URL",
"will",
"not",
"work",
"in",
"AWS",
"China"
] | train | https://github.com/oasmobile/php-aws-wrappers/blob/0f756dc60ef6f51e9a99f67c9125289e40f19e3f/src/AwsWrappers/S3Client.php#L37-L59 |
BugBuster1701/botdetection | src/modules/ModuleFrontendDemo2.php | ModuleFrontendDemo2.compile | protected function compile()
{
$arrFields = array();
$arrFields['name'] = array
(
'name' => 'name',
'label' => $GLOBALS['TL_LANG']['MSC']['botdetectiondemo2_agent'],
'inputType' => 'text',
'eval' => array('mandatory'=>true, 'maxlength'=>256, 'decodeEntities'=>true)
);
$arrFields['captcha'] = array
(
'name' => 'captcha',
'label' => $GLOBALS['TL_LANG']['MSC']['botdetectiondemo2_captcha'],
'inputType' => 'captcha',
'eval' => array('mandatory'=>true)
);
$doNotSubmit = false;
$arrWidgets = array();
// Initialize widgets
foreach ($arrFields as $arrField)
{
$strClass = $GLOBALS['TL_FFL'][$arrField['inputType']];
// Continue if the class is not defined
if (!$this->classFileExists($strClass))
{
continue;
}
$arrField['eval']['required'] = $arrField['eval']['mandatory'];
$objWidget = new $strClass($strClass::getAttributesFromDca($arrField, $arrField['name'], $arrField['value']));
// Validate widget
if (\Input::post('FORM_SUBMIT') == 'botdetectiondemo2')
{
$objWidget->validate();
if ($objWidget->hasErrors())
{
$doNotSubmit = true;
}
}
$arrWidgets[$arrField['name']] = $objWidget;
}
$this->Template->fields = $arrWidgets;
$this->Template->submit = $GLOBALS['TL_LANG']['MSC']['botdetectiondemo2_submit'];
$this->Template->action = ampersand(\Environment::get('request'));
$this->Template->hasError = $doNotSubmit;
if (\Input::post('FORM_SUBMIT') == 'botdetectiondemo2' && !$doNotSubmit)
{
$arrSet = array( 'agent_name' => \Input::post('name',true) );
//einzel tests direkt aufgerufen
$test01 = CheckBotAgentSimple::checkAgent($arrSet['agent_name']);
$test02 = CheckBotAgentExtended::checkAgentName($arrSet['agent_name']);
$BrowsCapInfo = CheckBotAgentExtended::getBrowscapResult($arrSet['agent_name']);
$not1 = ($test01) ? "<span style=\"color:green;\">".$GLOBALS['TL_LANG']['MSC']['botdetectiondemo2_found']."</span>" : "<span style=\"color:red;\">".$GLOBALS['TL_LANG']['MSC']['botdetectiondemo2_not']."</span>";
$not2 = ($test02) ? "<span style=\"color:green;\">".$GLOBALS['TL_LANG']['MSC']['botdetectiondemo2_found']."</span>" : "<span style=\"color:red;\">".$GLOBALS['TL_LANG']['MSC']['botdetectiondemo2_not']."</span>";
$not3 = ($test02) ? " (".$test02.")" : "";
$messages = "<strong>".$GLOBALS['TL_LANG']['MSC']['botdetectiondemo2_message_1'].":</strong><br />".$arrSet['agent_name']."<br /><br />";
$messages .= "<div style=\"font-weight:bold; width:190px;float:left;\">CheckBotAgentSimple:</div> ".$not1."<br />";
$messages .= "<div style=\"font-weight:bold; width:190px;float:left;\">CheckBotAgentExtended:</div> ".$not2.$not3."<br />";
$messages .= "<div style=\"font-weight:bold; width:190px;float:left;\">BrowsCapInfo:</div><pre>".print_r($BrowsCapInfo,true)."</pre><br />";
$this->Template->message = $messages;
$arrWidgets = array();
foreach ($arrFields as $arrField)
{
$strClass = $GLOBALS['TL_FFL'][$arrField['inputType']];
// Continue if the class is not defined
if (!$this->classFileExists($strClass)) { continue; }
$arrField['eval']['required'] = $arrField['eval']['mandatory'];
$objWidget = new $strClass($strClass::getAttributesFromDca($arrField, $arrField['name'], $arrField['value']));
$arrWidgets[$arrField['name']] = $objWidget;
}
$this->Template->fields = $arrWidgets;
}
// get module version
$this->ModuleBotDetection = new \BotDetection\ModuleBotDetection();
$this->Template->version = $this->ModuleBotDetection->getVersion();
} | php | protected function compile()
{
$arrFields = array();
$arrFields['name'] = array
(
'name' => 'name',
'label' => $GLOBALS['TL_LANG']['MSC']['botdetectiondemo2_agent'],
'inputType' => 'text',
'eval' => array('mandatory'=>true, 'maxlength'=>256, 'decodeEntities'=>true)
);
$arrFields['captcha'] = array
(
'name' => 'captcha',
'label' => $GLOBALS['TL_LANG']['MSC']['botdetectiondemo2_captcha'],
'inputType' => 'captcha',
'eval' => array('mandatory'=>true)
);
$doNotSubmit = false;
$arrWidgets = array();
// Initialize widgets
foreach ($arrFields as $arrField)
{
$strClass = $GLOBALS['TL_FFL'][$arrField['inputType']];
// Continue if the class is not defined
if (!$this->classFileExists($strClass))
{
continue;
}
$arrField['eval']['required'] = $arrField['eval']['mandatory'];
$objWidget = new $strClass($strClass::getAttributesFromDca($arrField, $arrField['name'], $arrField['value']));
// Validate widget
if (\Input::post('FORM_SUBMIT') == 'botdetectiondemo2')
{
$objWidget->validate();
if ($objWidget->hasErrors())
{
$doNotSubmit = true;
}
}
$arrWidgets[$arrField['name']] = $objWidget;
}
$this->Template->fields = $arrWidgets;
$this->Template->submit = $GLOBALS['TL_LANG']['MSC']['botdetectiondemo2_submit'];
$this->Template->action = ampersand(\Environment::get('request'));
$this->Template->hasError = $doNotSubmit;
if (\Input::post('FORM_SUBMIT') == 'botdetectiondemo2' && !$doNotSubmit)
{
$arrSet = array( 'agent_name' => \Input::post('name',true) );
//einzel tests direkt aufgerufen
$test01 = CheckBotAgentSimple::checkAgent($arrSet['agent_name']);
$test02 = CheckBotAgentExtended::checkAgentName($arrSet['agent_name']);
$BrowsCapInfo = CheckBotAgentExtended::getBrowscapResult($arrSet['agent_name']);
$not1 = ($test01) ? "<span style=\"color:green;\">".$GLOBALS['TL_LANG']['MSC']['botdetectiondemo2_found']."</span>" : "<span style=\"color:red;\">".$GLOBALS['TL_LANG']['MSC']['botdetectiondemo2_not']."</span>";
$not2 = ($test02) ? "<span style=\"color:green;\">".$GLOBALS['TL_LANG']['MSC']['botdetectiondemo2_found']."</span>" : "<span style=\"color:red;\">".$GLOBALS['TL_LANG']['MSC']['botdetectiondemo2_not']."</span>";
$not3 = ($test02) ? " (".$test02.")" : "";
$messages = "<strong>".$GLOBALS['TL_LANG']['MSC']['botdetectiondemo2_message_1'].":</strong><br />".$arrSet['agent_name']."<br /><br />";
$messages .= "<div style=\"font-weight:bold; width:190px;float:left;\">CheckBotAgentSimple:</div> ".$not1."<br />";
$messages .= "<div style=\"font-weight:bold; width:190px;float:left;\">CheckBotAgentExtended:</div> ".$not2.$not3."<br />";
$messages .= "<div style=\"font-weight:bold; width:190px;float:left;\">BrowsCapInfo:</div><pre>".print_r($BrowsCapInfo,true)."</pre><br />";
$this->Template->message = $messages;
$arrWidgets = array();
foreach ($arrFields as $arrField)
{
$strClass = $GLOBALS['TL_FFL'][$arrField['inputType']];
// Continue if the class is not defined
if (!$this->classFileExists($strClass)) { continue; }
$arrField['eval']['required'] = $arrField['eval']['mandatory'];
$objWidget = new $strClass($strClass::getAttributesFromDca($arrField, $arrField['name'], $arrField['value']));
$arrWidgets[$arrField['name']] = $objWidget;
}
$this->Template->fields = $arrWidgets;
}
// get module version
$this->ModuleBotDetection = new \BotDetection\ModuleBotDetection();
$this->Template->version = $this->ModuleBotDetection->getVersion();
} | [
"protected",
"function",
"compile",
"(",
")",
"{",
"$",
"arrFields",
"=",
"array",
"(",
")",
";",
"$",
"arrFields",
"[",
"'name'",
"]",
"=",
"array",
"(",
"'name'",
"=>",
"'name'",
",",
"'label'",
"=>",
"$",
"GLOBALS",
"[",
"'TL_LANG'",
"]",
"[",
"'M... | Generate module | [
"Generate",
"module"
] | train | https://github.com/BugBuster1701/botdetection/blob/b27cc1d80932af7d29b9f345da9132842d2adbce/src/modules/ModuleFrontendDemo2.php#L64-L153 |
despark/ignicms | database/migrations/2016_06_24_120615_create_permission_tables.php | CreatePermissionTables.up | public function up()
{
$config = config('laravel-permission.table_names');
Schema::create($config['roles'], function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});
Schema::create($config['permissions'], function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});
Schema::create($config['user_has_permissions'], function (Blueprint $table) use ($config) {
$table->integer('user_id')->unsigned();
$table->integer('permission_id')->unsigned();
$table->foreign('user_id')
->references('id')
->on($config['users'])
->onDelete('cascade');
$table->foreign('permission_id')
->references('id')
->on($config['permissions'])
->onDelete('cascade');
$table->primary(['user_id', 'permission_id']);
});
Schema::create($config['user_has_roles'], function (Blueprint $table) use ($config) {
$table->integer('role_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('role_id')
->references('id')
->on($config['roles'])
->onDelete('cascade');
$table->foreign('user_id')
->references('id')
->on($config['users'])
->onDelete('cascade');
$table->primary(['role_id', 'user_id']);
Schema::create($config['role_has_permissions'], function (Blueprint $table) use ($config) {
$table->integer('permission_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->foreign('permission_id')
->references('id')
->on($config['permissions'])
->onDelete('cascade');
$table->foreign('role_id')
->references('id')
->on($config['roles'])
->onDelete('cascade');
$table->primary(['permission_id', 'role_id']);
});
});
} | php | public function up()
{
$config = config('laravel-permission.table_names');
Schema::create($config['roles'], function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});
Schema::create($config['permissions'], function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});
Schema::create($config['user_has_permissions'], function (Blueprint $table) use ($config) {
$table->integer('user_id')->unsigned();
$table->integer('permission_id')->unsigned();
$table->foreign('user_id')
->references('id')
->on($config['users'])
->onDelete('cascade');
$table->foreign('permission_id')
->references('id')
->on($config['permissions'])
->onDelete('cascade');
$table->primary(['user_id', 'permission_id']);
});
Schema::create($config['user_has_roles'], function (Blueprint $table) use ($config) {
$table->integer('role_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('role_id')
->references('id')
->on($config['roles'])
->onDelete('cascade');
$table->foreign('user_id')
->references('id')
->on($config['users'])
->onDelete('cascade');
$table->primary(['role_id', 'user_id']);
Schema::create($config['role_has_permissions'], function (Blueprint $table) use ($config) {
$table->integer('permission_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->foreign('permission_id')
->references('id')
->on($config['permissions'])
->onDelete('cascade');
$table->foreign('role_id')
->references('id')
->on($config['roles'])
->onDelete('cascade');
$table->primary(['permission_id', 'role_id']);
});
});
} | [
"public",
"function",
"up",
"(",
")",
"{",
"$",
"config",
"=",
"config",
"(",
"'laravel-permission.table_names'",
")",
";",
"Schema",
"::",
"create",
"(",
"$",
"config",
"[",
"'roles'",
"]",
",",
"function",
"(",
"Blueprint",
"$",
"table",
")",
"{",
"$",... | Run the migrations.
@return void | [
"Run",
"the",
"migrations",
"."
] | train | https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/database/migrations/2016_06_24_120615_create_permission_tables.php#L13-L79 |
aimeos/ai-admin-extadm | controller/extjs/src/Controller/ExtJS/Catalog/Lists/Standard.php | Standard.deleteItems | public function deleteItems( \stdClass $params )
{
$this->checkParams( $params, array( 'site', 'items' ) );
$this->setLocale( $params->site );
$refIds = [];
$ids = (array) $params->items;
$manager = $this->getManager();
$search = $manager->createSearch();
$search->setConditions( $search->compare( '==', $this->getPrefix() . '.id', $ids ) );
$search->setSlice( 0, count( $ids ) );
foreach( $manager->searchItems( $search ) as $item ) {
$refIds[$item->getDomain()][] = $item->getRefId();
}
$manager->deleteItems( $ids );
if( isset( $refIds['product'] ) )
{
$this->rebuildIndex( (array) $refIds['product'] );
$this->clearCache( (array) $refIds['product'], 'product' );
}
return array(
'items' => $params->items,
'success' => true,
);
} | php | public function deleteItems( \stdClass $params )
{
$this->checkParams( $params, array( 'site', 'items' ) );
$this->setLocale( $params->site );
$refIds = [];
$ids = (array) $params->items;
$manager = $this->getManager();
$search = $manager->createSearch();
$search->setConditions( $search->compare( '==', $this->getPrefix() . '.id', $ids ) );
$search->setSlice( 0, count( $ids ) );
foreach( $manager->searchItems( $search ) as $item ) {
$refIds[$item->getDomain()][] = $item->getRefId();
}
$manager->deleteItems( $ids );
if( isset( $refIds['product'] ) )
{
$this->rebuildIndex( (array) $refIds['product'] );
$this->clearCache( (array) $refIds['product'], 'product' );
}
return array(
'items' => $params->items,
'success' => true,
);
} | [
"public",
"function",
"deleteItems",
"(",
"\\",
"stdClass",
"$",
"params",
")",
"{",
"$",
"this",
"->",
"checkParams",
"(",
"$",
"params",
",",
"array",
"(",
"'site'",
",",
"'items'",
")",
")",
";",
"$",
"this",
"->",
"setLocale",
"(",
"$",
"params",
... | Deletes an item or a list of items.
@param \stdClass $params Associative list of parameters
@return array Associative list with success value | [
"Deletes",
"an",
"item",
"or",
"a",
"list",
"of",
"items",
"."
] | train | https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Catalog/Lists/Standard.php#L45-L74 |
aimeos/ai-admin-extadm | controller/extjs/src/Controller/ExtJS/Catalog/Lists/Standard.php | Standard.saveItems | public function saveItems( \stdClass $params )
{
$this->checkParams( $params, array( 'site', 'items' ) );
$this->setLocale( $params->site );
$ids = $refIds = [];
$manager = $this->getManager();
$items = ( !is_array( $params->items ) ? array( $params->items ) : $params->items );
foreach( $items as $entry )
{
$item = $manager->createItem();
$item->fromArray( (array) $this->transformValues( $entry ) );
$item = $manager->saveItem( $item );
$refIds[$item->getDomain()][] = $item->getRefId();
$ids[] = $item->getId();
}
if( isset( $refIds['product'] ) )
{
$this->rebuildIndex( (array) $refIds['product'] );
$this->clearCache( (array) $refIds['product'], 'product' );
}
return $this->getItems( $ids, $this->getPrefix() );
} | php | public function saveItems( \stdClass $params )
{
$this->checkParams( $params, array( 'site', 'items' ) );
$this->setLocale( $params->site );
$ids = $refIds = [];
$manager = $this->getManager();
$items = ( !is_array( $params->items ) ? array( $params->items ) : $params->items );
foreach( $items as $entry )
{
$item = $manager->createItem();
$item->fromArray( (array) $this->transformValues( $entry ) );
$item = $manager->saveItem( $item );
$refIds[$item->getDomain()][] = $item->getRefId();
$ids[] = $item->getId();
}
if( isset( $refIds['product'] ) )
{
$this->rebuildIndex( (array) $refIds['product'] );
$this->clearCache( (array) $refIds['product'], 'product' );
}
return $this->getItems( $ids, $this->getPrefix() );
} | [
"public",
"function",
"saveItems",
"(",
"\\",
"stdClass",
"$",
"params",
")",
"{",
"$",
"this",
"->",
"checkParams",
"(",
"$",
"params",
",",
"array",
"(",
"'site'",
",",
"'items'",
")",
")",
";",
"$",
"this",
"->",
"setLocale",
"(",
"$",
"params",
"... | Creates a new list item or updates an existing one or a list thereof.
@param \stdClass $params Associative array containing the item properties | [
"Creates",
"a",
"new",
"list",
"item",
"or",
"updates",
"an",
"existing",
"one",
"or",
"a",
"list",
"thereof",
"."
] | train | https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Catalog/Lists/Standard.php#L82-L108 |
aimeos/ai-admin-extadm | controller/extjs/src/Controller/ExtJS/Catalog/Lists/Standard.php | Standard.searchItems | public function searchItems( \stdClass $params )
{
$this->checkParams( $params, array( 'site' ) );
$this->setLocale( $params->site );
$totalList = 0;
$search = $this->initCriteria( $this->getManager()->createSearch(), $params );
$result = $this->getManager()->searchItems( $search, [], $totalList );
$idLists = [];
$listItems = [];
foreach( $result as $item )
{
if( ( $domain = $item->getDomain() ) != '' ) {
$idLists[$domain][] = $item->getRefId();
}
$listItems[] = (object) $item->toArray( true );
}
return array(
'items' => $listItems,
'total' => $totalList,
'graph' => $this->getDomainItems( $idLists ),
'success' => true,
);
} | php | public function searchItems( \stdClass $params )
{
$this->checkParams( $params, array( 'site' ) );
$this->setLocale( $params->site );
$totalList = 0;
$search = $this->initCriteria( $this->getManager()->createSearch(), $params );
$result = $this->getManager()->searchItems( $search, [], $totalList );
$idLists = [];
$listItems = [];
foreach( $result as $item )
{
if( ( $domain = $item->getDomain() ) != '' ) {
$idLists[$domain][] = $item->getRefId();
}
$listItems[] = (object) $item->toArray( true );
}
return array(
'items' => $listItems,
'total' => $totalList,
'graph' => $this->getDomainItems( $idLists ),
'success' => true,
);
} | [
"public",
"function",
"searchItems",
"(",
"\\",
"stdClass",
"$",
"params",
")",
"{",
"$",
"this",
"->",
"checkParams",
"(",
"$",
"params",
",",
"array",
"(",
"'site'",
")",
")",
";",
"$",
"this",
"->",
"setLocale",
"(",
"$",
"params",
"->",
"site",
"... | Retrieves all items matching the given criteria.
@param \stdClass $params Associative array containing the parameters
@return array List of associative arrays with item properties, total number of items and success property | [
"Retrieves",
"all",
"items",
"matching",
"the",
"given",
"criteria",
"."
] | train | https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Catalog/Lists/Standard.php#L117-L143 |
aimeos/ai-admin-extadm | controller/extjs/src/Controller/ExtJS/Catalog/Lists/Standard.php | Standard.rebuildIndex | protected function rebuildIndex( array $prodIds )
{
$context = $this->getContext();
$productManager = \Aimeos\MShop\Factory::createManager( $context, 'product' );
$search = $productManager->createSearch();
$search->setConditions( $search->compare( '==', 'product.id', $prodIds ) );
$search->setSlice( 0, count( $prodIds ) );
$indexManager = \Aimeos\MShop\Factory::createManager( $context, 'index' );
$indexManager->rebuildIndex( $productManager->searchItems( $search ) );
} | php | protected function rebuildIndex( array $prodIds )
{
$context = $this->getContext();
$productManager = \Aimeos\MShop\Factory::createManager( $context, 'product' );
$search = $productManager->createSearch();
$search->setConditions( $search->compare( '==', 'product.id', $prodIds ) );
$search->setSlice( 0, count( $prodIds ) );
$indexManager = \Aimeos\MShop\Factory::createManager( $context, 'index' );
$indexManager->rebuildIndex( $productManager->searchItems( $search ) );
} | [
"protected",
"function",
"rebuildIndex",
"(",
"array",
"$",
"prodIds",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"getContext",
"(",
")",
";",
"$",
"productManager",
"=",
"\\",
"Aimeos",
"\\",
"MShop",
"\\",
"Factory",
"::",
"createManager",
"(",
... | Rebuild the index for the given product IDs
@param array $prodIds List of product IDs | [
"Rebuild",
"the",
"index",
"for",
"the",
"given",
"product",
"IDs"
] | train | https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Catalog/Lists/Standard.php#L205-L216 |
aimeos/ai-admin-extadm | controller/extjs/src/Controller/ExtJS/Coupon/Code/Standard.php | Standard.uploadFile | public function uploadFile( \stdClass $params )
{
$this->checkParams( $params, array( 'site', 'parentid' ) );
$this->setLocale( $params->site );
if( ( $fileinfo = reset( $_FILES ) ) === false ) {
throw new \Aimeos\Controller\ExtJS\Exception( 'No file was uploaded' );
}
$config = $this->getContext()->getConfig();
/** controller/extjs/coupon/code/standard/uploaddir
* Upload directory for text files that should be imported
*
* The upload directory must be an absolute path. Avoid a trailing slash
* at the end of the upload directory string!
*
* @param string Absolute path including a leading slash
* @since 2014.09
* @category Developer
*/
$dir = $config->get( 'controller/extjs/coupon/code/standard/uploaddir', 'uploads' );
/** controller/extjs/coupon/code/standard/enablecheck
* Enables checking uploaded files if they are valid and not part of an attack
*
* This configuration option is for unit testing only! Please don't disable
* the checks for uploaded files in production environments as this
* would give attackers the possibility to infiltrate your installation!
*
* @param boolean True to enable, false to disable
* @since 2014.09
* @category Developer
*/
if( $config->get( 'controller/extjs/coupon/code/standard/enablecheck', true ) ) {
$this->checkFileUpload( $fileinfo['tmp_name'], $fileinfo['error'] );
}
$fileext = pathinfo( $fileinfo['name'], PATHINFO_EXTENSION );
$dest = $dir . DIRECTORY_SEPARATOR . md5( $fileinfo['name'] . time() . getmypid() ) . '.' . $fileext;
if( rename( $fileinfo['tmp_name'], $dest ) !== true )
{
$msg = sprintf( 'Uploaded file could not be moved to upload directory "%1$s"', $dir );
throw new \Aimeos\Controller\ExtJS\Exception( $msg );
}
/** controller/extjs/coupon/code/standard/fileperms
* File permissions used when storing uploaded files
*
* The representation of the permissions is in octal notation (using 0-7)
* with a leading zero. The first number after the leading zero are the
* permissions for the web server creating the directory, the second is
* for the primary group of the web server and the last number represents
* the permissions for everyone else.
*
* You should use 0660 or 0600 for the permissions as the web server needs
* to manage the files. The group permissions are important if you plan
* to upload files directly via FTP or by other means because then the
* web server needs to be able to read and manage those files. In this
* case use 0660 as permissions, otherwise you can limit them to 0600.
*
* A more detailed description of the meaning of the Unix file permission
* bits can be found in the Wikipedia article about
* {@link https://en.wikipedia.org/wiki/File_system_permissions#Numeric_notation file system permissions}
*
* @param integer Octal Unix permission representation
* @since 2014.09
* @category Developer
*/
$perms = $config->get( 'controller/extjs/coupon/code/standard/fileperms', 0660 );
if( chmod( $dest, $perms ) !== true )
{
$msg = sprintf( 'Could not set permissions "%1$s" for file "%2$s"', $perms, $dest );
throw new \Aimeos\Controller\ExtJS\Exception( $msg );
}
$result = (object) array(
'site' => $params->site,
'items' => array(
(object) array(
'job.label' => 'Coupon code import: ' . $fileinfo['name'],
'job.method' => 'Coupon_Code.importFile',
'job.parameter' => array(
'site' => $params->site,
'parentid' => $params->parentid,
'items' => $dest,
),
'job.status' => 1,
),
),
);
$jobController = \Aimeos\Controller\ExtJS\Admin\Job\Factory::createController( $this->getContext() );
$jobController->saveItems( $result );
return array(
'items' => $dest,
'success' => true,
);
} | php | public function uploadFile( \stdClass $params )
{
$this->checkParams( $params, array( 'site', 'parentid' ) );
$this->setLocale( $params->site );
if( ( $fileinfo = reset( $_FILES ) ) === false ) {
throw new \Aimeos\Controller\ExtJS\Exception( 'No file was uploaded' );
}
$config = $this->getContext()->getConfig();
/** controller/extjs/coupon/code/standard/uploaddir
* Upload directory for text files that should be imported
*
* The upload directory must be an absolute path. Avoid a trailing slash
* at the end of the upload directory string!
*
* @param string Absolute path including a leading slash
* @since 2014.09
* @category Developer
*/
$dir = $config->get( 'controller/extjs/coupon/code/standard/uploaddir', 'uploads' );
/** controller/extjs/coupon/code/standard/enablecheck
* Enables checking uploaded files if they are valid and not part of an attack
*
* This configuration option is for unit testing only! Please don't disable
* the checks for uploaded files in production environments as this
* would give attackers the possibility to infiltrate your installation!
*
* @param boolean True to enable, false to disable
* @since 2014.09
* @category Developer
*/
if( $config->get( 'controller/extjs/coupon/code/standard/enablecheck', true ) ) {
$this->checkFileUpload( $fileinfo['tmp_name'], $fileinfo['error'] );
}
$fileext = pathinfo( $fileinfo['name'], PATHINFO_EXTENSION );
$dest = $dir . DIRECTORY_SEPARATOR . md5( $fileinfo['name'] . time() . getmypid() ) . '.' . $fileext;
if( rename( $fileinfo['tmp_name'], $dest ) !== true )
{
$msg = sprintf( 'Uploaded file could not be moved to upload directory "%1$s"', $dir );
throw new \Aimeos\Controller\ExtJS\Exception( $msg );
}
/** controller/extjs/coupon/code/standard/fileperms
* File permissions used when storing uploaded files
*
* The representation of the permissions is in octal notation (using 0-7)
* with a leading zero. The first number after the leading zero are the
* permissions for the web server creating the directory, the second is
* for the primary group of the web server and the last number represents
* the permissions for everyone else.
*
* You should use 0660 or 0600 for the permissions as the web server needs
* to manage the files. The group permissions are important if you plan
* to upload files directly via FTP or by other means because then the
* web server needs to be able to read and manage those files. In this
* case use 0660 as permissions, otherwise you can limit them to 0600.
*
* A more detailed description of the meaning of the Unix file permission
* bits can be found in the Wikipedia article about
* {@link https://en.wikipedia.org/wiki/File_system_permissions#Numeric_notation file system permissions}
*
* @param integer Octal Unix permission representation
* @since 2014.09
* @category Developer
*/
$perms = $config->get( 'controller/extjs/coupon/code/standard/fileperms', 0660 );
if( chmod( $dest, $perms ) !== true )
{
$msg = sprintf( 'Could not set permissions "%1$s" for file "%2$s"', $perms, $dest );
throw new \Aimeos\Controller\ExtJS\Exception( $msg );
}
$result = (object) array(
'site' => $params->site,
'items' => array(
(object) array(
'job.label' => 'Coupon code import: ' . $fileinfo['name'],
'job.method' => 'Coupon_Code.importFile',
'job.parameter' => array(
'site' => $params->site,
'parentid' => $params->parentid,
'items' => $dest,
),
'job.status' => 1,
),
),
);
$jobController = \Aimeos\Controller\ExtJS\Admin\Job\Factory::createController( $this->getContext() );
$jobController->saveItems( $result );
return array(
'items' => $dest,
'success' => true,
);
} | [
"public",
"function",
"uploadFile",
"(",
"\\",
"stdClass",
"$",
"params",
")",
"{",
"$",
"this",
"->",
"checkParams",
"(",
"$",
"params",
",",
"array",
"(",
"'site'",
",",
"'parentid'",
")",
")",
";",
"$",
"this",
"->",
"setLocale",
"(",
"$",
"params",... | Uploads a file with coupon codes and meta information.
@param \stdClass $params Object containing the properties | [
"Uploads",
"a",
"file",
"with",
"coupon",
"codes",
"and",
"meta",
"information",
"."
] | train | https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Coupon/Code/Standard.php#L44-L144 |
aimeos/ai-admin-extadm | controller/extjs/src/Controller/ExtJS/Coupon/Code/Standard.php | Standard.importFile | public function importFile( \stdClass $params )
{
$this->checkParams( $params, array( 'site', 'parentid', 'items' ) );
$this->setLocale( $params->site );
/** controller/extjs/coupon/code/standard/container/type
* Container file type storing all coupon code files to import
*
* All coupon code files or content objects must be put into one
* container file so editors don't have to upload one file for each
* coupon code file.
*
* The container file types that are supported by default are:
* * Zip
*
* Extensions implement other container types like spread sheets, XMLs or
* more advanced ways of handling the exported data.
*
* @param string Container file type
* @since 2014.09
* @category Developer
* @category User
* @see controller/extjs/coupon/code/standard/container/format
*/
/** controller/extjs/coupon/code/standard/container/format
* Format of the coupon code files to import
*
* The coupon codes are stored in one or more files or content
* objects. The format of that file or content object can be configured
* with this option but most formats are bound to a specific container
* type.
*
* The formats that are supported by default are:
* * CSV (requires container type "Zip")
*
* Extensions implement other container types like spread sheets, XMLs or
* more advanced ways of handling the exported data.
*
* @param string Content file type
* @since 2014.09
* @category Developer
* @category User
* @see controller/extjs/coupon/code/standard/container/type
* @see controller/extjs/coupon/code/standard/container/options
*/
/** controller/extjs/coupon/code/standard/container/options
* Options changing the expected format of the coupon codes to import
*
* Each content format may support some configuration options to change
* the output for that content type.
*
* The options for the CSV content format are:
* * csv-separator, default ','
* * csv-enclosure, default '"'
* * csv-escape, default '"'
* * csv-lineend, default '\n'
*
* For format options provided by other container types implemented by
* extensions, please have a look into the extension documentation.
*
* @param array Associative list of options with the name as key and its value
* @since 2014.09
* @category Developer
* @category User
* @see controller/extjs/coupon/code/standard/container/format
*/
$config = $this->getContext()->getConfig();
$type = $config->get( 'controller/extjs/coupon/code/standard/container/type', 'Zip' );
$format = $config->get( 'controller/extjs/coupon/code/standard/container/format', 'CSV' );
$options = $config->get( 'controller/extjs/coupon/code/standard/container/options', [] );
$items = ( !is_array( $params->items ) ? array( $params->items ) : $params->items );
foreach( $items as $path )
{
$container = \Aimeos\MW\Container\Factory::getContainer( $path, $type, $format, $options );
foreach( $container as $content ) {
$this->importContent( $content, $params->parentid );
}
unlink( $path );
}
return array(
'success' => true,
);
} | php | public function importFile( \stdClass $params )
{
$this->checkParams( $params, array( 'site', 'parentid', 'items' ) );
$this->setLocale( $params->site );
/** controller/extjs/coupon/code/standard/container/type
* Container file type storing all coupon code files to import
*
* All coupon code files or content objects must be put into one
* container file so editors don't have to upload one file for each
* coupon code file.
*
* The container file types that are supported by default are:
* * Zip
*
* Extensions implement other container types like spread sheets, XMLs or
* more advanced ways of handling the exported data.
*
* @param string Container file type
* @since 2014.09
* @category Developer
* @category User
* @see controller/extjs/coupon/code/standard/container/format
*/
/** controller/extjs/coupon/code/standard/container/format
* Format of the coupon code files to import
*
* The coupon codes are stored in one or more files or content
* objects. The format of that file or content object can be configured
* with this option but most formats are bound to a specific container
* type.
*
* The formats that are supported by default are:
* * CSV (requires container type "Zip")
*
* Extensions implement other container types like spread sheets, XMLs or
* more advanced ways of handling the exported data.
*
* @param string Content file type
* @since 2014.09
* @category Developer
* @category User
* @see controller/extjs/coupon/code/standard/container/type
* @see controller/extjs/coupon/code/standard/container/options
*/
/** controller/extjs/coupon/code/standard/container/options
* Options changing the expected format of the coupon codes to import
*
* Each content format may support some configuration options to change
* the output for that content type.
*
* The options for the CSV content format are:
* * csv-separator, default ','
* * csv-enclosure, default '"'
* * csv-escape, default '"'
* * csv-lineend, default '\n'
*
* For format options provided by other container types implemented by
* extensions, please have a look into the extension documentation.
*
* @param array Associative list of options with the name as key and its value
* @since 2014.09
* @category Developer
* @category User
* @see controller/extjs/coupon/code/standard/container/format
*/
$config = $this->getContext()->getConfig();
$type = $config->get( 'controller/extjs/coupon/code/standard/container/type', 'Zip' );
$format = $config->get( 'controller/extjs/coupon/code/standard/container/format', 'CSV' );
$options = $config->get( 'controller/extjs/coupon/code/standard/container/options', [] );
$items = ( !is_array( $params->items ) ? array( $params->items ) : $params->items );
foreach( $items as $path )
{
$container = \Aimeos\MW\Container\Factory::getContainer( $path, $type, $format, $options );
foreach( $container as $content ) {
$this->importContent( $content, $params->parentid );
}
unlink( $path );
}
return array(
'success' => true,
);
} | [
"public",
"function",
"importFile",
"(",
"\\",
"stdClass",
"$",
"params",
")",
"{",
"$",
"this",
"->",
"checkParams",
"(",
"$",
"params",
",",
"array",
"(",
"'site'",
",",
"'parentid'",
",",
"'items'",
")",
")",
";",
"$",
"this",
"->",
"setLocale",
"("... | Imports a file with coupon codes and optional meta information.
@param \stdClass $params Object containing the properties | [
"Imports",
"a",
"file",
"with",
"coupon",
"codes",
"and",
"optional",
"meta",
"information",
"."
] | train | https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Coupon/Code/Standard.php#L152-L243 |
aimeos/ai-admin-extadm | controller/extjs/src/Controller/ExtJS/Coupon/Code/Standard.php | Standard.getItemBase | protected function getItemBase( \Aimeos\MShop\Coupon\Item\Code\Iface $item, array $row )
{
foreach( $row as $idx => $value ) {
$row[$idx] = trim( $value );
}
$count = ( isset( $row[1] ) && $row[1] != '' ? $row[1] : 1 );
$start = ( isset( $row[2] ) && $row[2] != '' ? $row[2] : null );
$end = ( isset( $row[3] ) && $row[3] != '' ? $row[3] : null );
$item->setId( null );
$item->setCode( $row[0] );
$item->setCount( $count );
$item->setDateStart( $start );
$item->setDateEnd( $end );
return $item;
} | php | protected function getItemBase( \Aimeos\MShop\Coupon\Item\Code\Iface $item, array $row )
{
foreach( $row as $idx => $value ) {
$row[$idx] = trim( $value );
}
$count = ( isset( $row[1] ) && $row[1] != '' ? $row[1] : 1 );
$start = ( isset( $row[2] ) && $row[2] != '' ? $row[2] : null );
$end = ( isset( $row[3] ) && $row[3] != '' ? $row[3] : null );
$item->setId( null );
$item->setCode( $row[0] );
$item->setCount( $count );
$item->setDateStart( $start );
$item->setDateEnd( $end );
return $item;
} | [
"protected",
"function",
"getItemBase",
"(",
"\\",
"Aimeos",
"\\",
"MShop",
"\\",
"Coupon",
"\\",
"Item",
"\\",
"Code",
"\\",
"Iface",
"$",
"item",
",",
"array",
"$",
"row",
")",
"{",
"foreach",
"(",
"$",
"row",
"as",
"$",
"idx",
"=>",
"$",
"value",
... | Returns the item populated by the data from the row.
@param \Aimeos\MShop\Coupon\Item\Code\Iface $item Empty coupon item
@param array $row List of coupon data (code, count, start and end)
@return \Aimeos\MShop\Coupon\Item\Code\Iface Populated coupon item | [
"Returns",
"the",
"item",
"populated",
"by",
"the",
"data",
"from",
"the",
"row",
"."
] | train | https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Coupon/Code/Standard.php#L284-L301 |
aimeos/ai-admin-extadm | controller/extjs/src/Controller/ExtJS/Coupon/Code/Standard.php | Standard.importContent | protected function importContent( \Aimeos\MW\Container\Content\Iface $content, $couponId )
{
$context = $this->getContext();
$manager = \Aimeos\MShop\Factory::createManager( $context, 'coupon/code' );
$item = $manager->createItem();
$item->setParentId( $couponId );
$manager->begin();
try
{
foreach( $content as $row )
{
if( trim( $row[0] ) == '' ) {
continue;
}
$item = $this->getItemBase( $item, $row );
$manager->saveItem( $item, false );
}
$manager->commit();
}
catch( \Exception $e )
{
$manager->rollback();
throw $e;
}
} | php | protected function importContent( \Aimeos\MW\Container\Content\Iface $content, $couponId )
{
$context = $this->getContext();
$manager = \Aimeos\MShop\Factory::createManager( $context, 'coupon/code' );
$item = $manager->createItem();
$item->setParentId( $couponId );
$manager->begin();
try
{
foreach( $content as $row )
{
if( trim( $row[0] ) == '' ) {
continue;
}
$item = $this->getItemBase( $item, $row );
$manager->saveItem( $item, false );
}
$manager->commit();
}
catch( \Exception $e )
{
$manager->rollback();
throw $e;
}
} | [
"protected",
"function",
"importContent",
"(",
"\\",
"Aimeos",
"\\",
"MW",
"\\",
"Container",
"\\",
"Content",
"\\",
"Iface",
"$",
"content",
",",
"$",
"couponId",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"getContext",
"(",
")",
";",
"$",
"man... | Imports the coupon codes and meta data from the content object.
@param \Aimeos\MW\Container\Content\Iface $content Content object with coupon codes and optional meta data
@param string $couponId Unique ID of the coupon configuration for which the codes should be imported
@throws \Exception If a code or its meta data can't be imported | [
"Imports",
"the",
"coupon",
"codes",
"and",
"meta",
"data",
"from",
"the",
"content",
"object",
"."
] | train | https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Coupon/Code/Standard.php#L337-L366 |
aimeos/ai-admin-extadm | controller/extjs/src/Controller/ExtJS/Coupon/Code/Standard.php | Standard.transformValues | protected function transformValues( \stdClass $entry )
{
if( isset( $entry->{'coupon.code.datestart'} ) ) {
$entry->{'coupon.code.datestart'} = str_replace( 'T', ' ', $entry->{'coupon.code.datestart'} );
}
if( isset( $entry->{'coupon.code.dateend'} ) ) {
$entry->{'coupon.code.dateend'} = str_replace( 'T', ' ', $entry->{'coupon.code.dateend'} );
}
return $entry;
} | php | protected function transformValues( \stdClass $entry )
{
if( isset( $entry->{'coupon.code.datestart'} ) ) {
$entry->{'coupon.code.datestart'} = str_replace( 'T', ' ', $entry->{'coupon.code.datestart'} );
}
if( isset( $entry->{'coupon.code.dateend'} ) ) {
$entry->{'coupon.code.dateend'} = str_replace( 'T', ' ', $entry->{'coupon.code.dateend'} );
}
return $entry;
} | [
"protected",
"function",
"transformValues",
"(",
"\\",
"stdClass",
"$",
"entry",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"entry",
"->",
"{",
"'coupon.code.datestart'",
"}",
")",
")",
"{",
"$",
"entry",
"->",
"{",
"'coupon.code.datestart'",
"}",
"=",
"str_r... | Transforms ExtJS values to be suitable for storing them
@param \stdClass $entry Entry object from ExtJS
@return \stdClass Modified object | [
"Transforms",
"ExtJS",
"values",
"to",
"be",
"suitable",
"for",
"storing",
"them"
] | train | https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Coupon/Code/Standard.php#L375-L386 |
accompli/accompli | src/Deployment/Strategy/RemoteInstallStrategy.php | RemoteInstallStrategy.install | public function install($version, $stage = null)
{
$successfulInstall = true;
$hosts = $this->configuration->getHosts();
if ($stage !== null) {
$hosts = $this->configuration->getHostsByStage($stage);
}
foreach ($hosts as $host) {
$exception = null;
$title = new Title($this->logger->getOutput(), sprintf('Installing release "%s" to "%s":', $version, $host->getHostname()));
$title->render();
try {
$this->eventDispatcher->dispatch(AccompliEvents::CREATE_CONNECTION, new HostEvent($host));
$workspaceEvent = new WorkspaceEvent($host);
$this->eventDispatcher->dispatch(AccompliEvents::PREPARE_WORKSPACE, $workspaceEvent);
$workspace = $workspaceEvent->getWorkspace();
if ($workspace instanceof Workspace) {
$prepareReleaseEvent = new PrepareReleaseEvent($workspace, $version);
$this->eventDispatcher->dispatch(AccompliEvents::PREPARE_RELEASE, $prepareReleaseEvent);
$release = $prepareReleaseEvent->getRelease();
if ($release instanceof Release) {
$installReleaseEvent = new InstallReleaseEvent($release);
$this->eventDispatcher->dispatch(AccompliEvents::INSTALL_RELEASE, $installReleaseEvent);
$this->eventDispatcher->dispatch(AccompliEvents::INSTALL_RELEASE_COMPLETE, $installReleaseEvent);
continue;
}
throw new RuntimeException(sprintf('No task configured to install or create release version "%s".', $version));
}
throw new RuntimeException('No task configured to initialize the workspace.');
} catch (Exception $exception) {
}
$successfulInstall = false;
$failedEvent = new FailedEvent($this->eventDispatcher->getLastDispatchedEventName(), $this->eventDispatcher->getLastDispatchedEvent(), $exception);
$this->eventDispatcher->dispatch(AccompliEvents::INSTALL_RELEASE_FAILED, $failedEvent);
}
return $successfulInstall;
} | php | public function install($version, $stage = null)
{
$successfulInstall = true;
$hosts = $this->configuration->getHosts();
if ($stage !== null) {
$hosts = $this->configuration->getHostsByStage($stage);
}
foreach ($hosts as $host) {
$exception = null;
$title = new Title($this->logger->getOutput(), sprintf('Installing release "%s" to "%s":', $version, $host->getHostname()));
$title->render();
try {
$this->eventDispatcher->dispatch(AccompliEvents::CREATE_CONNECTION, new HostEvent($host));
$workspaceEvent = new WorkspaceEvent($host);
$this->eventDispatcher->dispatch(AccompliEvents::PREPARE_WORKSPACE, $workspaceEvent);
$workspace = $workspaceEvent->getWorkspace();
if ($workspace instanceof Workspace) {
$prepareReleaseEvent = new PrepareReleaseEvent($workspace, $version);
$this->eventDispatcher->dispatch(AccompliEvents::PREPARE_RELEASE, $prepareReleaseEvent);
$release = $prepareReleaseEvent->getRelease();
if ($release instanceof Release) {
$installReleaseEvent = new InstallReleaseEvent($release);
$this->eventDispatcher->dispatch(AccompliEvents::INSTALL_RELEASE, $installReleaseEvent);
$this->eventDispatcher->dispatch(AccompliEvents::INSTALL_RELEASE_COMPLETE, $installReleaseEvent);
continue;
}
throw new RuntimeException(sprintf('No task configured to install or create release version "%s".', $version));
}
throw new RuntimeException('No task configured to initialize the workspace.');
} catch (Exception $exception) {
}
$successfulInstall = false;
$failedEvent = new FailedEvent($this->eventDispatcher->getLastDispatchedEventName(), $this->eventDispatcher->getLastDispatchedEvent(), $exception);
$this->eventDispatcher->dispatch(AccompliEvents::INSTALL_RELEASE_FAILED, $failedEvent);
}
return $successfulInstall;
} | [
"public",
"function",
"install",
"(",
"$",
"version",
",",
"$",
"stage",
"=",
"null",
")",
"{",
"$",
"successfulInstall",
"=",
"true",
";",
"$",
"hosts",
"=",
"$",
"this",
"->",
"configuration",
"->",
"getHosts",
"(",
")",
";",
"if",
"(",
"$",
"stage... | {@inheritdoc} | [
"{"
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Strategy/RemoteInstallStrategy.php#L27-L77 |
shpasser/GaeSupport | src/Shpasser/GaeSupport/Queue/GaeQueue.php | GaeQueue.pushRaw | public function pushRaw($payload, $queue = null, array $options = array())
{
if ($this->shouldEncrypt) $payload = $this->crypt->encrypt($payload);
$task = new PushTask($this->url,
array(self::PAYLOAD_REQ_PARAM_NAME => $payload),
$options);
return $task->add($this->getQueue($queue));
} | php | public function pushRaw($payload, $queue = null, array $options = array())
{
if ($this->shouldEncrypt) $payload = $this->crypt->encrypt($payload);
$task = new PushTask($this->url,
array(self::PAYLOAD_REQ_PARAM_NAME => $payload),
$options);
return $task->add($this->getQueue($queue));
} | [
"public",
"function",
"pushRaw",
"(",
"$",
"payload",
",",
"$",
"queue",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"shouldEncrypt",
")",
"$",
"payload",
"=",
"$",
"this",
"->",
"crypt... | Push a raw payload onto the queue.
@param string $payload
@param string $queue
@param array $options
@return mixed | [
"Push",
"a",
"raw",
"payload",
"onto",
"the",
"queue",
"."
] | train | https://github.com/shpasser/GaeSupport/blob/7f37f2bf177a4e8f1cbefdf04f49b51016e85ae3/src/Shpasser/GaeSupport/Queue/GaeQueue.php#L78-L86 |
shpasser/GaeSupport | src/Shpasser/GaeSupport/Queue/GaeQueue.php | GaeQueue.marshal | public function marshal()
{
try
{
$job = $this->marshalPushedJob();
}
catch(\Exception $e)
{
// Ignore for security reasons!
// So if we are being hacked
// the hacker would think it went OK.
return new Response('OK');
}
$this->createPushedGaeJob($job)->fire();
return new Response('OK');
} | php | public function marshal()
{
try
{
$job = $this->marshalPushedJob();
}
catch(\Exception $e)
{
// Ignore for security reasons!
// So if we are being hacked
// the hacker would think it went OK.
return new Response('OK');
}
$this->createPushedGaeJob($job)->fire();
return new Response('OK');
} | [
"public",
"function",
"marshal",
"(",
")",
"{",
"try",
"{",
"$",
"job",
"=",
"$",
"this",
"->",
"marshalPushedJob",
"(",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"// Ignore for security reasons!",
"// So if we are being hacked",
"/... | Marshal a push queue request and fire the job.
@return \Illuminate\Http\Response | [
"Marshal",
"a",
"push",
"queue",
"request",
"and",
"fire",
"the",
"job",
"."
] | train | https://github.com/shpasser/GaeSupport/blob/7f37f2bf177a4e8f1cbefdf04f49b51016e85ae3/src/Shpasser/GaeSupport/Queue/GaeQueue.php#L149-L166 |
arastta/form | Form.php | Form.applyValues | protected function applyValues()
{
foreach ($this->elements as $element) {
$name = $element->getAttribute("name");
if (isset($this->values[$name])) {
$element->setAttribute("value", $this->values[$name]);
} elseif (substr($name, -2) == "[]" && isset($this->values[substr($name, 0, -2)])) {
$element->setAttribute("value", $this->values[substr($name, 0, -2)]);
}
}
} | php | protected function applyValues()
{
foreach ($this->elements as $element) {
$name = $element->getAttribute("name");
if (isset($this->values[$name])) {
$element->setAttribute("value", $this->values[$name]);
} elseif (substr($name, -2) == "[]" && isset($this->values[substr($name, 0, -2)])) {
$element->setAttribute("value", $this->values[substr($name, 0, -2)]);
}
}
} | [
"protected",
"function",
"applyValues",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"elements",
"as",
"$",
"element",
")",
"{",
"$",
"name",
"=",
"$",
"element",
"->",
"getAttribute",
"(",
"\"name\"",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"th... | /*Values that have been set through the setValues method, either manually by the developer
or after validation errors, are applied to elements within this method. | [
"/",
"*",
"Values",
"that",
"have",
"been",
"set",
"through",
"the",
"setValues",
"method",
"either",
"manually",
"by",
"the",
"developer",
"or",
"after",
"validation",
"errors",
"are",
"applied",
"to",
"elements",
"within",
"this",
"method",
"."
] | train | https://github.com/arastta/form/blob/ece7b53973f14399d86243600b821b6180a886a2/Form.php#L99-L109 |
arastta/form | Form.php | Form.setError | public static function setError($id, $errors, $element = "")
{
if (!is_array($errors)) {
$errors = array($errors);
}
if (empty($_SESSION["form"][$id]["errors"][$element])) {
$_SESSION["form"][$id]["errors"][$element] = array();
}
foreach ($errors as $error) {
$_SESSION["form"][$id]["errors"][$element][] = $error;
}
} | php | public static function setError($id, $errors, $element = "")
{
if (!is_array($errors)) {
$errors = array($errors);
}
if (empty($_SESSION["form"][$id]["errors"][$element])) {
$_SESSION["form"][$id]["errors"][$element] = array();
}
foreach ($errors as $error) {
$_SESSION["form"][$id]["errors"][$element][] = $error;
}
} | [
"public",
"static",
"function",
"setError",
"(",
"$",
"id",
",",
"$",
"errors",
",",
"$",
"element",
"=",
"\"\"",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"errors",
")",
")",
"{",
"$",
"errors",
"=",
"array",
"(",
"$",
"errors",
")",
";",
... | /*Valldation errors are saved in the session after the form submission, and will be displayed to the user
when redirected back to the form. | [
"/",
"*",
"Valldation",
"errors",
"are",
"saved",
"in",
"the",
"session",
"after",
"the",
"form",
"submission",
"and",
"will",
"be",
"displayed",
"to",
"the",
"user",
"when",
"redirected",
"back",
"to",
"the",
"form",
"."
] | train | https://github.com/arastta/form/blob/ece7b53973f14399d86243600b821b6180a886a2/Form.php#L491-L504 |
jonnnnyw/craft-awss3assets | AWSS3AssetsPlugin.php | AWSS3AssetsPlugin.onBeforeInstall | public function onBeforeInstall()
{
if (!class_exists('\JonnyW\AWSS3Assets\S3Bucket')) {
$autoload = realpath(dirname(__FILE__)) . '/../../../vendor/autoload.php';
throw new CraftException(
Craft::t('AWSS3AssetsPlugin could not locate an autoload file in {path}.', array('path' => $autoload))
);
}
} | php | public function onBeforeInstall()
{
if (!class_exists('\JonnyW\AWSS3Assets\S3Bucket')) {
$autoload = realpath(dirname(__FILE__)) . '/../../../vendor/autoload.php';
throw new CraftException(
Craft::t('AWSS3AssetsPlugin could not locate an autoload file in {path}.', array('path' => $autoload))
);
}
} | [
"public",
"function",
"onBeforeInstall",
"(",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"'\\JonnyW\\AWSS3Assets\\S3Bucket'",
")",
")",
"{",
"$",
"autoload",
"=",
"realpath",
"(",
"dirname",
"(",
"__FILE__",
")",
")",
".",
"'/../../../vendor/autoload.php'",
... | On before install
@access public
@return void
@throws \Craft\CraftException | [
"On",
"before",
"install"
] | train | https://github.com/jonnnnyw/craft-awss3assets/blob/6bc146a8f3496f148c28d431cd8a9e7dc8199a9d/AWSS3AssetsPlugin.php#L111-L121 |
jonnnnyw/craft-awss3assets | AWSS3AssetsPlugin.php | AWSS3AssetsPlugin.init | public function init()
{
craft()->on('assets.onSaveAsset', function (Event $event) {
$this->copyAsset($event->params['asset']);
});
craft()->on('assets.onReplaceFile', function (Event $event) {
$this->copyAsset($event->params['asset']);
});
craft()->on('assets.onBeforeDeleteAsset', function (Event $event) {
$this->deleteAsset($event->params['asset']);
});
} | php | public function init()
{
craft()->on('assets.onSaveAsset', function (Event $event) {
$this->copyAsset($event->params['asset']);
});
craft()->on('assets.onReplaceFile', function (Event $event) {
$this->copyAsset($event->params['asset']);
});
craft()->on('assets.onBeforeDeleteAsset', function (Event $event) {
$this->deleteAsset($event->params['asset']);
});
} | [
"public",
"function",
"init",
"(",
")",
"{",
"craft",
"(",
")",
"->",
"on",
"(",
"'assets.onSaveAsset'",
",",
"function",
"(",
"Event",
"$",
"event",
")",
"{",
"$",
"this",
"->",
"copyAsset",
"(",
"$",
"event",
"->",
"params",
"[",
"'asset'",
"]",
")... | Initialize plugin.
@access public
@return void | [
"Initialize",
"plugin",
"."
] | train | https://github.com/jonnnnyw/craft-awss3assets/blob/6bc146a8f3496f148c28d431cd8a9e7dc8199a9d/AWSS3AssetsPlugin.php#L129-L142 |
jonnnnyw/craft-awss3assets | AWSS3AssetsPlugin.php | AWSS3AssetsPlugin.getS3Bucket | private function getS3Bucket()
{
$settings = $this->getSettings();
$bucket = S3Bucket::getInstance(
$settings->bucketRegion,
$settings->bucketName,
$settings->awsKey,
$settings->awsSecret
);
return $bucket;
} | php | private function getS3Bucket()
{
$settings = $this->getSettings();
$bucket = S3Bucket::getInstance(
$settings->bucketRegion,
$settings->bucketName,
$settings->awsKey,
$settings->awsSecret
);
return $bucket;
} | [
"private",
"function",
"getS3Bucket",
"(",
")",
"{",
"$",
"settings",
"=",
"$",
"this",
"->",
"getSettings",
"(",
")",
";",
"$",
"bucket",
"=",
"S3Bucket",
"::",
"getInstance",
"(",
"$",
"settings",
"->",
"bucketRegion",
",",
"$",
"settings",
"->",
"buck... | Get S3 Bucket instance.
@access private
@return \JonnyW\AWSS3Assets\S3Bucket | [
"Get",
"S3",
"Bucket",
"instance",
"."
] | train | https://github.com/jonnnnyw/craft-awss3assets/blob/6bc146a8f3496f148c28d431cd8a9e7dc8199a9d/AWSS3AssetsPlugin.php#L175-L187 |
jonnnnyw/craft-awss3assets | AWSS3AssetsPlugin.php | AWSS3AssetsPlugin.copyAsset | public function copyAsset(AssetFileModel $asset)
{
$settings = $this->getSettings();
try {
$this->getS3Bucket()->cp($this->getAssetPath($asset), trim($settings->bucketPath . '/' . $asset->filename, '/'));
} catch (\Exception $e) {
throw new CraftException($e->getMessage());
}
} | php | public function copyAsset(AssetFileModel $asset)
{
$settings = $this->getSettings();
try {
$this->getS3Bucket()->cp($this->getAssetPath($asset), trim($settings->bucketPath . '/' . $asset->filename, '/'));
} catch (\Exception $e) {
throw new CraftException($e->getMessage());
}
} | [
"public",
"function",
"copyAsset",
"(",
"AssetFileModel",
"$",
"asset",
")",
"{",
"$",
"settings",
"=",
"$",
"this",
"->",
"getSettings",
"(",
")",
";",
"try",
"{",
"$",
"this",
"->",
"getS3Bucket",
"(",
")",
"->",
"cp",
"(",
"$",
"this",
"->",
"getA... | Copy asset to bucket.
@access public
@param \Craft\AssetFileModel $asset
@return void
@throws \Craft\Exception | [
"Copy",
"asset",
"to",
"bucket",
"."
] | train | https://github.com/jonnnnyw/craft-awss3assets/blob/6bc146a8f3496f148c28d431cd8a9e7dc8199a9d/AWSS3AssetsPlugin.php#L197-L206 |
jonnnnyw/craft-awss3assets | AWSS3AssetsPlugin.php | AWSS3AssetsPlugin.deleteAsset | public function deleteAsset(AssetFileModel $asset)
{
$settings = $this->getSettings();
try {
$this->getS3Bucket()->rm(trim($settings->bucketPath . '/' . $asset->filename, '/'));
} catch (\Exception $e) {
throw new CraftException($e->getMessage());
}
} | php | public function deleteAsset(AssetFileModel $asset)
{
$settings = $this->getSettings();
try {
$this->getS3Bucket()->rm(trim($settings->bucketPath . '/' . $asset->filename, '/'));
} catch (\Exception $e) {
throw new CraftException($e->getMessage());
}
} | [
"public",
"function",
"deleteAsset",
"(",
"AssetFileModel",
"$",
"asset",
")",
"{",
"$",
"settings",
"=",
"$",
"this",
"->",
"getSettings",
"(",
")",
";",
"try",
"{",
"$",
"this",
"->",
"getS3Bucket",
"(",
")",
"->",
"rm",
"(",
"trim",
"(",
"$",
"set... | Delete asset from bucket.
@access public
@param \Craft\AssetFileModel $asset
@return void
@throws \Craft\Exception | [
"Delete",
"asset",
"from",
"bucket",
"."
] | train | https://github.com/jonnnnyw/craft-awss3assets/blob/6bc146a8f3496f148c28d431cd8a9e7dc8199a9d/AWSS3AssetsPlugin.php#L216-L225 |
jonnnnyw/craft-awss3assets | AWSS3AssetsPlugin.php | AWSS3AssetsPlugin.getAssetPath | private function getAssetPath(AssetFileModel $asset)
{
if ($asset->getSource()->type != 'Local') {
throw new Exception(Craft::t('Could not get asset upload path as source is not "Local"'));
}
$sourcePath = $asset->getSource()->settings['path'];
$folderPath = $asset->getFolder()->path;
return $sourcePath . $folderPath . $asset->filename;
} | php | private function getAssetPath(AssetFileModel $asset)
{
if ($asset->getSource()->type != 'Local') {
throw new Exception(Craft::t('Could not get asset upload path as source is not "Local"'));
}
$sourcePath = $asset->getSource()->settings['path'];
$folderPath = $asset->getFolder()->path;
return $sourcePath . $folderPath . $asset->filename;
} | [
"private",
"function",
"getAssetPath",
"(",
"AssetFileModel",
"$",
"asset",
")",
"{",
"if",
"(",
"$",
"asset",
"->",
"getSource",
"(",
")",
"->",
"type",
"!=",
"'Local'",
")",
"{",
"throw",
"new",
"Exception",
"(",
"Craft",
"::",
"t",
"(",
"'Could not ge... | Get asset path
@access private
@param \Craft\AssetFileModel $asset
@return string
@throws \Exception | [
"Get",
"asset",
"path"
] | train | https://github.com/jonnnnyw/craft-awss3assets/blob/6bc146a8f3496f148c28d431cd8a9e7dc8199a9d/AWSS3AssetsPlugin.php#L235-L245 |
saxulum/saxulum-elasticsearch-querybuilder | src/Node/AbstractNode.php | AbstractNode.setParent | public function setParent(AbstractParentNode $parent)
{
if (null !== $this->parent) {
throw new \InvalidArgumentException('Node already got a parent!');
}
$this->parent = $parent;
} | php | public function setParent(AbstractParentNode $parent)
{
if (null !== $this->parent) {
throw new \InvalidArgumentException('Node already got a parent!');
}
$this->parent = $parent;
} | [
"public",
"function",
"setParent",
"(",
"AbstractParentNode",
"$",
"parent",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"parent",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Node already got a parent!'",
")",
";",
"}",
"$",
... | @param AbstractParentNode $parent
@throws \InvalidArgumentException | [
"@param",
"AbstractParentNode",
"$parent"
] | train | https://github.com/saxulum/saxulum-elasticsearch-querybuilder/blob/2f5a15925f3f3afe6a8efabf1f2c9af42f81d9b1/src/Node/AbstractNode.php#L33-L40 |
makinacorpus/drupal-ucms | ucms_user/src/Form/MyAccountChangePassword.php | MyAccountChangePassword.buildForm | public function buildForm(array $form, FormStateInterface $form_state)
{
$account = $this->entityManager->getStorage('user')->load($this->currentUser()->id());
$form_state->setTemporaryValue('account', $account);
$form['#form_horizontal'] = true;
$form['current_password'] = [
'#type' => 'password',
'#title' => $this->t('Current password'),
'#size' => 20,
'#required' => true,
];
$form['new_password'] = [
'#type' => 'password_confirm',
'#size' => 20,
'#required' => true,
'#description' => $this->t("!count characters at least. Mix letters, digits and special characters for a better password.", ['!count' => UCMS_USER_PWD_MIN_LENGTH]),
// Fix display
'#form_horizontal' => false,
'#nowrapper' => true,
];
$form['actions'] = [
'#type' => 'actions',
'submit' => [
'#type' => 'submit',
'#value' => $this->t('Save'),
],
];
return $form;
} | php | public function buildForm(array $form, FormStateInterface $form_state)
{
$account = $this->entityManager->getStorage('user')->load($this->currentUser()->id());
$form_state->setTemporaryValue('account', $account);
$form['#form_horizontal'] = true;
$form['current_password'] = [
'#type' => 'password',
'#title' => $this->t('Current password'),
'#size' => 20,
'#required' => true,
];
$form['new_password'] = [
'#type' => 'password_confirm',
'#size' => 20,
'#required' => true,
'#description' => $this->t("!count characters at least. Mix letters, digits and special characters for a better password.", ['!count' => UCMS_USER_PWD_MIN_LENGTH]),
// Fix display
'#form_horizontal' => false,
'#nowrapper' => true,
];
$form['actions'] = [
'#type' => 'actions',
'submit' => [
'#type' => 'submit',
'#value' => $this->t('Save'),
],
];
return $form;
} | [
"public",
"function",
"buildForm",
"(",
"array",
"$",
"form",
",",
"FormStateInterface",
"$",
"form_state",
")",
"{",
"$",
"account",
"=",
"$",
"this",
"->",
"entityManager",
"->",
"getStorage",
"(",
"'user'",
")",
"->",
"load",
"(",
"$",
"this",
"->",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_user/src/Form/MyAccountChangePassword.php#L54-L87 |
makinacorpus/drupal-ucms | ucms_user/src/Form/MyAccountChangePassword.php | MyAccountChangePassword.validateForm | public function validateForm(array &$form, FormStateInterface $form_state)
{
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
$account = $form_state->getTemporaryValue('account');
$password = $form_state->getValue('current_password');
if (!user_check_password($password, $account)) {
$form_state->setErrorByName('current_password', $this->t("Your current password is incorrect."));
}
$new_password = $form_state->getValue('new_password');
if (strlen($new_password) < UCMS_USER_PWD_MIN_LENGTH) {
$form_state->setErrorByName('new_password', $this->t("Your new password must contain !count characters at least.", ['!count' => UCMS_USER_PWD_MIN_LENGTH]));
}
} | php | public function validateForm(array &$form, FormStateInterface $form_state)
{
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
$account = $form_state->getTemporaryValue('account');
$password = $form_state->getValue('current_password');
if (!user_check_password($password, $account)) {
$form_state->setErrorByName('current_password', $this->t("Your current password is incorrect."));
}
$new_password = $form_state->getValue('new_password');
if (strlen($new_password) < UCMS_USER_PWD_MIN_LENGTH) {
$form_state->setErrorByName('new_password', $this->t("Your new password must contain !count characters at least.", ['!count' => UCMS_USER_PWD_MIN_LENGTH]));
}
} | [
"public",
"function",
"validateForm",
"(",
"array",
"&",
"$",
"form",
",",
"FormStateInterface",
"$",
"form_state",
")",
"{",
"require_once",
"DRUPAL_ROOT",
".",
"'/'",
".",
"variable_get",
"(",
"'password_inc'",
",",
"'includes/password.inc'",
")",
";",
"$",
"a... | {@inheritdoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_user/src/Form/MyAccountChangePassword.php#L93-L109 |
makinacorpus/drupal-ucms | ucms_user/src/Form/MyAccountChangePassword.php | MyAccountChangePassword.submitForm | public function submitForm(array &$form, FormStateInterface $form_state)
{
$new_password = $form_state->getValue('new_password');
$account = $form_state->getTemporaryValue('account');
$account->pass = user_hash_password($new_password);
$this->entityManager->getStorage('user')->save($account);
drupal_set_message($this->t("Your new password has been saved."));
$form_state->setRedirect('admin/dashboard');
} | php | public function submitForm(array &$form, FormStateInterface $form_state)
{
$new_password = $form_state->getValue('new_password');
$account = $form_state->getTemporaryValue('account');
$account->pass = user_hash_password($new_password);
$this->entityManager->getStorage('user')->save($account);
drupal_set_message($this->t("Your new password has been saved."));
$form_state->setRedirect('admin/dashboard');
} | [
"public",
"function",
"submitForm",
"(",
"array",
"&",
"$",
"form",
",",
"FormStateInterface",
"$",
"form_state",
")",
"{",
"$",
"new_password",
"=",
"$",
"form_state",
"->",
"getValue",
"(",
"'new_password'",
")",
";",
"$",
"account",
"=",
"$",
"form_state"... | {@inheritdoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_user/src/Form/MyAccountChangePassword.php#L115-L125 |
shopgate/cart-integration-sdk | src/helper/logging/stack_trace/GeneratorDefault.php | Shopgate_Helper_Logging_Stack_Trace_GeneratorDefault.generate | public function generate($exception, $maxDepth = 10)
{
$formattedHeader = $this->generateFormattedHeader($exception);
$formattedTrace = $this->generateFormattedTrace($exception->getTrace());
$messages = array($formattedHeader . "\n" . $formattedTrace);
$depthCounter = 1;
$previousException = $this->getPreviousException($exception);
while ($previousException !== null && $depthCounter < $maxDepth) {
$messages[] =
$this->generateFormattedHeader($previousException, false) . "\n" .
$this->generateFormattedTrace($previousException->getTrace());
$previousException = $this->getPreviousException($previousException);
$depthCounter++;
}
return implode("\n\n", $messages);
} | php | public function generate($exception, $maxDepth = 10)
{
$formattedHeader = $this->generateFormattedHeader($exception);
$formattedTrace = $this->generateFormattedTrace($exception->getTrace());
$messages = array($formattedHeader . "\n" . $formattedTrace);
$depthCounter = 1;
$previousException = $this->getPreviousException($exception);
while ($previousException !== null && $depthCounter < $maxDepth) {
$messages[] =
$this->generateFormattedHeader($previousException, false) . "\n" .
$this->generateFormattedTrace($previousException->getTrace());
$previousException = $this->getPreviousException($previousException);
$depthCounter++;
}
return implode("\n\n", $messages);
} | [
"public",
"function",
"generate",
"(",
"$",
"exception",
",",
"$",
"maxDepth",
"=",
"10",
")",
"{",
"$",
"formattedHeader",
"=",
"$",
"this",
"->",
"generateFormattedHeader",
"(",
"$",
"exception",
")",
";",
"$",
"formattedTrace",
"=",
"$",
"this",
"->",
... | @param Exception|Throwable $exception
@param int $maxDepth
@return string | [
"@param",
"Exception|Throwable",
"$exception",
"@param",
"int",
"$maxDepth"
] | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/helper/logging/stack_trace/GeneratorDefault.php#L59-L78 |
shopgate/cart-integration-sdk | src/helper/logging/stack_trace/GeneratorDefault.php | Shopgate_Helper_Logging_Stack_Trace_GeneratorDefault.getPreviousException | private function getPreviousException($exception)
{
$previousException = null;
if (method_exists($exception, 'getPrevious')) {
$previousException = $exception->getPrevious();
}
return $previousException;
} | php | private function getPreviousException($exception)
{
$previousException = null;
if (method_exists($exception, 'getPrevious')) {
$previousException = $exception->getPrevious();
}
return $previousException;
} | [
"private",
"function",
"getPreviousException",
"(",
"$",
"exception",
")",
"{",
"$",
"previousException",
"=",
"null",
";",
"if",
"(",
"method_exists",
"(",
"$",
"exception",
",",
"'getPrevious'",
")",
")",
"{",
"$",
"previousException",
"=",
"$",
"exception",... | Returns previous exception.
Some customers are still running PHP below version 5.3, but method Exception::getPrevious is available since
version 5.3. Therefor we check if method is existent, if not method returns null
@param Exception|Throwable $exception
@return Exception|null | [
"Returns",
"previous",
"exception",
".",
"Some",
"customers",
"are",
"still",
"running",
"PHP",
"below",
"version",
"5",
".",
"3",
"but",
"method",
"Exception",
"::",
"getPrevious",
"is",
"available",
"since",
"version",
"5",
".",
"3",
".",
"Therefor",
"we",... | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/helper/logging/stack_trace/GeneratorDefault.php#L89-L98 |
shopgate/cart-integration-sdk | src/helper/logging/stack_trace/GeneratorDefault.php | Shopgate_Helper_Logging_Stack_Trace_GeneratorDefault.generateFormattedTrace | private function generateFormattedTrace(array $traces)
{
$formattedTraceLines = array();
$traces = array_reverse($traces);
foreach ($traces as $trace) {
if (!isset($trace['class'])) {
$trace['class'] = '';
$trace['type'] = '';
}
if (!isset($trace['file'])) {
$trace['file'] = 'unknown file';
$trace['line'] = 'unknown line';
}
if (!isset($trace['function'])) {
$trace['function'] = 'unknown function';
}
if (!isset($trace['args']) || !is_array($trace['args'])) {
$trace['args'] = array();
}
$arguments = $this->namedParameterProvider->get($trace['class'], $trace['function'], $trace['args']);
$arguments = $this->obfuscator->cleanParamsForLog($arguments);
array_walk($arguments, array($this, 'flatten'));
$arguments = implode(', ', $arguments);
$formattedTraceLines[] =
"at {$trace['class']}{$trace['type']}{$trace['function']}({$arguments}) " .
"called in {$trace['file']}:{$trace['line']}";
}
return implode("\n", $formattedTraceLines);
} | php | private function generateFormattedTrace(array $traces)
{
$formattedTraceLines = array();
$traces = array_reverse($traces);
foreach ($traces as $trace) {
if (!isset($trace['class'])) {
$trace['class'] = '';
$trace['type'] = '';
}
if (!isset($trace['file'])) {
$trace['file'] = 'unknown file';
$trace['line'] = 'unknown line';
}
if (!isset($trace['function'])) {
$trace['function'] = 'unknown function';
}
if (!isset($trace['args']) || !is_array($trace['args'])) {
$trace['args'] = array();
}
$arguments = $this->namedParameterProvider->get($trace['class'], $trace['function'], $trace['args']);
$arguments = $this->obfuscator->cleanParamsForLog($arguments);
array_walk($arguments, array($this, 'flatten'));
$arguments = implode(', ', $arguments);
$formattedTraceLines[] =
"at {$trace['class']}{$trace['type']}{$trace['function']}({$arguments}) " .
"called in {$trace['file']}:{$trace['line']}";
}
return implode("\n", $formattedTraceLines);
} | [
"private",
"function",
"generateFormattedTrace",
"(",
"array",
"$",
"traces",
")",
"{",
"$",
"formattedTraceLines",
"=",
"array",
"(",
")",
";",
"$",
"traces",
"=",
"array_reverse",
"(",
"$",
"traces",
")",
";",
"foreach",
"(",
"$",
"traces",
"as",
"$",
... | @param array $traces
@return string | [
"@param",
"array",
"$traces"
] | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/helper/logging/stack_trace/GeneratorDefault.php#L122-L157 |
shopgate/cart-integration-sdk | src/helper/logging/stack_trace/GeneratorDefault.php | Shopgate_Helper_Logging_Stack_Trace_GeneratorDefault.flatten | private function flatten(
&$value,
/** @noinspection PhpUnusedParameterInspection */
$key
) {
if (is_object($value)) {
$value = 'Object';
}
if (is_array($value)) {
$value = 'Array';
}
if (is_bool($value)) {
$value = $value
? 'true'
: 'false';
}
} | php | private function flatten(
&$value,
/** @noinspection PhpUnusedParameterInspection */
$key
) {
if (is_object($value)) {
$value = 'Object';
}
if (is_array($value)) {
$value = 'Array';
}
if (is_bool($value)) {
$value = $value
? 'true'
: 'false';
}
} | [
"private",
"function",
"flatten",
"(",
"&",
"$",
"value",
",",
"/** @noinspection PhpUnusedParameterInspection */",
"$",
"key",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"value",
")",
")",
"{",
"$",
"value",
"=",
"'Object'",
";",
"}",
"if",
"(",
"is_arra... | Function to be passed to array_walk(); will remove sub-arrays or objects.
@param mixed $key
@param mixed $value
@post $value contains 'Object' if it was an object before.
@post $value contains 'Array' if it was an array before.
@pist $value contains 'true' / 'false' if it was boolean true / false before.
@post $value is left untouched if it was any other simple type before. | [
"Function",
"to",
"be",
"passed",
"to",
"array_walk",
"()",
";",
"will",
"remove",
"sub",
"-",
"arrays",
"or",
"objects",
"."
] | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/helper/logging/stack_trace/GeneratorDefault.php#L170-L188 |
despark/ignicms | src/Http/Middleware/RoleMiddleware.php | RoleMiddleware.handle | public function handle($request, Closure $next, $role = null, $permission = null)
{
if (Auth::guest()) {
return redirect('/admin/login');
}
if ($role && ! $request->user()->hasRole($role)) {
throw new NotFoundHttpException;
}
if ($permission && ! $request->user()->can($permission)) {
throw new NotFoundHttpException;
}
return $next($request);
} | php | public function handle($request, Closure $next, $role = null, $permission = null)
{
if (Auth::guest()) {
return redirect('/admin/login');
}
if ($role && ! $request->user()->hasRole($role)) {
throw new NotFoundHttpException;
}
if ($permission && ! $request->user()->can($permission)) {
throw new NotFoundHttpException;
}
return $next($request);
} | [
"public",
"function",
"handle",
"(",
"$",
"request",
",",
"Closure",
"$",
"next",
",",
"$",
"role",
"=",
"null",
",",
"$",
"permission",
"=",
"null",
")",
"{",
"if",
"(",
"Auth",
"::",
"guest",
"(",
")",
")",
"{",
"return",
"redirect",
"(",
"'/admi... | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@param $role
@param $permission
@return mixed | [
"Handle",
"an",
"incoming",
"request",
"."
] | train | https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/src/Http/Middleware/RoleMiddleware.php#L20-L35 |
noherczeg/breadcrumb | src/Noherczeg/Breadcrumb/BreadcrumbServiceProvider.php | BreadcrumbServiceProvider.register | public function register()
{
$this->app['breadcrumb'] = $this->app->share(function($app)
{
$options = $app['config']['noherczeg::breadcrumb'];
return new Breadcrumb($app['request']->root(), $options);
});
} | php | public function register()
{
$this->app['breadcrumb'] = $this->app->share(function($app)
{
$options = $app['config']['noherczeg::breadcrumb'];
return new Breadcrumb($app['request']->root(), $options);
});
} | [
"public",
"function",
"register",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"[",
"'breadcrumb'",
"]",
"=",
"$",
"this",
"->",
"app",
"->",
"share",
"(",
"function",
"(",
"$",
"app",
")",
"{",
"$",
"options",
"=",
"$",
"app",
"[",
"'config'",
"]",
... | Register the service provider.
@return void | [
"Register",
"the",
"service",
"provider",
"."
] | train | https://github.com/noherczeg/breadcrumb/blob/d46ad3b58fbc6fa118ccad57e42e95214a0416c8/src/Noherczeg/Breadcrumb/BreadcrumbServiceProvider.php#L31-L39 |
accompli/accompli | src/Task/YamlConfigurationTask.php | YamlConfigurationTask.onInstallReleaseCreateOrUpdateConfiguration | public function onInstallReleaseCreateOrUpdateConfiguration(InstallReleaseEvent $event, $eventName, EventDispatcherInterface $eventDispatcher)
{
$release = $event->getRelease();
$this->gatherEnvironmentVariables($release);
$connection = $this->ensureConnection($release->getWorkspace()->getHost());
$configurationFile = $release->getPath().$this->configurationFile;
$configurationDistributionFile = $configurationFile.'.dist';
$context = array('action' => 'Creating', 'configurationFile' => $configurationFile, 'event.task.action' => TaskInterface::ACTION_IN_PROGRESS);
if ($connection->isFile($configurationFile)) {
$context['action'] = 'Updating';
}
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::NOTICE, '{action} configuration file "{configurationFile}"...', $eventName, $this, $context));
$yamlConfiguration = $this->getYamlConfiguration($connection, $release->getWorkspace()->getHost()->getStage(), $configurationFile, $configurationDistributionFile);
if ($connection->putContents($configurationFile, $yamlConfiguration)) {
$context['event.task.action'] = TaskInterface::ACTION_COMPLETED;
if ($context['action'] === 'Creating') {
$context['action'] = 'Created';
} else {
$context['action'] = 'Updated';
}
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::NOTICE, '{action} configuration file "{configurationFile}".', $eventName, $this, $context));
} else {
$context['event.task.action'] = TaskInterface::ACTION_FAILED;
$context['action'] = strtolower($context['action']);
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::WARNING, 'Failed {action} configuration file "{configurationFile}".', $eventName, $this, $context));
}
} | php | public function onInstallReleaseCreateOrUpdateConfiguration(InstallReleaseEvent $event, $eventName, EventDispatcherInterface $eventDispatcher)
{
$release = $event->getRelease();
$this->gatherEnvironmentVariables($release);
$connection = $this->ensureConnection($release->getWorkspace()->getHost());
$configurationFile = $release->getPath().$this->configurationFile;
$configurationDistributionFile = $configurationFile.'.dist';
$context = array('action' => 'Creating', 'configurationFile' => $configurationFile, 'event.task.action' => TaskInterface::ACTION_IN_PROGRESS);
if ($connection->isFile($configurationFile)) {
$context['action'] = 'Updating';
}
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::NOTICE, '{action} configuration file "{configurationFile}"...', $eventName, $this, $context));
$yamlConfiguration = $this->getYamlConfiguration($connection, $release->getWorkspace()->getHost()->getStage(), $configurationFile, $configurationDistributionFile);
if ($connection->putContents($configurationFile, $yamlConfiguration)) {
$context['event.task.action'] = TaskInterface::ACTION_COMPLETED;
if ($context['action'] === 'Creating') {
$context['action'] = 'Created';
} else {
$context['action'] = 'Updated';
}
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::NOTICE, '{action} configuration file "{configurationFile}".', $eventName, $this, $context));
} else {
$context['event.task.action'] = TaskInterface::ACTION_FAILED;
$context['action'] = strtolower($context['action']);
$eventDispatcher->dispatch(AccompliEvents::LOG, new LogEvent(LogLevel::WARNING, 'Failed {action} configuration file "{configurationFile}".', $eventName, $this, $context));
}
} | [
"public",
"function",
"onInstallReleaseCreateOrUpdateConfiguration",
"(",
"InstallReleaseEvent",
"$",
"event",
",",
"$",
"eventName",
",",
"EventDispatcherInterface",
"$",
"eventDispatcher",
")",
"{",
"$",
"release",
"=",
"$",
"event",
"->",
"getRelease",
"(",
")",
... | Saves a YAML configuration file to a path within the release.
@param InstallReleaseEvent $event
@param string $eventName
@param EventDispatcherInterface $eventDispatcher | [
"Saves",
"a",
"YAML",
"configuration",
"file",
"to",
"a",
"path",
"within",
"the",
"release",
"."
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Task/YamlConfigurationTask.php#L91-L124 |
accompli/accompli | src/Task/YamlConfigurationTask.php | YamlConfigurationTask.gatherEnvironmentVariables | private function gatherEnvironmentVariables(Release $release)
{
$this->environmentVariables = array(
'%stage%' => $release->getWorkspace()->getHost()->getStage(),
'%version%' => $release->getVersion(),
);
} | php | private function gatherEnvironmentVariables(Release $release)
{
$this->environmentVariables = array(
'%stage%' => $release->getWorkspace()->getHost()->getStage(),
'%version%' => $release->getVersion(),
);
} | [
"private",
"function",
"gatherEnvironmentVariables",
"(",
"Release",
"$",
"release",
")",
"{",
"$",
"this",
"->",
"environmentVariables",
"=",
"array",
"(",
"'%stage%'",
"=>",
"$",
"release",
"->",
"getWorkspace",
"(",
")",
"->",
"getHost",
"(",
")",
"->",
"... | Gathers environment variables to use in the YAML configuration.
@param Release $release | [
"Gathers",
"environment",
"variables",
"to",
"use",
"in",
"the",
"YAML",
"configuration",
"."
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Task/YamlConfigurationTask.php#L131-L137 |
accompli/accompli | src/Task/YamlConfigurationTask.php | YamlConfigurationTask.getYamlConfiguration | private function getYamlConfiguration(ConnectionAdapterInterface $connection, $stage, $configurationFile, $configurationDistributionFile)
{
$configuration = array();
if ($connection->isFile($configurationFile)) {
$configuration = Yaml::parse($connection->getContents($configurationFile));
}
$distributionConfiguration = array();
if ($connection->isFile($configurationDistributionFile)) {
$distributionConfiguration = Yaml::parse($connection->getContents($configurationDistributionFile));
}
$stageSpecificConfiguration = array();
if (isset($this->stageSpecificConfigurations[$stage])) {
$stageSpecificConfiguration = $this->stageSpecificConfigurations[$stage];
}
$configuration = array_replace_recursive($distributionConfiguration, $configuration, $this->configuration, $stageSpecificConfiguration);
foreach ($this->generateValueForParameters as $generateValueForParameter) {
$this->findKeyAndGenerateValue($configuration, explode('.', $generateValueForParameter));
}
$configuration = $this->addEnvironmentVariables($configuration);
return Yaml::dump($configuration);
} | php | private function getYamlConfiguration(ConnectionAdapterInterface $connection, $stage, $configurationFile, $configurationDistributionFile)
{
$configuration = array();
if ($connection->isFile($configurationFile)) {
$configuration = Yaml::parse($connection->getContents($configurationFile));
}
$distributionConfiguration = array();
if ($connection->isFile($configurationDistributionFile)) {
$distributionConfiguration = Yaml::parse($connection->getContents($configurationDistributionFile));
}
$stageSpecificConfiguration = array();
if (isset($this->stageSpecificConfigurations[$stage])) {
$stageSpecificConfiguration = $this->stageSpecificConfigurations[$stage];
}
$configuration = array_replace_recursive($distributionConfiguration, $configuration, $this->configuration, $stageSpecificConfiguration);
foreach ($this->generateValueForParameters as $generateValueForParameter) {
$this->findKeyAndGenerateValue($configuration, explode('.', $generateValueForParameter));
}
$configuration = $this->addEnvironmentVariables($configuration);
return Yaml::dump($configuration);
} | [
"private",
"function",
"getYamlConfiguration",
"(",
"ConnectionAdapterInterface",
"$",
"connection",
",",
"$",
"stage",
",",
"$",
"configurationFile",
",",
"$",
"configurationDistributionFile",
")",
"{",
"$",
"configuration",
"=",
"array",
"(",
")",
";",
"if",
"("... | Returns the generated YAML content based on the existing configuration file, distribution configuration file and the configuration configured with this task.
@param ConnectionAdapterInterface $connection
@param string $stage
@param string $configurationFile
@param string $configurationDistributionFile
@return string | [
"Returns",
"the",
"generated",
"YAML",
"content",
"based",
"on",
"the",
"existing",
"configuration",
"file",
"distribution",
"configuration",
"file",
"and",
"the",
"configuration",
"configured",
"with",
"this",
"task",
"."
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Task/YamlConfigurationTask.php#L149-L173 |
accompli/accompli | src/Task/YamlConfigurationTask.php | YamlConfigurationTask.findKeyAndGenerateValue | private function findKeyAndGenerateValue(array &$configuration, array $parameterParts)
{
foreach ($configuration as $key => $value) {
if ($key === current($parameterParts)) {
if (is_array($value) && count($parameterParts) > 1) {
array_shift($parameterParts);
$this->findKeyAndGenerateValue($value, $parameterParts);
$configuration[$key] = $value;
} elseif (is_scalar($value)) {
$configuration[$key] = sha1(uniqid());
}
}
}
} | php | private function findKeyAndGenerateValue(array &$configuration, array $parameterParts)
{
foreach ($configuration as $key => $value) {
if ($key === current($parameterParts)) {
if (is_array($value) && count($parameterParts) > 1) {
array_shift($parameterParts);
$this->findKeyAndGenerateValue($value, $parameterParts);
$configuration[$key] = $value;
} elseif (is_scalar($value)) {
$configuration[$key] = sha1(uniqid());
}
}
}
} | [
"private",
"function",
"findKeyAndGenerateValue",
"(",
"array",
"&",
"$",
"configuration",
",",
"array",
"$",
"parameterParts",
")",
"{",
"foreach",
"(",
"$",
"configuration",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"key",
"===",
... | Traverses through the configuration array to find the configuration key and generates a unique sha1 hash.
@param array $configuration
@param array $parameterParts | [
"Traverses",
"through",
"the",
"configuration",
"array",
"to",
"find",
"the",
"configuration",
"key",
"and",
"generates",
"a",
"unique",
"sha1",
"hash",
"."
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Task/YamlConfigurationTask.php#L181-L195 |
accompli/accompli | src/Task/YamlConfigurationTask.php | YamlConfigurationTask.addEnvironmentVariables | private function addEnvironmentVariables($value)
{
if (is_array($value)) {
$value = array_map(array($this, __METHOD__), $value);
} elseif (is_string($value)) {
$value = strtr($value, $this->environmentVariables);
}
return $value;
} | php | private function addEnvironmentVariables($value)
{
if (is_array($value)) {
$value = array_map(array($this, __METHOD__), $value);
} elseif (is_string($value)) {
$value = strtr($value, $this->environmentVariables);
}
return $value;
} | [
"private",
"function",
"addEnvironmentVariables",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"$",
"value",
"=",
"array_map",
"(",
"array",
"(",
"$",
"this",
",",
"__METHOD__",
")",
",",
"$",
"value",
")",
";... | Adds the environment variables.
@param mixed $value
@return mixed | [
"Adds",
"the",
"environment",
"variables",
"."
] | train | https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Task/YamlConfigurationTask.php#L204-L213 |
shopgate/cart-integration-sdk | src/helper/logging/stack_trace/NamedParameterProviderReflection.php | Shopgate_Helper_Logging_Stack_Trace_NamedParameterProviderReflection.getNamedArguments | private function getNamedArguments($className, $functionName, array $arguments)
{
$fullFunctionName = $this->getFullFunctionName($className, $functionName);
if (empty($this->functionArgumentsCache[$fullFunctionName])) {
$this->functionArgumentsCache[$fullFunctionName] =
$this->buildReflectionFunction($className, $functionName)->getParameters();
}
$i = 0;
$namedArguments = array();
foreach ($this->functionArgumentsCache[$fullFunctionName] as $parameter) {
/** @var ReflectionParameter $parameter */
try {
$defaultValue = '[defaultValue:' . $this->sanitize($parameter->getDefaultValue()) . ']';
} catch (ReflectionException $e) {
$defaultValue = '';
}
$namedArguments[$parameter->getName()] = isset($arguments[$i])
? $arguments[$i]
: $defaultValue;
$i++;
}
return $namedArguments;
} | php | private function getNamedArguments($className, $functionName, array $arguments)
{
$fullFunctionName = $this->getFullFunctionName($className, $functionName);
if (empty($this->functionArgumentsCache[$fullFunctionName])) {
$this->functionArgumentsCache[$fullFunctionName] =
$this->buildReflectionFunction($className, $functionName)->getParameters();
}
$i = 0;
$namedArguments = array();
foreach ($this->functionArgumentsCache[$fullFunctionName] as $parameter) {
/** @var ReflectionParameter $parameter */
try {
$defaultValue = '[defaultValue:' . $this->sanitize($parameter->getDefaultValue()) . ']';
} catch (ReflectionException $e) {
$defaultValue = '';
}
$namedArguments[$parameter->getName()] = isset($arguments[$i])
? $arguments[$i]
: $defaultValue;
$i++;
}
return $namedArguments;
} | [
"private",
"function",
"getNamedArguments",
"(",
"$",
"className",
",",
"$",
"functionName",
",",
"array",
"$",
"arguments",
")",
"{",
"$",
"fullFunctionName",
"=",
"$",
"this",
"->",
"getFullFunctionName",
"(",
"$",
"className",
",",
"$",
"functionName",
")",... | @param string $className
@param string $functionName
@param mixed[] $arguments The list of arguments.
@return array [string, mixed] An array of the arguments with named indices according to function parameter names. | [
"@param",
"string",
"$className",
"@param",
"string",
"$functionName",
"@param",
"mixed",
"[]",
"$arguments",
"The",
"list",
"of",
"arguments",
"."
] | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/helper/logging/stack_trace/NamedParameterProviderReflection.php#L66-L92 |
shopgate/cart-integration-sdk | src/helper/logging/stack_trace/NamedParameterProviderReflection.php | Shopgate_Helper_Logging_Stack_Trace_NamedParameterProviderReflection.buildReflectionFunction | private function buildReflectionFunction($className, $functionName)
{
return (empty($className))
? new ReflectionFunction($this->getFullFunctionName($className, $functionName))
: new ReflectionMethod($className, $functionName);
} | php | private function buildReflectionFunction($className, $functionName)
{
return (empty($className))
? new ReflectionFunction($this->getFullFunctionName($className, $functionName))
: new ReflectionMethod($className, $functionName);
} | [
"private",
"function",
"buildReflectionFunction",
"(",
"$",
"className",
",",
"$",
"functionName",
")",
"{",
"return",
"(",
"empty",
"(",
"$",
"className",
")",
")",
"?",
"new",
"ReflectionFunction",
"(",
"$",
"this",
"->",
"getFullFunctionName",
"(",
"$",
"... | @param string $className
@param string $functionName
@return ReflectionFunctionAbstract | [
"@param",
"string",
"$className",
"@param",
"string",
"$functionName"
] | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/helper/logging/stack_trace/NamedParameterProviderReflection.php#L113-L118 |
shopgate/cart-integration-sdk | src/helper/logging/stack_trace/NamedParameterProviderReflection.php | Shopgate_Helper_Logging_Stack_Trace_NamedParameterProviderReflection.exists | private function exists($className, $functionName)
{
return
function_exists($this->getFullFunctionName($className, $functionName))
|| method_exists($className, $functionName);
} | php | private function exists($className, $functionName)
{
return
function_exists($this->getFullFunctionName($className, $functionName))
|| method_exists($className, $functionName);
} | [
"private",
"function",
"exists",
"(",
"$",
"className",
",",
"$",
"functionName",
")",
"{",
"return",
"function_exists",
"(",
"$",
"this",
"->",
"getFullFunctionName",
"(",
"$",
"className",
",",
"$",
"functionName",
")",
")",
"||",
"method_exists",
"(",
"$"... | @param string $className
@param string $functionName
@return bool | [
"@param",
"string",
"$className",
"@param",
"string",
"$functionName"
] | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/helper/logging/stack_trace/NamedParameterProviderReflection.php#L126-L131 |
shopgate/cart-integration-sdk | src/helper/logging/stack_trace/NamedParameterProviderReflection.php | Shopgate_Helper_Logging_Stack_Trace_NamedParameterProviderReflection.sanitize | private function sanitize($value)
{
if ($value === null) {
$value = 'null';
}
if (is_array($value)) {
$value = 'array';
}
if (is_bool($value)) {
$value = $value
? 'true'
: 'false';
}
return $value;
} | php | private function sanitize($value)
{
if ($value === null) {
$value = 'null';
}
if (is_array($value)) {
$value = 'array';
}
if (is_bool($value)) {
$value = $value
? 'true'
: 'false';
}
return $value;
} | [
"private",
"function",
"sanitize",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"$",
"value",
"=",
"'null'",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"$",
"value",
"=",
"'array'",
";",
... | @param mixed $value
@return string | [
"@param",
"mixed",
"$value"
] | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/helper/logging/stack_trace/NamedParameterProviderReflection.php#L138-L155 |
qloog/yaf-library | src/Validators/UrlValidator.php | UrlValidator.validator | public function validator($field, array $data)
{
$value = isset($data[$field]) ? $data[$field] : null;
if ($this->validatorValue($value)) {
return true;
}
return $this->message('{fieldName}不是链接!', [
'{fieldName}' => $this->getName($field),
]);
} | php | public function validator($field, array $data)
{
$value = isset($data[$field]) ? $data[$field] : null;
if ($this->validatorValue($value)) {
return true;
}
return $this->message('{fieldName}不是链接!', [
'{fieldName}' => $this->getName($field),
]);
} | [
"public",
"function",
"validator",
"(",
"$",
"field",
",",
"array",
"$",
"data",
")",
"{",
"$",
"value",
"=",
"isset",
"(",
"$",
"data",
"[",
"$",
"field",
"]",
")",
"?",
"$",
"data",
"[",
"$",
"field",
"]",
":",
"null",
";",
"if",
"(",
"$",
... | 验证
@param string $field
@param array $data
@return bool|string | [
"验证"
] | train | https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Validators/UrlValidator.php#L39-L49 |
qloog/yaf-library | src/Validators/UrlValidator.php | UrlValidator.validatorValue | protected function validatorValue($value)
{
if (!$value) {
return $this->allowEmpty;
}
$pattern = str_replace('{schemes}', '(' . implode('|', $this->validSchemes) . ')', $this->pattern);
if (preg_match($pattern, $value)) {
return true;
}
return false;
} | php | protected function validatorValue($value)
{
if (!$value) {
return $this->allowEmpty;
}
$pattern = str_replace('{schemes}', '(' . implode('|', $this->validSchemes) . ')', $this->pattern);
if (preg_match($pattern, $value)) {
return true;
}
return false;
} | [
"protected",
"function",
"validatorValue",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"$",
"value",
")",
"{",
"return",
"$",
"this",
"->",
"allowEmpty",
";",
"}",
"$",
"pattern",
"=",
"str_replace",
"(",
"'{schemes}'",
",",
"'('",
".",
"implode",
"("... | 验证值
@param $value
@return bool|string | [
"验证值"
] | train | https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Validators/UrlValidator.php#L57-L69 |
danmichaelo/php-coma | src/Danmichaelo/Coma/sRGB.php | sRGB.toXyz | public function toXyz()
{
// Reverse transform from sRGB to XYZ:
$color = array(
$this->pivot($this->r / 255),
$this->pivot($this->g / 255),
$this->pivot($this->b / 255),
);
// Observer = 2°, Illuminant = D65
return new XYZ(
$color[0] * 0.412453 + $color[1] * 0.357580 + $color[2] * 0.180423,
$color[0] * 0.212671 + $color[1] * 0.715160 + $color[2] * 0.072169,
$color[0] * 0.019334 + $color[1] * 0.119193 + $color[2] * 0.950227
);
} | php | public function toXyz()
{
// Reverse transform from sRGB to XYZ:
$color = array(
$this->pivot($this->r / 255),
$this->pivot($this->g / 255),
$this->pivot($this->b / 255),
);
// Observer = 2°, Illuminant = D65
return new XYZ(
$color[0] * 0.412453 + $color[1] * 0.357580 + $color[2] * 0.180423,
$color[0] * 0.212671 + $color[1] * 0.715160 + $color[2] * 0.072169,
$color[0] * 0.019334 + $color[1] * 0.119193 + $color[2] * 0.950227
);
} | [
"public",
"function",
"toXyz",
"(",
")",
"{",
"// Reverse transform from sRGB to XYZ:",
"$",
"color",
"=",
"array",
"(",
"$",
"this",
"->",
"pivot",
"(",
"$",
"this",
"->",
"r",
"/",
"255",
")",
",",
"$",
"this",
"->",
"pivot",
"(",
"$",
"this",
"->",
... | The reverse transformation (sRGB to CIE XYZ)
https://en.wikipedia.org/wiki/SRGB. | [
"The",
"reverse",
"transformation",
"(",
"sRGB",
"to",
"CIE",
"XYZ",
")",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"SRGB",
"."
] | train | https://github.com/danmichaelo/php-coma/blob/946cd4c26f009cdc210d492962456a35eee8fbc3/src/Danmichaelo/Coma/sRGB.php#L53-L69 |
artkonekt/gears | src/UI/Tree.php | Tree.findNode | public function findNode(string $id, $searchChildren = false)
{
return $this->findByIdAmongChildren($id, $this->nodes(), $searchChildren);
} | php | public function findNode(string $id, $searchChildren = false)
{
return $this->findByIdAmongChildren($id, $this->nodes(), $searchChildren);
} | [
"public",
"function",
"findNode",
"(",
"string",
"$",
"id",
",",
"$",
"searchChildren",
"=",
"false",
")",
"{",
"return",
"$",
"this",
"->",
"findByIdAmongChildren",
"(",
"$",
"id",
",",
"$",
"this",
"->",
"nodes",
"(",
")",
",",
"$",
"searchChildren",
... | Searches a node in the tree and returns it if it was found
@param string $id
@param bool $searchChildren
@return Node|null | [
"Searches",
"a",
"node",
"in",
"the",
"tree",
"and",
"returns",
"it",
"if",
"it",
"was",
"found"
] | train | https://github.com/artkonekt/gears/blob/6c006a3e8e334d8100aab768a2a5e807bcac5695/src/UI/Tree.php#L50-L53 |
qloog/yaf-library | src/Log/Log.php | Log.getLogger | protected static function getLogger()
{
static $day;
if (static::$logger && $day == date('Y-m-d')) {
return static::$logger;
}
$day = date('Y-m-d');
$config = static::getConfig();
$logger = new Logger($config['channel']);
// 单元测试时不执行
if (defined('PHPUNIT_RUNNING')) {
$logger->pushHandler(new NullHandler());
} else {
// Syslog Log Handler
if (isset($config['syslog']) && isset($config['syslog']['host'], $config['syslog']['port'])) {
$handler = new SyslogUdpHandler($config['syslog']['host'], $config['syslog']['port'], LOG_USER, $config['level']);
$handler->setFormatter(new LineFormatter(static::getFormat()));
$logger->pushHandler($handler);
}
// File Log Handler
if (isset($config['file'])) {
if (!isset($config['file']['dir'])) {
throw new ConfigException('No log config!');
}
$logDir = $config['file']['dir'];
$logFile = $logDir . '/' . $day . '.log';
$handler = new StreamHandler($logFile, $config['level'], true, 0777);
$handler->setFormatter(new LineFormatter(static::getFormat() . "\n"));
$logger->pushHandler($handler);
}
}
return static::$logger = $logger;
} | php | protected static function getLogger()
{
static $day;
if (static::$logger && $day == date('Y-m-d')) {
return static::$logger;
}
$day = date('Y-m-d');
$config = static::getConfig();
$logger = new Logger($config['channel']);
// 单元测试时不执行
if (defined('PHPUNIT_RUNNING')) {
$logger->pushHandler(new NullHandler());
} else {
// Syslog Log Handler
if (isset($config['syslog']) && isset($config['syslog']['host'], $config['syslog']['port'])) {
$handler = new SyslogUdpHandler($config['syslog']['host'], $config['syslog']['port'], LOG_USER, $config['level']);
$handler->setFormatter(new LineFormatter(static::getFormat()));
$logger->pushHandler($handler);
}
// File Log Handler
if (isset($config['file'])) {
if (!isset($config['file']['dir'])) {
throw new ConfigException('No log config!');
}
$logDir = $config['file']['dir'];
$logFile = $logDir . '/' . $day . '.log';
$handler = new StreamHandler($logFile, $config['level'], true, 0777);
$handler->setFormatter(new LineFormatter(static::getFormat() . "\n"));
$logger->pushHandler($handler);
}
}
return static::$logger = $logger;
} | [
"protected",
"static",
"function",
"getLogger",
"(",
")",
"{",
"static",
"$",
"day",
";",
"if",
"(",
"static",
"::",
"$",
"logger",
"&&",
"$",
"day",
"==",
"date",
"(",
"'Y-m-d'",
")",
")",
"{",
"return",
"static",
"::",
"$",
"logger",
";",
"}",
"$... | Make a default log instance.
@return Logger|LoggerInterface
@throws ConfigException | [
"Make",
"a",
"default",
"log",
"instance",
"."
] | train | https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Log/Log.php#L154-L193 |
qloog/yaf-library | src/Log/Log.php | Log.getConfig | protected static function getConfig()
{
if (static::$config) {
return static::$config;
}
$config = Registry::get('config');
if (!isset($config['log'])) {
throw new ConfigException('log config not exists');
}
$config = $config['log'];
if (!isset($config['level'])) {
$config['level'] = 'info';
}
$config['level'] = isset(static::$logLevels[$config['level']])
? static::$logLevels[$config['level']]
: Logger::INFO;
if (!isset($config['channel'])) {
$config['channel'] = static::$defaultChannel;
}
return static::$config = $config;
} | php | protected static function getConfig()
{
if (static::$config) {
return static::$config;
}
$config = Registry::get('config');
if (!isset($config['log'])) {
throw new ConfigException('log config not exists');
}
$config = $config['log'];
if (!isset($config['level'])) {
$config['level'] = 'info';
}
$config['level'] = isset(static::$logLevels[$config['level']])
? static::$logLevels[$config['level']]
: Logger::INFO;
if (!isset($config['channel'])) {
$config['channel'] = static::$defaultChannel;
}
return static::$config = $config;
} | [
"protected",
"static",
"function",
"getConfig",
"(",
")",
"{",
"if",
"(",
"static",
"::",
"$",
"config",
")",
"{",
"return",
"static",
"::",
"$",
"config",
";",
"}",
"$",
"config",
"=",
"Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"if",
"(",
... | 获取配置信息
@todo should be inject
@return array
@throws ConfigException | [
"获取配置信息"
] | train | https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Log/Log.php#L203-L227 |
makinacorpus/drupal-ucms | ucms_group/src/Action/SiteActionProvider.php | SiteActionProvider.getActions | public function getActions($item, $primaryOnly = false, array $groups = [])
{
/** @var \MakinaCorpus\Ucms\Site\Site $item */
$ret = [];
if ($this->isGranted(Access::PERM_GROUP_MANAGE_ALL)) {
$ret[] = new Action($this->t("Attach to group"), 'admin/dashboard/site/' . $item->getId() . '/group-attach', 'dialog', 'tent', 200, false, true, false, 'group');
}
return $ret;
} | php | public function getActions($item, $primaryOnly = false, array $groups = [])
{
/** @var \MakinaCorpus\Ucms\Site\Site $item */
$ret = [];
if ($this->isGranted(Access::PERM_GROUP_MANAGE_ALL)) {
$ret[] = new Action($this->t("Attach to group"), 'admin/dashboard/site/' . $item->getId() . '/group-attach', 'dialog', 'tent', 200, false, true, false, 'group');
}
return $ret;
} | [
"public",
"function",
"getActions",
"(",
"$",
"item",
",",
"$",
"primaryOnly",
"=",
"false",
",",
"array",
"$",
"groups",
"=",
"[",
"]",
")",
"{",
"/** @var \\MakinaCorpus\\Ucms\\Site\\Site $item */",
"$",
"ret",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"this",... | {inheritdoc} | [
"{",
"inheritdoc",
"}"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_group/src/Action/SiteActionProvider.php#L15-L25 |
potsky/microsoft-translator-php-sdk | src/MicrosoftTranslator/Tools.php | Tools.httpBuildUrl | public static function httpBuildUrl( $url , $parts = array() , $flags = self::HTTP_URL_REPLACE , &$new_url = false )
{
$keys = array( 'user' , 'pass' , 'port' , 'path' , 'query' , 'fragment' );
// self::HTTP_URL_STRIP_ALL becomes all the self::HTTP_URL_STRIP_Xs
if ( $flags & self::HTTP_URL_STRIP_ALL )
{
$flags |= self::HTTP_URL_STRIP_USER;
$flags |= self::HTTP_URL_STRIP_PASS;
$flags |= self::HTTP_URL_STRIP_PORT;
$flags |= self::HTTP_URL_STRIP_PATH;
$flags |= self::HTTP_URL_STRIP_QUERY;
$flags |= self::HTTP_URL_STRIP_FRAGMENT;
}
// self::HTTP_URL_STRIP_AUTH becomes self::HTTP_URL_STRIP_USER and self::HTTP_URL_STRIP_PASS
else if ( $flags & self::HTTP_URL_STRIP_AUTH )
{
$flags |= self::HTTP_URL_STRIP_USER;
$flags |= self::HTTP_URL_STRIP_PASS;
}
// Parse the original URL
$parse_url = (array)parse_url( $url );
// Scheme and Host are always replaced
if ( isset( $parts[ 'scheme' ] ) )
{
$parse_url[ 'scheme' ] = $parts[ 'scheme' ];
}
if ( isset( $parts[ 'host' ] ) )
{
$parse_url[ 'host' ] = $parts[ 'host' ];
}
// (If applicable) Replace the original URL with it's new parts
if ( $flags & self::HTTP_URL_REPLACE )
{
foreach ( $keys as $key )
{
if ( isset( $parts[ $key ] ) )
{
$parse_url[ $key ] = $parts[ $key ];
}
}
}
else
{
// Join the original URL path with the new path
if ( isset( $parts[ 'path' ] ) && ( $flags & self::HTTP_URL_JOIN_PATH ) )
{
if ( isset( $parse_url[ 'path' ] ) )
{
$parse_url[ 'path' ] = rtrim( str_replace( basename( $parse_url[ 'path' ] ) , '' , $parse_url[ 'path' ] ) , '/' ) . '/' . ltrim( $parts[ 'path' ] , '/' );
}
else
{
$parse_url[ 'path' ] = $parts[ 'path' ];
}
}
// Join the original query string with the new query string
if ( isset( $parts[ 'query' ] ) && ( $flags & self::HTTP_URL_JOIN_QUERY ) )
{
if ( isset( $parse_url[ 'query' ] ) )
{
$parse_url[ 'query' ] .= '&' . $parts[ 'query' ];
}
else
{
$parse_url[ 'query' ] = $parts[ 'query' ];
}
}
}
// Strips all the applicable sections of the URL
// Note: Scheme and Host are never stripped
foreach ( $keys as $key )
{
if ( $flags & (int)constant( 'self::HTTP_URL_STRIP_' . strtoupper( $key ) ) )
{
unset( $parse_url[ $key ] );
}
}
$new_url = $parse_url;
return ( ( isset( $parse_url[ 'scheme' ] ) ) ? $parse_url[ 'scheme' ] . '://' : '' )
. ( ( isset( $parse_url[ 'user' ] ) ) ? $parse_url[ 'user' ] . ( ( isset( $parse_url[ 'pass' ] ) ) ? ':' . $parse_url[ 'pass' ] : '' ) . '@' : '' )
. ( ( isset( $parse_url[ 'host' ] ) ) ? $parse_url[ 'host' ] : '' )
. ( ( isset( $parse_url[ 'port' ] ) ) ? ':' . $parse_url[ 'port' ] : '' )
. ( ( isset( $parse_url[ 'path' ] ) ) ? $parse_url[ 'path' ] : '' )
. ( ( isset( $parse_url[ 'query' ] ) ) ? '?' . $parse_url[ 'query' ] : '' )
. ( ( isset( $parse_url[ 'fragment' ] ) ) ? '#' . $parse_url[ 'fragment' ] : '' );
} | php | public static function httpBuildUrl( $url , $parts = array() , $flags = self::HTTP_URL_REPLACE , &$new_url = false )
{
$keys = array( 'user' , 'pass' , 'port' , 'path' , 'query' , 'fragment' );
// self::HTTP_URL_STRIP_ALL becomes all the self::HTTP_URL_STRIP_Xs
if ( $flags & self::HTTP_URL_STRIP_ALL )
{
$flags |= self::HTTP_URL_STRIP_USER;
$flags |= self::HTTP_URL_STRIP_PASS;
$flags |= self::HTTP_URL_STRIP_PORT;
$flags |= self::HTTP_URL_STRIP_PATH;
$flags |= self::HTTP_URL_STRIP_QUERY;
$flags |= self::HTTP_URL_STRIP_FRAGMENT;
}
// self::HTTP_URL_STRIP_AUTH becomes self::HTTP_URL_STRIP_USER and self::HTTP_URL_STRIP_PASS
else if ( $flags & self::HTTP_URL_STRIP_AUTH )
{
$flags |= self::HTTP_URL_STRIP_USER;
$flags |= self::HTTP_URL_STRIP_PASS;
}
// Parse the original URL
$parse_url = (array)parse_url( $url );
// Scheme and Host are always replaced
if ( isset( $parts[ 'scheme' ] ) )
{
$parse_url[ 'scheme' ] = $parts[ 'scheme' ];
}
if ( isset( $parts[ 'host' ] ) )
{
$parse_url[ 'host' ] = $parts[ 'host' ];
}
// (If applicable) Replace the original URL with it's new parts
if ( $flags & self::HTTP_URL_REPLACE )
{
foreach ( $keys as $key )
{
if ( isset( $parts[ $key ] ) )
{
$parse_url[ $key ] = $parts[ $key ];
}
}
}
else
{
// Join the original URL path with the new path
if ( isset( $parts[ 'path' ] ) && ( $flags & self::HTTP_URL_JOIN_PATH ) )
{
if ( isset( $parse_url[ 'path' ] ) )
{
$parse_url[ 'path' ] = rtrim( str_replace( basename( $parse_url[ 'path' ] ) , '' , $parse_url[ 'path' ] ) , '/' ) . '/' . ltrim( $parts[ 'path' ] , '/' );
}
else
{
$parse_url[ 'path' ] = $parts[ 'path' ];
}
}
// Join the original query string with the new query string
if ( isset( $parts[ 'query' ] ) && ( $flags & self::HTTP_URL_JOIN_QUERY ) )
{
if ( isset( $parse_url[ 'query' ] ) )
{
$parse_url[ 'query' ] .= '&' . $parts[ 'query' ];
}
else
{
$parse_url[ 'query' ] = $parts[ 'query' ];
}
}
}
// Strips all the applicable sections of the URL
// Note: Scheme and Host are never stripped
foreach ( $keys as $key )
{
if ( $flags & (int)constant( 'self::HTTP_URL_STRIP_' . strtoupper( $key ) ) )
{
unset( $parse_url[ $key ] );
}
}
$new_url = $parse_url;
return ( ( isset( $parse_url[ 'scheme' ] ) ) ? $parse_url[ 'scheme' ] . '://' : '' )
. ( ( isset( $parse_url[ 'user' ] ) ) ? $parse_url[ 'user' ] . ( ( isset( $parse_url[ 'pass' ] ) ) ? ':' . $parse_url[ 'pass' ] : '' ) . '@' : '' )
. ( ( isset( $parse_url[ 'host' ] ) ) ? $parse_url[ 'host' ] : '' )
. ( ( isset( $parse_url[ 'port' ] ) ) ? ':' . $parse_url[ 'port' ] : '' )
. ( ( isset( $parse_url[ 'path' ] ) ) ? $parse_url[ 'path' ] : '' )
. ( ( isset( $parse_url[ 'query' ] ) ) ? '?' . $parse_url[ 'query' ] : '' )
. ( ( isset( $parse_url[ 'fragment' ] ) ) ? '#' . $parse_url[ 'fragment' ] : '' );
} | [
"public",
"static",
"function",
"httpBuildUrl",
"(",
"$",
"url",
",",
"$",
"parts",
"=",
"array",
"(",
")",
",",
"$",
"flags",
"=",
"self",
"::",
"HTTP_URL_REPLACE",
",",
"&",
"$",
"new_url",
"=",
"false",
")",
"{",
"$",
"keys",
"=",
"array",
"(",
... | Build an URL
The parts of the second URL will be merged into the first according to the flags argument.
@param mixed $url (Part(s) of) an URL in form of a string or associative array like parse_url() returns
@param mixed $parts Same as the first argument
@param int $flags A bitmask of binary or'ed HTTP_URL constants (Optional)self::HTTP_URL_REPLACE is the
default
@param array|bool $new_url If set, it will be filled with the parts of the composed url like parse_url() would
return
@return string | [
"Build",
"an",
"URL",
"The",
"parts",
"of",
"the",
"second",
"URL",
"will",
"be",
"merged",
"into",
"the",
"first",
"according",
"to",
"the",
"flags",
"argument",
"."
] | train | https://github.com/potsky/microsoft-translator-php-sdk/blob/102f2411be5abb0e57a73c475f8e9e185a9f4859/src/MicrosoftTranslator/Tools.php#L31-L124 |
potsky/microsoft-translator-php-sdk | src/MicrosoftTranslator/Tools.php | Tools.getArrayDotValue | public static function getArrayDotValue( array $context , $name )
{
$pieces = explode( '.' , $name );
foreach ( $pieces as $piece )
{
if ( ! is_array( $context ) || ! array_key_exists( $piece , $context ) )
{
return null;
}
$context = $context[ $piece ];
}
return $context;
} | php | public static function getArrayDotValue( array $context , $name )
{
$pieces = explode( '.' , $name );
foreach ( $pieces as $piece )
{
if ( ! is_array( $context ) || ! array_key_exists( $piece , $context ) )
{
return null;
}
$context = $context[ $piece ];
}
return $context;
} | [
"public",
"static",
"function",
"getArrayDotValue",
"(",
"array",
"$",
"context",
",",
"$",
"name",
")",
"{",
"$",
"pieces",
"=",
"explode",
"(",
"'.'",
",",
"$",
"name",
")",
";",
"foreach",
"(",
"$",
"pieces",
"as",
"$",
"piece",
")",
"{",
"if",
... | Get a key in a multi-dimension array with array dot notation
@param array $context the haystack
@param string $name the array dot key notation needle
@return mixed|null | [
"Get",
"a",
"key",
"in",
"a",
"multi",
"-",
"dimension",
"array",
"with",
"array",
"dot",
"notation"
] | train | https://github.com/potsky/microsoft-translator-php-sdk/blob/102f2411be5abb0e57a73c475f8e9e185a9f4859/src/MicrosoftTranslator/Tools.php#L135-L148 |
potsky/microsoft-translator-php-sdk | src/MicrosoftTranslator/Tools.php | Tools.endsWith | public static function endsWith( $haystack , $needle )
{
return $needle === "" || ( ( $temp = strlen( $haystack ) - strlen( $needle ) ) >= 0 && strpos( $haystack , $needle , $temp ) !== false );
} | php | public static function endsWith( $haystack , $needle )
{
return $needle === "" || ( ( $temp = strlen( $haystack ) - strlen( $needle ) ) >= 0 && strpos( $haystack , $needle , $temp ) !== false );
} | [
"public",
"static",
"function",
"endsWith",
"(",
"$",
"haystack",
",",
"$",
"needle",
")",
"{",
"return",
"$",
"needle",
"===",
"\"\"",
"||",
"(",
"(",
"$",
"temp",
"=",
"strlen",
"(",
"$",
"haystack",
")",
"-",
"strlen",
"(",
"$",
"needle",
")",
"... | @param string $haystack
@param string $needle
@return bool | [
"@param",
"string",
"$haystack",
"@param",
"string",
"$needle"
] | train | https://github.com/potsky/microsoft-translator-php-sdk/blob/102f2411be5abb0e57a73c475f8e9e185a9f4859/src/MicrosoftTranslator/Tools.php#L177-L180 |
beyerz/OpenGraphProtocolBundle | Libraries/OpenGraph.php | OpenGraph.prepareLibraryDefaults | public function prepareLibraryDefaults(){
$libraries = $this->container->getParameter('libraries');
//Initiate Library Classes and load defaults
foreach($libraries as $library=>$defaults){
//load class
$this->addLibraryClass($library,$defaults[self::FIELD_CLASS]);
$this->setLibDefaults($library,$defaults[self::FIELD_DEFAULT_VALUES]);
}
} | php | public function prepareLibraryDefaults(){
$libraries = $this->container->getParameter('libraries');
//Initiate Library Classes and load defaults
foreach($libraries as $library=>$defaults){
//load class
$this->addLibraryClass($library,$defaults[self::FIELD_CLASS]);
$this->setLibDefaults($library,$defaults[self::FIELD_DEFAULT_VALUES]);
}
} | [
"public",
"function",
"prepareLibraryDefaults",
"(",
")",
"{",
"$",
"libraries",
"=",
"$",
"this",
"->",
"container",
"->",
"getParameter",
"(",
"'libraries'",
")",
";",
"//Initiate Library Classes and load defaults",
"foreach",
"(",
"$",
"libraries",
"as",
"$",
"... | Load the defined libraries and set the defaults on each of them | [
"Load",
"the",
"defined",
"libraries",
"and",
"set",
"the",
"defaults",
"on",
"each",
"of",
"them"
] | train | https://github.com/beyerz/OpenGraphProtocolBundle/blob/6f058432895c29055e15ad044c5b7b3bbd3b098a/Libraries/OpenGraph.php#L26-L34 |
makinacorpus/drupal-ucms | ucms_layout/src/EventDispatcher/NodeEventSubscriber.php | NodeEventSubscriber.onInsert | public function onInsert(NodeEvent $event)
{
$node = $event->getNode();
// When inserting a node, site_id is always the current site context.
if ($event->isClone() && $node->site_id) {
$exists = (bool)$this
->db
->query(
"SELECT 1 FROM {ucms_site_node} WHERE nid = :nid AND site_id = :sid",
[':nid' => $node->parent_nid, ':sid' => $node->site_id]
)
;
if ($exists) {
// On clone, the original node layout should be kept but owned
// by the clone instead of the parent, IF AND ONLY IF the site
// is the same; please note that the dereferencing happens in
// 'ucms_site' module.
$this
->db
->query(
"UPDATE {ucms_layout} SET nid = :clone WHERE nid = :parent AND site_id = :site",
[
':clone' => $node->id(),
':parent' => $node->parent_nid,
':site' => $node->site_id,
]
)
;
// The same way, if the original node was present in some site
// layout, it must be replaced by the new one, IF AND ONLY IF
// the site is the same
switch ($this->db->driver()) {
case 'mysql':
$sql = "
UPDATE {ucms_layout_data} d
JOIN {ucms_layout} l ON l.id = d.layout_id
SET
d.nid = :clone
WHERE
d.nid = :parent
AND l.site_id = :site
";
break;
default:
$sql = "
UPDATE {ucms_layout_data} AS d
SET
nid = :clone
FROM {ucms_layout} l
WHERE
l.id = d.layout_id
AND d.nid = :parent
AND l.site_id = :site
";
break;
}
$this->db->query($sql, [
':clone' => $node->id(),
':parent' => $node->parent_nid,
':site' => $node->site_id,
]);
}
}
} | php | public function onInsert(NodeEvent $event)
{
$node = $event->getNode();
// When inserting a node, site_id is always the current site context.
if ($event->isClone() && $node->site_id) {
$exists = (bool)$this
->db
->query(
"SELECT 1 FROM {ucms_site_node} WHERE nid = :nid AND site_id = :sid",
[':nid' => $node->parent_nid, ':sid' => $node->site_id]
)
;
if ($exists) {
// On clone, the original node layout should be kept but owned
// by the clone instead of the parent, IF AND ONLY IF the site
// is the same; please note that the dereferencing happens in
// 'ucms_site' module.
$this
->db
->query(
"UPDATE {ucms_layout} SET nid = :clone WHERE nid = :parent AND site_id = :site",
[
':clone' => $node->id(),
':parent' => $node->parent_nid,
':site' => $node->site_id,
]
)
;
// The same way, if the original node was present in some site
// layout, it must be replaced by the new one, IF AND ONLY IF
// the site is the same
switch ($this->db->driver()) {
case 'mysql':
$sql = "
UPDATE {ucms_layout_data} d
JOIN {ucms_layout} l ON l.id = d.layout_id
SET
d.nid = :clone
WHERE
d.nid = :parent
AND l.site_id = :site
";
break;
default:
$sql = "
UPDATE {ucms_layout_data} AS d
SET
nid = :clone
FROM {ucms_layout} l
WHERE
l.id = d.layout_id
AND d.nid = :parent
AND l.site_id = :site
";
break;
}
$this->db->query($sql, [
':clone' => $node->id(),
':parent' => $node->parent_nid,
':site' => $node->site_id,
]);
}
}
} | [
"public",
"function",
"onInsert",
"(",
"NodeEvent",
"$",
"event",
")",
"{",
"$",
"node",
"=",
"$",
"event",
"->",
"getNode",
"(",
")",
";",
"// When inserting a node, site_id is always the current site context.",
"if",
"(",
"$",
"event",
"->",
"isClone",
"(",
")... | When cloning a node within a site, we must replace all its parent
references using the new new node identifier instead, in order to make
it gracefully inherit from the right layouts. | [
"When",
"cloning",
"a",
"node",
"within",
"a",
"site",
"we",
"must",
"replace",
"all",
"its",
"parent",
"references",
"using",
"the",
"new",
"new",
"node",
"identifier",
"instead",
"in",
"order",
"to",
"make",
"it",
"gracefully",
"inherit",
"from",
"the",
... | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_layout/src/EventDispatcher/NodeEventSubscriber.php#L44-L115 |
despark/ignicms | src/Models/AdminModel.php | AdminModel.setAttribute | public function setAttribute($key, $value)
{
parent::setAttribute($key, $value); // TODO: Change the autogenerated stub
if (isset($this->attributes[$key]) && is_string($this->attributes[$key]) && strlen($this->attributes[$key]) === 0) {
$this->attributes[$key] = null;
}
return $this;
} | php | public function setAttribute($key, $value)
{
parent::setAttribute($key, $value); // TODO: Change the autogenerated stub
if (isset($this->attributes[$key]) && is_string($this->attributes[$key]) && strlen($this->attributes[$key]) === 0) {
$this->attributes[$key] = null;
}
return $this;
} | [
"public",
"function",
"setAttribute",
"(",
"$",
"key",
",",
"$",
"value",
")",
"{",
"parent",
"::",
"setAttribute",
"(",
"$",
"key",
",",
"$",
"value",
")",
";",
"// TODO: Change the autogenerated stub",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"attribu... | Override set attributes so we can check for empty strings.
@todo We need a different way to achieve this
@param string $key
@param mixed $value
@return $this | [
"Override",
"set",
"attributes",
"so",
"we",
"can",
"check",
"for",
"empty",
"strings",
"."
] | train | https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/src/Models/AdminModel.php#L81-L90 |
despark/ignicms | src/Models/AdminModel.php | AdminModel.getDirty | public function getDirty()
{
$dirty = parent::getDirty();
if (! empty($this->files)) {
// We just set the ID to the same value to trigger the update.
$dirty[$this->getKeyName()] = $this->getKey();
}
return $dirty;
} | php | public function getDirty()
{
$dirty = parent::getDirty();
if (! empty($this->files)) {
// We just set the ID to the same value to trigger the update.
$dirty[$this->getKeyName()] = $this->getKey();
}
return $dirty;
} | [
"public",
"function",
"getDirty",
"(",
")",
"{",
"$",
"dirty",
"=",
"parent",
"::",
"getDirty",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"files",
")",
")",
"{",
"// We just set the ID to the same value to trigger the update.",
"$",
"di... | Override is dirty so we can trigger update if we have dirty images.
@return array | [
"Override",
"is",
"dirty",
"so",
"we",
"can",
"trigger",
"update",
"if",
"we",
"have",
"dirty",
"images",
"."
] | train | https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/src/Models/AdminModel.php#L142-L151 |
makinacorpus/drupal-ucms | ucms_notification/src/EventDispatcher/NodeEventSubscriber.php | NodeEventSubscriber.ensureNodeSubscribers | private function ensureNodeSubscribers(NodeEvent $event)
{
$node = $event->getNode();
$followers = [];
if ($userId = $node->getOwnerId()) {
$followers[] = $userId;
}
if ($userId = $this->currentUser->id()) {
$followers[] = $userId;
}
if ($this->siteManager && $node->site_id) {
// Notify all webmasters for the site, useful for content modified by local contributors.
$site = $this->siteManager->getStorage()->findOne($node->site_id);
foreach ($this->siteManager->getAccess()->listWebmasters($site) as $webmaster) {
$followers[] = $webmaster->getUserId();
}
}
$this->service->getNotificationService()->subscribe('node', $node->id(), $followers);
} | php | private function ensureNodeSubscribers(NodeEvent $event)
{
$node = $event->getNode();
$followers = [];
if ($userId = $node->getOwnerId()) {
$followers[] = $userId;
}
if ($userId = $this->currentUser->id()) {
$followers[] = $userId;
}
if ($this->siteManager && $node->site_id) {
// Notify all webmasters for the site, useful for content modified by local contributors.
$site = $this->siteManager->getStorage()->findOne($node->site_id);
foreach ($this->siteManager->getAccess()->listWebmasters($site) as $webmaster) {
$followers[] = $webmaster->getUserId();
}
}
$this->service->getNotificationService()->subscribe('node', $node->id(), $followers);
} | [
"private",
"function",
"ensureNodeSubscribers",
"(",
"NodeEvent",
"$",
"event",
")",
"{",
"$",
"node",
"=",
"$",
"event",
"->",
"getNode",
"(",
")",
";",
"$",
"followers",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"userId",
"=",
"$",
"node",
"->",
"getOwne... | From the given node, ensure subscribers
@param NodeEvent $event | [
"From",
"the",
"given",
"node",
"ensure",
"subscribers"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_notification/src/EventDispatcher/NodeEventSubscriber.php#L77-L99 |
makinacorpus/drupal-ucms | ucms_notification/src/EventDispatcher/NodeEventSubscriber.php | NodeEventSubscriber.onInsert | public function onInsert(NodeEvent $event)
{
$node = $event->getNode();
$this->ensureNodeSubscribers($event);
// Enfore node event to run, so that the automatic resource listener
// will raise the correct notifications
$newEvent = new ResourceEvent('node', $node->nid, $this->currentUser->id());
$this->dispatcher->dispatch('node:add', $newEvent);
} | php | public function onInsert(NodeEvent $event)
{
$node = $event->getNode();
$this->ensureNodeSubscribers($event);
// Enfore node event to run, so that the automatic resource listener
// will raise the correct notifications
$newEvent = new ResourceEvent('node', $node->nid, $this->currentUser->id());
$this->dispatcher->dispatch('node:add', $newEvent);
} | [
"public",
"function",
"onInsert",
"(",
"NodeEvent",
"$",
"event",
")",
"{",
"$",
"node",
"=",
"$",
"event",
"->",
"getNode",
"(",
")",
";",
"$",
"this",
"->",
"ensureNodeSubscribers",
"(",
"$",
"event",
")",
";",
"// Enfore node event to run, so that the autom... | On node insert | [
"On",
"node",
"insert"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_notification/src/EventDispatcher/NodeEventSubscriber.php#L104-L114 |
makinacorpus/drupal-ucms | ucms_notification/src/EventDispatcher/NodeEventSubscriber.php | NodeEventSubscriber.onUpdateRunNodeEvents | public function onUpdateRunNodeEvents(NodeEvent $event)
{
$node = $event->getNode();
$this->ensureNodeSubscribers($event);
$newEvent = new ResourceEvent('node', $node->nid, $this->currentUser->id());
if ($node->is_flagged != $node->original->is_flagged) {
if ($node->is_flagged) {
$this->dispatcher->dispatch('node:flag', $newEvent);
}
} else if ($node->status != $node->original->status) {
if ($node->status) {
$this->dispatcher->dispatch('node:publish', $newEvent);
} else {
$this->dispatcher->dispatch('node:unpublish', $newEvent);
}
} else {
$this->dispatcher->dispatch('node:edit', $newEvent);
}
} | php | public function onUpdateRunNodeEvents(NodeEvent $event)
{
$node = $event->getNode();
$this->ensureNodeSubscribers($event);
$newEvent = new ResourceEvent('node', $node->nid, $this->currentUser->id());
if ($node->is_flagged != $node->original->is_flagged) {
if ($node->is_flagged) {
$this->dispatcher->dispatch('node:flag', $newEvent);
}
} else if ($node->status != $node->original->status) {
if ($node->status) {
$this->dispatcher->dispatch('node:publish', $newEvent);
} else {
$this->dispatcher->dispatch('node:unpublish', $newEvent);
}
} else {
$this->dispatcher->dispatch('node:edit', $newEvent);
}
} | [
"public",
"function",
"onUpdateRunNodeEvents",
"(",
"NodeEvent",
"$",
"event",
")",
"{",
"$",
"node",
"=",
"$",
"event",
"->",
"getNode",
"(",
")",
";",
"$",
"this",
"->",
"ensureNodeSubscribers",
"(",
"$",
"event",
")",
";",
"$",
"newEvent",
"=",
"new",... | On node update raise node related notifications | [
"On",
"node",
"update",
"raise",
"node",
"related",
"notifications"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_notification/src/EventDispatcher/NodeEventSubscriber.php#L119-L140 |
makinacorpus/drupal-ucms | ucms_notification/src/EventDispatcher/NodeEventSubscriber.php | NodeEventSubscriber.onUpdateRunLabelEvents | public function onUpdateRunLabelEvents(NodeEvent $event)
{
$node = $event->getNode();
if ($oldLabels = field_get_items('node', $node->original, 'labels')) {
$oldLabels = array_column($oldLabels, 'tid');
} else {
$oldLabels = [];
}
if ($currentLabels = field_get_items('node', $node, 'labels')) {
if (is_array($currentLabels)) {
$currentLabels = array_column($currentLabels, 'tid');
}
else {
$currentLabels = (array) $currentLabels;
}
}
if ($currentLabels && ($newLabels = array_diff($currentLabels, $oldLabels))) {
$newEvent = new ResourceEvent('node', $node->nid, $this->currentUser->id());
$newEvent->setArgument('new_labels', $newLabels);
$this->dispatcher->dispatch('node:new_labels', $newEvent);
}
} | php | public function onUpdateRunLabelEvents(NodeEvent $event)
{
$node = $event->getNode();
if ($oldLabels = field_get_items('node', $node->original, 'labels')) {
$oldLabels = array_column($oldLabels, 'tid');
} else {
$oldLabels = [];
}
if ($currentLabels = field_get_items('node', $node, 'labels')) {
if (is_array($currentLabels)) {
$currentLabels = array_column($currentLabels, 'tid');
}
else {
$currentLabels = (array) $currentLabels;
}
}
if ($currentLabels && ($newLabels = array_diff($currentLabels, $oldLabels))) {
$newEvent = new ResourceEvent('node', $node->nid, $this->currentUser->id());
$newEvent->setArgument('new_labels', $newLabels);
$this->dispatcher->dispatch('node:new_labels', $newEvent);
}
} | [
"public",
"function",
"onUpdateRunLabelEvents",
"(",
"NodeEvent",
"$",
"event",
")",
"{",
"$",
"node",
"=",
"$",
"event",
"->",
"getNode",
"(",
")",
";",
"if",
"(",
"$",
"oldLabels",
"=",
"field_get_items",
"(",
"'node'",
",",
"$",
"node",
"->",
"origina... | On node update raise label related notifications | [
"On",
"node",
"update",
"raise",
"label",
"related",
"notifications"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_notification/src/EventDispatcher/NodeEventSubscriber.php#L145-L169 |
makinacorpus/drupal-ucms | ucms_notification/src/EventDispatcher/NodeEventSubscriber.php | NodeEventSubscriber.onDelete | public function onDelete(NodeEvent $event)
{
$this->service->getNotificationService()->getBackend()->deleteChannel('node:' . $event->getEntityId());
} | php | public function onDelete(NodeEvent $event)
{
$this->service->getNotificationService()->getBackend()->deleteChannel('node:' . $event->getEntityId());
} | [
"public",
"function",
"onDelete",
"(",
"NodeEvent",
"$",
"event",
")",
"{",
"$",
"this",
"->",
"service",
"->",
"getNotificationService",
"(",
")",
"->",
"getBackend",
"(",
")",
"->",
"deleteChannel",
"(",
"'node:'",
".",
"$",
"event",
"->",
"getEntityId",
... | On node delete | [
"On",
"node",
"delete"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_notification/src/EventDispatcher/NodeEventSubscriber.php#L174-L177 |
aginev/acl | src/Http/Middleware/Acl.php | Acl.handle | public function handle($request, Closure $next)
{
$resource = $request->route()->getActionName();
$permission = Permission::where('resource', '=', $resource)->first();
// If the specific route requires permissions
if ($permission) {
// Get user permissions
try {
$user_permissions = Auth::user()->role->permissions->keyBy('resource');
} catch (\Exception $e) {
return abort(401, trans('acl::general.messages.user_permissions_not_found'));
}
// And the user has permissions
if (! $user_permissions->has($resource)) {
return abort(401, trans('acl::general.messages.no_permissions'));
}
}
return $next($request);
} | php | public function handle($request, Closure $next)
{
$resource = $request->route()->getActionName();
$permission = Permission::where('resource', '=', $resource)->first();
// If the specific route requires permissions
if ($permission) {
// Get user permissions
try {
$user_permissions = Auth::user()->role->permissions->keyBy('resource');
} catch (\Exception $e) {
return abort(401, trans('acl::general.messages.user_permissions_not_found'));
}
// And the user has permissions
if (! $user_permissions->has($resource)) {
return abort(401, trans('acl::general.messages.no_permissions'));
}
}
return $next($request);
} | [
"public",
"function",
"handle",
"(",
"$",
"request",
",",
"Closure",
"$",
"next",
")",
"{",
"$",
"resource",
"=",
"$",
"request",
"->",
"route",
"(",
")",
"->",
"getActionName",
"(",
")",
";",
"$",
"permission",
"=",
"Permission",
"::",
"where",
"(",
... | Handle an incoming request.
@param Request $request
@param \Closure $next
@return mixed | [
"Handle",
"an",
"incoming",
"request",
"."
] | train | https://github.com/aginev/acl/blob/7dcbe39c0955c3da7487f5d528423dd6e7ac7fd1/src/Http/Middleware/Acl.php#L17-L38 |
saxulum/saxulum-elasticsearch-querybuilder | src/QueryBuilder.php | QueryBuilder.add | public function add(...$arguments): QueryBuilderInterface
{
if ($this->node instanceof ObjectNode) {
return $this->addToObjectNode(...$arguments);
}
return $this->addToArrayNode(...$arguments);
} | php | public function add(...$arguments): QueryBuilderInterface
{
if ($this->node instanceof ObjectNode) {
return $this->addToObjectNode(...$arguments);
}
return $this->addToArrayNode(...$arguments);
} | [
"public",
"function",
"add",
"(",
"...",
"$",
"arguments",
")",
":",
"QueryBuilderInterface",
"{",
"if",
"(",
"$",
"this",
"->",
"node",
"instanceof",
"ObjectNode",
")",
"{",
"return",
"$",
"this",
"->",
"addToObjectNode",
"(",
"...",
"$",
"arguments",
")"... | @param array ...$arguments
@return QueryBuilderInterface
@throws \Exception | [
"@param",
"array",
"...",
"$arguments"
] | train | https://github.com/saxulum/saxulum-elasticsearch-querybuilder/blob/2f5a15925f3f3afe6a8efabf1f2c9af42f81d9b1/src/QueryBuilder.php#L46-L53 |
saxulum/saxulum-elasticsearch-querybuilder | src/QueryBuilder.php | QueryBuilder.addToArrayNode | public function addToArrayNode(AbstractNode $node): QueryBuilderInterface
{
if (!$this->node instanceof ArrayNode) {
throw new \Exception(sprintf('You cannot call %s on node type: %s', __FUNCTION__, get_class($this->node)));
}
$this->node->add($node);
$this->reassignParent($node);
return $this;
} | php | public function addToArrayNode(AbstractNode $node): QueryBuilderInterface
{
if (!$this->node instanceof ArrayNode) {
throw new \Exception(sprintf('You cannot call %s on node type: %s', __FUNCTION__, get_class($this->node)));
}
$this->node->add($node);
$this->reassignParent($node);
return $this;
} | [
"public",
"function",
"addToArrayNode",
"(",
"AbstractNode",
"$",
"node",
")",
":",
"QueryBuilderInterface",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"node",
"instanceof",
"ArrayNode",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"sprintf",
"(",
"'You ca... | @param AbstractNode $node
@return QueryBuilderInterface
@throws \Exception | [
"@param",
"AbstractNode",
"$node"
] | train | https://github.com/saxulum/saxulum-elasticsearch-querybuilder/blob/2f5a15925f3f3afe6a8efabf1f2c9af42f81d9b1/src/QueryBuilder.php#L62-L72 |
saxulum/saxulum-elasticsearch-querybuilder | src/QueryBuilder.php | QueryBuilder.addToObjectNode | public function addToObjectNode(string $key, AbstractNode $node): QueryBuilderInterface
{
if (!$this->node instanceof ObjectNode) {
throw new \Exception(sprintf('You cannot call %s on node type: %s', __FUNCTION__, get_class($this->node)));
}
$this->node->add($key, $node);
$this->reassignParent($node);
return $this;
} | php | public function addToObjectNode(string $key, AbstractNode $node): QueryBuilderInterface
{
if (!$this->node instanceof ObjectNode) {
throw new \Exception(sprintf('You cannot call %s on node type: %s', __FUNCTION__, get_class($this->node)));
}
$this->node->add($key, $node);
$this->reassignParent($node);
return $this;
} | [
"public",
"function",
"addToObjectNode",
"(",
"string",
"$",
"key",
",",
"AbstractNode",
"$",
"node",
")",
":",
"QueryBuilderInterface",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"node",
"instanceof",
"ObjectNode",
")",
"{",
"throw",
"new",
"\\",
"Exception",
... | @param string $key
@param AbstractNode $node
@return QueryBuilderInterface
@throws \Exception | [
"@param",
"string",
"$key",
"@param",
"AbstractNode",
"$node"
] | train | https://github.com/saxulum/saxulum-elasticsearch-querybuilder/blob/2f5a15925f3f3afe6a8efabf1f2c9af42f81d9b1/src/QueryBuilder.php#L82-L92 |
saxulum/saxulum-elasticsearch-querybuilder | src/QueryBuilder.php | QueryBuilder.end | public function end(): QueryBuilderInterface
{
if (null === $this->node = $this->node->getParent()) {
throw new \Exception(sprintf('You cannot call %s on main node', __FUNCTION__));
}
return $this;
} | php | public function end(): QueryBuilderInterface
{
if (null === $this->node = $this->node->getParent()) {
throw new \Exception(sprintf('You cannot call %s on main node', __FUNCTION__));
}
return $this;
} | [
"public",
"function",
"end",
"(",
")",
":",
"QueryBuilderInterface",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"node",
"=",
"$",
"this",
"->",
"node",
"->",
"getParent",
"(",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"sprintf",
"... | @return QueryBuilderInterface
@throws \Exception | [
"@return",
"QueryBuilderInterface"
] | train | https://github.com/saxulum/saxulum-elasticsearch-querybuilder/blob/2f5a15925f3f3afe6a8efabf1f2c9af42f81d9b1/src/QueryBuilder.php#L109-L116 |
saxulum/saxulum-elasticsearch-querybuilder | src/QueryBuilder.php | QueryBuilder.boolNode | public function boolNode($value = null, bool $allowSerializeEmpty = false): BoolNode
{
return BoolNode::create($value, $allowSerializeEmpty);
} | php | public function boolNode($value = null, bool $allowSerializeEmpty = false): BoolNode
{
return BoolNode::create($value, $allowSerializeEmpty);
} | [
"public",
"function",
"boolNode",
"(",
"$",
"value",
"=",
"null",
",",
"bool",
"$",
"allowSerializeEmpty",
"=",
"false",
")",
":",
"BoolNode",
"{",
"return",
"BoolNode",
"::",
"create",
"(",
"$",
"value",
",",
"$",
"allowSerializeEmpty",
")",
";",
"}"
] | @param bool|null $value
@param bool $allowSerializeEmpty
@return BoolNode | [
"@param",
"bool|null",
"$value",
"@param",
"bool",
"$allowSerializeEmpty"
] | train | https://github.com/saxulum/saxulum-elasticsearch-querybuilder/blob/2f5a15925f3f3afe6a8efabf1f2c9af42f81d9b1/src/QueryBuilder.php#L134-L137 |
saxulum/saxulum-elasticsearch-querybuilder | src/QueryBuilder.php | QueryBuilder.floatNode | public function floatNode($value = null, bool $allowSerializeEmpty = false): FloatNode
{
return FloatNode::create($value, $allowSerializeEmpty);
} | php | public function floatNode($value = null, bool $allowSerializeEmpty = false): FloatNode
{
return FloatNode::create($value, $allowSerializeEmpty);
} | [
"public",
"function",
"floatNode",
"(",
"$",
"value",
"=",
"null",
",",
"bool",
"$",
"allowSerializeEmpty",
"=",
"false",
")",
":",
"FloatNode",
"{",
"return",
"FloatNode",
"::",
"create",
"(",
"$",
"value",
",",
"$",
"allowSerializeEmpty",
")",
";",
"}"
] | @param float|null $value
@param bool $allowSerializeEmpty
@return FloatNode | [
"@param",
"float|null",
"$value",
"@param",
"bool",
"$allowSerializeEmpty"
] | train | https://github.com/saxulum/saxulum-elasticsearch-querybuilder/blob/2f5a15925f3f3afe6a8efabf1f2c9af42f81d9b1/src/QueryBuilder.php#L145-L148 |
saxulum/saxulum-elasticsearch-querybuilder | src/QueryBuilder.php | QueryBuilder.intNode | public function intNode($value = null, bool $allowSerializeEmpty = false): IntNode
{
return IntNode::create($value, $allowSerializeEmpty);
} | php | public function intNode($value = null, bool $allowSerializeEmpty = false): IntNode
{
return IntNode::create($value, $allowSerializeEmpty);
} | [
"public",
"function",
"intNode",
"(",
"$",
"value",
"=",
"null",
",",
"bool",
"$",
"allowSerializeEmpty",
"=",
"false",
")",
":",
"IntNode",
"{",
"return",
"IntNode",
"::",
"create",
"(",
"$",
"value",
",",
"$",
"allowSerializeEmpty",
")",
";",
"}"
] | @param int|null $value
@param bool $allowSerializeEmpty
@return IntNode | [
"@param",
"int|null",
"$value",
"@param",
"bool",
"$allowSerializeEmpty"
] | train | https://github.com/saxulum/saxulum-elasticsearch-querybuilder/blob/2f5a15925f3f3afe6a8efabf1f2c9af42f81d9b1/src/QueryBuilder.php#L156-L159 |
saxulum/saxulum-elasticsearch-querybuilder | src/QueryBuilder.php | QueryBuilder.stringNode | public function stringNode($value = null, bool $allowSerializeEmpty = false): StringNode
{
return StringNode::create($value, $allowSerializeEmpty);
} | php | public function stringNode($value = null, bool $allowSerializeEmpty = false): StringNode
{
return StringNode::create($value, $allowSerializeEmpty);
} | [
"public",
"function",
"stringNode",
"(",
"$",
"value",
"=",
"null",
",",
"bool",
"$",
"allowSerializeEmpty",
"=",
"false",
")",
":",
"StringNode",
"{",
"return",
"StringNode",
"::",
"create",
"(",
"$",
"value",
",",
"$",
"allowSerializeEmpty",
")",
";",
"}... | @param string|null $value
@param bool $allowSerializeEmpty
@return StringNode | [
"@param",
"string|null",
"$value",
"@param",
"bool",
"$allowSerializeEmpty"
] | train | https://github.com/saxulum/saxulum-elasticsearch-querybuilder/blob/2f5a15925f3f3afe6a8efabf1f2c9af42f81d9b1/src/QueryBuilder.php#L185-L188 |
saxulum/saxulum-elasticsearch-querybuilder | src/QueryBuilder.php | QueryBuilder.json | public function json(bool $beautify = false): string
{
if (null === $serialized = $this->serialize()) {
return '';
}
if ($beautify) {
return json_encode($serialized, JSON_PRETTY_PRINT);
}
return json_encode($serialized);
} | php | public function json(bool $beautify = false): string
{
if (null === $serialized = $this->serialize()) {
return '';
}
if ($beautify) {
return json_encode($serialized, JSON_PRETTY_PRINT);
}
return json_encode($serialized);
} | [
"public",
"function",
"json",
"(",
"bool",
"$",
"beautify",
"=",
"false",
")",
":",
"string",
"{",
"if",
"(",
"null",
"===",
"$",
"serialized",
"=",
"$",
"this",
"->",
"serialize",
"(",
")",
")",
"{",
"return",
"''",
";",
"}",
"if",
"(",
"$",
"be... | @param bool $beautify
@return string | [
"@param",
"bool",
"$beautify"
] | train | https://github.com/saxulum/saxulum-elasticsearch-querybuilder/blob/2f5a15925f3f3afe6a8efabf1f2c9af42f81d9b1/src/QueryBuilder.php#L203-L214 |
makinacorpus/drupal-ucms | ucms_composition/src/EventDispatcher/NodeEventSubscriber.php | NodeEventSubscriber.onSitePostInit | public function onSitePostInit(SiteEvent $event)
{
// @todo Ugly... The best would be to not use drupal_valid_token()
require_once DRUPAL_ROOT . '/includes/common.inc';
$request = $this->requestStack->getCurrentRequest();
$pageContext = $this->contextManager->getPageContext();
$transContext = $this->contextManager->getSiteContext();
$site = $event->getSite();
$token = null;
$matches = [];
// Column is nullable, so this is possible
if ($siteHomeNid = $site->getHomeNodeId()) {
if (($token = $request->get(ContextManager::PARAM_SITE_TOKEN)) && drupal_valid_token($token)) {
$transContext->setToken($token);
}
$transContext->setCurrentLayoutNodeId($siteHomeNid, $site->getId());
}
// @todo $_GET['q']: cannot use Request::get() here since Drupal
// alters the 'q' variable directly in the $_GET array
if (preg_match('/^node\/([0-9]+)$/', $_GET['q'], $matches) === 1) {
if (($token = $request->get(ContextManager::PARAM_PAGE_TOKEN)) && drupal_valid_token($token)) {
$pageContext->setToken($token);
}
$pageContext->setCurrentLayoutNodeId((int)$matches[1], $site->getId());
}
if (($token = $request->get(ContextManager::PARAM_AJAX_TOKEN)) && drupal_valid_token($token) && ($region = $request->get('region'))) {
if ($this->contextManager->isPageContextRegion($region, $site->theme)) {
$pageContext->setToken($token);
} else if ($this->contextManager->isTransversalContextRegion($region, $site->theme)) {
$transContext->setToken($token);
}
}
} | php | public function onSitePostInit(SiteEvent $event)
{
// @todo Ugly... The best would be to not use drupal_valid_token()
require_once DRUPAL_ROOT . '/includes/common.inc';
$request = $this->requestStack->getCurrentRequest();
$pageContext = $this->contextManager->getPageContext();
$transContext = $this->contextManager->getSiteContext();
$site = $event->getSite();
$token = null;
$matches = [];
// Column is nullable, so this is possible
if ($siteHomeNid = $site->getHomeNodeId()) {
if (($token = $request->get(ContextManager::PARAM_SITE_TOKEN)) && drupal_valid_token($token)) {
$transContext->setToken($token);
}
$transContext->setCurrentLayoutNodeId($siteHomeNid, $site->getId());
}
// @todo $_GET['q']: cannot use Request::get() here since Drupal
// alters the 'q' variable directly in the $_GET array
if (preg_match('/^node\/([0-9]+)$/', $_GET['q'], $matches) === 1) {
if (($token = $request->get(ContextManager::PARAM_PAGE_TOKEN)) && drupal_valid_token($token)) {
$pageContext->setToken($token);
}
$pageContext->setCurrentLayoutNodeId((int)$matches[1], $site->getId());
}
if (($token = $request->get(ContextManager::PARAM_AJAX_TOKEN)) && drupal_valid_token($token) && ($region = $request->get('region'))) {
if ($this->contextManager->isPageContextRegion($region, $site->theme)) {
$pageContext->setToken($token);
} else if ($this->contextManager->isTransversalContextRegion($region, $site->theme)) {
$transContext->setToken($token);
}
}
} | [
"public",
"function",
"onSitePostInit",
"(",
"SiteEvent",
"$",
"event",
")",
"{",
"// @todo Ugly... The best would be to not use drupal_valid_token()",
"require_once",
"DRUPAL_ROOT",
".",
"'/includes/common.inc'",
";",
"$",
"request",
"=",
"$",
"this",
"->",
"requestStack",... | Home page handling mostly. | [
"Home",
"page",
"handling",
"mostly",
"."
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_composition/src/EventDispatcher/NodeEventSubscriber.php#L141-L177 |
makinacorpus/drupal-ucms | ucms_composition/src/EventDispatcher/NodeEventSubscriber.php | NodeEventSubscriber.onSiteClone | public function onSiteClone(SiteCloneEvent $event)
{
$source = $event->getTemplateSite();
$target = $event->getSite();
// First copy node layouts
$this
->database
->query(
"
INSERT INTO {layout} (site_id, nid, region)
SELECT
:target, usn.nid, ul.region
FROM {layout} ul
JOIN {ucms_site_node} usn ON
ul.nid = usn.nid
AND usn.site_id = :target
WHERE
ul.site_id = :source
AND NOT EXISTS (
SELECT 1
FROM {layout} s_ul
WHERE
s_ul.nid = ul.nid
AND s_ul.site_id = :target3
)
",
[
':target' => $target->getId(),
':target2' => $target->getId(),
':source' => $source->getId(),
':target3' => $target->getId(),
]
)
;
// Then duplicate layout data
$this
->database
->query(
"
INSERT INTO {layout_data}
(layout_id, item_type, item_id, style, position, options)
SELECT
target_ul.id,
uld.item_type,
uld.item_id,
uld.style,
uld.position,
uld.options
FROM {layout} source_ul
JOIN {layout_data} uld ON
source_ul.id = uld.layout_id
AND source_ul.site_id = :source
JOIN {node} n ON n.nid = uld.nid
JOIN {layout} target_ul ON
target_ul.nid = source_ul.nid
AND target_ul.site_id = :target
WHERE
(n.status = 1 OR n.is_global = 0)
",
[
':source' => $source->getId(),
':target' => $target->getId(),
]
)
;
} | php | public function onSiteClone(SiteCloneEvent $event)
{
$source = $event->getTemplateSite();
$target = $event->getSite();
// First copy node layouts
$this
->database
->query(
"
INSERT INTO {layout} (site_id, nid, region)
SELECT
:target, usn.nid, ul.region
FROM {layout} ul
JOIN {ucms_site_node} usn ON
ul.nid = usn.nid
AND usn.site_id = :target
WHERE
ul.site_id = :source
AND NOT EXISTS (
SELECT 1
FROM {layout} s_ul
WHERE
s_ul.nid = ul.nid
AND s_ul.site_id = :target3
)
",
[
':target' => $target->getId(),
':target2' => $target->getId(),
':source' => $source->getId(),
':target3' => $target->getId(),
]
)
;
// Then duplicate layout data
$this
->database
->query(
"
INSERT INTO {layout_data}
(layout_id, item_type, item_id, style, position, options)
SELECT
target_ul.id,
uld.item_type,
uld.item_id,
uld.style,
uld.position,
uld.options
FROM {layout} source_ul
JOIN {layout_data} uld ON
source_ul.id = uld.layout_id
AND source_ul.site_id = :source
JOIN {node} n ON n.nid = uld.nid
JOIN {layout} target_ul ON
target_ul.nid = source_ul.nid
AND target_ul.site_id = :target
WHERE
(n.status = 1 OR n.is_global = 0)
",
[
':source' => $source->getId(),
':target' => $target->getId(),
]
)
;
} | [
"public",
"function",
"onSiteClone",
"(",
"SiteCloneEvent",
"$",
"event",
")",
"{",
"$",
"source",
"=",
"$",
"event",
"->",
"getTemplateSite",
"(",
")",
";",
"$",
"target",
"=",
"$",
"event",
"->",
"getSite",
"(",
")",
";",
"// First copy node layouts",
"$... | When cloning a site, we need to clone all layouts as well. | [
"When",
"cloning",
"a",
"site",
"we",
"need",
"to",
"clone",
"all",
"layouts",
"as",
"well",
"."
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_composition/src/EventDispatcher/NodeEventSubscriber.php#L182-L249 |
makinacorpus/drupal-ucms | ucms_composition/src/EventDispatcher/NodeEventSubscriber.php | NodeEventSubscriber.onAttach | public function onAttach(SiteAttachEvent $event)
{
// On 08/09/2016, I stumbled upon this piece of code. Long story short:
// when you reference a node in a site, it duplicates the original site
// layout in the new site.
//
// While I could see some kind of use for this, I am not sure this is
// really necessary.
//
// I am quite sure that the original wanted behavior was on node clone
// and not on node reference: when you want to edit a node that's not
// yours, on your site, the application propose that you may clone it on
// the site instead of editing the original node, at this exact point in
// time, you do need to duplicate layouts.
// Do no run when in edit mode
if ($this->context->hasToken()) {
return;
}
$siteIdList = $event->getSiteIdList();
/* @var \Drupal\node\NodeInterface[] $nodeList */
$nodeList = $this->entityManager->getStorage('node')->loadMultiple($event->getNodeIdList());
$pageContext = $this->contextManager->getPageContext();
$storage = $pageContext->getStorage();
// @todo Find a better way
foreach ($siteIdList as $siteId) {
foreach ($nodeList as $node) {
if (!$node->site_id) {
continue;
}
// Ensure a layout does not already exists (for example when
// cloning a node, the layout data already has been inserted
// if the original was existing).
$exists = (bool)$this
->db
->query(
"SELECT 1 FROM {ucms_layout} WHERE nid = :nid AND site_id = :sid",
[':nid' => $node->id(), ':sid' => $siteId]
)
->fetchField()
;
if ($exists) {
return;
}
$layout = $storage->findForNodeOnSite($node->id(), $node->site_id);
if ($layout) {
$clone = clone $layout;
$clone->setId(null);
$clone->setSiteId($siteId);
foreach ($clone->getAllRegions() as $region) {
$region->toggleUpdateStatus(true);
}
$storage->save($clone);
}
}
}
} | php | public function onAttach(SiteAttachEvent $event)
{
// On 08/09/2016, I stumbled upon this piece of code. Long story short:
// when you reference a node in a site, it duplicates the original site
// layout in the new site.
//
// While I could see some kind of use for this, I am not sure this is
// really necessary.
//
// I am quite sure that the original wanted behavior was on node clone
// and not on node reference: when you want to edit a node that's not
// yours, on your site, the application propose that you may clone it on
// the site instead of editing the original node, at this exact point in
// time, you do need to duplicate layouts.
// Do no run when in edit mode
if ($this->context->hasToken()) {
return;
}
$siteIdList = $event->getSiteIdList();
/* @var \Drupal\node\NodeInterface[] $nodeList */
$nodeList = $this->entityManager->getStorage('node')->loadMultiple($event->getNodeIdList());
$pageContext = $this->contextManager->getPageContext();
$storage = $pageContext->getStorage();
// @todo Find a better way
foreach ($siteIdList as $siteId) {
foreach ($nodeList as $node) {
if (!$node->site_id) {
continue;
}
// Ensure a layout does not already exists (for example when
// cloning a node, the layout data already has been inserted
// if the original was existing).
$exists = (bool)$this
->db
->query(
"SELECT 1 FROM {ucms_layout} WHERE nid = :nid AND site_id = :sid",
[':nid' => $node->id(), ':sid' => $siteId]
)
->fetchField()
;
if ($exists) {
return;
}
$layout = $storage->findForNodeOnSite($node->id(), $node->site_id);
if ($layout) {
$clone = clone $layout;
$clone->setId(null);
$clone->setSiteId($siteId);
foreach ($clone->getAllRegions() as $region) {
$region->toggleUpdateStatus(true);
}
$storage->save($clone);
}
}
}
} | [
"public",
"function",
"onAttach",
"(",
"SiteAttachEvent",
"$",
"event",
")",
"{",
"// On 08/09/2016, I stumbled upon this piece of code. Long story short:",
"// when you reference a node in a site, it duplicates the original site",
"// layout in the new site.",
"//",
"// While I could see ... | When referencing a node on site, we clone its original layout as well
so the user gets an exact copy of the page. | [
"When",
"referencing",
"a",
"node",
"on",
"site",
"we",
"clone",
"its",
"original",
"layout",
"as",
"well",
"so",
"the",
"user",
"gets",
"an",
"exact",
"copy",
"of",
"the",
"page",
"."
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_composition/src/EventDispatcher/NodeEventSubscriber.php#L255-L321 |
PHPixie/HTTP | src/PHPixie/HTTP/Responses/Response.php | Response.setStatus | public function setStatus($code, $reasonPhrase = null)
{
$this->statusCode = $code;
$this->reasonPhrase = $reasonPhrase;
} | php | public function setStatus($code, $reasonPhrase = null)
{
$this->statusCode = $code;
$this->reasonPhrase = $reasonPhrase;
} | [
"public",
"function",
"setStatus",
"(",
"$",
"code",
",",
"$",
"reasonPhrase",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"statusCode",
"=",
"$",
"code",
";",
"$",
"this",
"->",
"reasonPhrase",
"=",
"$",
"reasonPhrase",
";",
"}"
] | Set status code and phrase
@param int $code
@param string|null $reasonPhrase | [
"Set",
"status",
"code",
"and",
"phrase"
] | train | https://github.com/PHPixie/HTTP/blob/581c0df452fd07ca4ea0b3e24e8ddee8dddc2912/src/PHPixie/HTTP/Responses/Response.php#L99-L103 |
PHPixie/HTTP | src/PHPixie/HTTP/Responses/Response.php | Response.asResponseMessage | public function asResponseMessage($context = null)
{
return $this->messages->response(
'1.1',
$this->mergeContextHeaders($context),
$this->body,
$this->statusCode,
$this->reasonPhrase
);
} | php | public function asResponseMessage($context = null)
{
return $this->messages->response(
'1.1',
$this->mergeContextHeaders($context),
$this->body,
$this->statusCode,
$this->reasonPhrase
);
} | [
"public",
"function",
"asResponseMessage",
"(",
"$",
"context",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"messages",
"->",
"response",
"(",
"'1.1'",
",",
"$",
"this",
"->",
"mergeContextHeaders",
"(",
"$",
"context",
")",
",",
"$",
"this",
"->... | Get PSR-7 response representation
@param Context|null $context HTTP context
@return ResponseInterface | [
"Get",
"PSR",
"-",
"7",
"response",
"representation"
] | train | https://github.com/PHPixie/HTTP/blob/581c0df452fd07ca4ea0b3e24e8ddee8dddc2912/src/PHPixie/HTTP/Responses/Response.php#L110-L119 |
PHPixie/HTTP | src/PHPixie/HTTP/Responses/Response.php | Response.mergeContextHeaders | protected function mergeContextHeaders($context)
{
$headers = $this->headers->asArray();
if($context === null ) {
return $headers;
}
$cookieUpdates = $context->cookies()->updates();
if(empty($cookieUpdates)) {
return $headers;
}
$cookieHeaders = array();
foreach($cookieUpdates as $update) {
$cookieHeaders[] = $update->asHeader();
}
foreach($headers as $name => $value) {
if(strtolower($name) === 'set-cookie') {
foreach($cookieHeaders as $header) {
$headers[$name][] = $header;
}
return $headers;
}
}
$headers['Set-Cookie'] = $cookieHeaders;
return $headers;
} | php | protected function mergeContextHeaders($context)
{
$headers = $this->headers->asArray();
if($context === null ) {
return $headers;
}
$cookieUpdates = $context->cookies()->updates();
if(empty($cookieUpdates)) {
return $headers;
}
$cookieHeaders = array();
foreach($cookieUpdates as $update) {
$cookieHeaders[] = $update->asHeader();
}
foreach($headers as $name => $value) {
if(strtolower($name) === 'set-cookie') {
foreach($cookieHeaders as $header) {
$headers[$name][] = $header;
}
return $headers;
}
}
$headers['Set-Cookie'] = $cookieHeaders;
return $headers;
} | [
"protected",
"function",
"mergeContextHeaders",
"(",
"$",
"context",
")",
"{",
"$",
"headers",
"=",
"$",
"this",
"->",
"headers",
"->",
"asArray",
"(",
")",
";",
"if",
"(",
"$",
"context",
"===",
"null",
")",
"{",
"return",
"$",
"headers",
";",
"}",
... | Merge headers from HTTP context
@param Context $context
@return array | [
"Merge",
"headers",
"from",
"HTTP",
"context"
] | train | https://github.com/PHPixie/HTTP/blob/581c0df452fd07ca4ea0b3e24e8ddee8dddc2912/src/PHPixie/HTTP/Responses/Response.php#L126-L155 |
qloog/yaf-library | src/Upload/Driver/Local.php | Local.checkSavePath | public function checkSavePath($savepath)
{
/* 检测并创建目录 */
if (!$this->mkdir($savepath)) {
return false;
} else {
/* 检测目录是否可写 */
if (!is_writable($this->rootPath . $savepath)) {
$this->error = '上传目录 ' . $savepath . ' 不可写!';
return false;
} else {
return true;
}
}
} | php | public function checkSavePath($savepath)
{
/* 检测并创建目录 */
if (!$this->mkdir($savepath)) {
return false;
} else {
/* 检测目录是否可写 */
if (!is_writable($this->rootPath . $savepath)) {
$this->error = '上传目录 ' . $savepath . ' 不可写!';
return false;
} else {
return true;
}
}
} | [
"public",
"function",
"checkSavePath",
"(",
"$",
"savepath",
")",
"{",
"/* 检测并创建目录 */",
"if",
"(",
"!",
"$",
"this",
"->",
"mkdir",
"(",
"$",
"savepath",
")",
")",
"{",
"return",
"false",
";",
"}",
"else",
"{",
"/* 检测目录是否可写 */",
"if",
"(",
"!",
"is_wri... | 检测上传目录
@param string $savepath 上传目录
@return boolean 检测结果,true-通过,false-失败 | [
"检测上传目录"
] | train | https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Upload/Driver/Local.php#L48-L63 |
qloog/yaf-library | src/Upload/Driver/Local.php | Local.save | public function save($file, $replace = true)
{
$filename = $this->rootPath . $file['savepath'] . $file['savename'];
/* 不覆盖同名文件 */
if (!$replace && is_file($filename)) {
$this->error = '存在同名文件' . $file['savename'];
return false;
}
/* 移动文件 */
if (!move_uploaded_file($file['tmp_name'], $filename)) {
$this->error = '文件上传保存错误!';
return false;
}
return true;
} | php | public function save($file, $replace = true)
{
$filename = $this->rootPath . $file['savepath'] . $file['savename'];
/* 不覆盖同名文件 */
if (!$replace && is_file($filename)) {
$this->error = '存在同名文件' . $file['savename'];
return false;
}
/* 移动文件 */
if (!move_uploaded_file($file['tmp_name'], $filename)) {
$this->error = '文件上传保存错误!';
return false;
}
return true;
} | [
"public",
"function",
"save",
"(",
"$",
"file",
",",
"$",
"replace",
"=",
"true",
")",
"{",
"$",
"filename",
"=",
"$",
"this",
"->",
"rootPath",
".",
"$",
"file",
"[",
"'savepath'",
"]",
".",
"$",
"file",
"[",
"'savename'",
"]",
";",
"/* 不覆盖同名文件 */",... | 保存指定文件
@param array $file 保存的文件信息
@param boolean $replace 同名文件是否覆盖
@return boolean 保存状态,true-成功,false-失败 | [
"保存指定文件"
] | train | https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Upload/Driver/Local.php#L71-L88 |
qloog/yaf-library | src/Upload/Driver/Local.php | Local.mkdir | public function mkdir($savepath)
{
$dir = $this->rootPath . $savepath;
if (is_dir($dir)) {
return true;
}
if (mkdir($dir, 0777, true)) {
return true;
} else {
$this->error = "目录 {$savepath} 创建失败!";
return false;
}
} | php | public function mkdir($savepath)
{
$dir = $this->rootPath . $savepath;
if (is_dir($dir)) {
return true;
}
if (mkdir($dir, 0777, true)) {
return true;
} else {
$this->error = "目录 {$savepath} 创建失败!";
return false;
}
} | [
"public",
"function",
"mkdir",
"(",
"$",
"savepath",
")",
"{",
"$",
"dir",
"=",
"$",
"this",
"->",
"rootPath",
".",
"$",
"savepath",
";",
"if",
"(",
"is_dir",
"(",
"$",
"dir",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"mkdir",
"(",
... | 创建目录
@param string $savepath 要创建的目录
@return boolean 创建状态,true-成功,false-失败 | [
"创建目录"
] | train | https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Upload/Driver/Local.php#L95-L108 |
browner12/validation | src/Validator.php | Validator.isValid | public function isValid(array $attributes, $rules = 'rules')
{
//validator
$validator = $this->factory->make($attributes, static::${$rules});
//passes validation
if (!$validator->fails()) {
return true;
}
//set errors
$this->errors = $validator->getMessageBag();
//return
return false;
} | php | public function isValid(array $attributes, $rules = 'rules')
{
//validator
$validator = $this->factory->make($attributes, static::${$rules});
//passes validation
if (!$validator->fails()) {
return true;
}
//set errors
$this->errors = $validator->getMessageBag();
//return
return false;
} | [
"public",
"function",
"isValid",
"(",
"array",
"$",
"attributes",
",",
"$",
"rules",
"=",
"'rules'",
")",
"{",
"//validator",
"$",
"validator",
"=",
"$",
"this",
"->",
"factory",
"->",
"make",
"(",
"$",
"attributes",
",",
"static",
"::",
"$",
"{",
"$",... | check if the input is valid
@param array $attributes
@param string $rules
@return bool | [
"check",
"if",
"the",
"input",
"is",
"valid"
] | train | https://github.com/browner12/validation/blob/539a8f1df76c719bf11aceffc9a2d9aaadab72b1/src/Validator.php#L35-L50 |
shpasser/GaeSupport | src/Shpasser/GaeSupport/Mail/GaeMailServiceProvider.php | GaeMailServiceProvider.registerSwiftTransport | protected function registerSwiftTransport($config)
{
switch ($config['driver'])
{
case 'gae':
if (! $this->app->isRunningOnGae()) {
throw new \InvalidArgumentException('Cannot use GaeMailProvider if '.
'not running on Google App Engine.');
}
return $this->registerGaeTransport($config);
default:
return parent::registerSwiftTransport($config);
}
} | php | protected function registerSwiftTransport($config)
{
switch ($config['driver'])
{
case 'gae':
if (! $this->app->isRunningOnGae()) {
throw new \InvalidArgumentException('Cannot use GaeMailProvider if '.
'not running on Google App Engine.');
}
return $this->registerGaeTransport($config);
default:
return parent::registerSwiftTransport($config);
}
} | [
"protected",
"function",
"registerSwiftTransport",
"(",
"$",
"config",
")",
"{",
"switch",
"(",
"$",
"config",
"[",
"'driver'",
"]",
")",
"{",
"case",
"'gae'",
":",
"if",
"(",
"!",
"$",
"this",
"->",
"app",
"->",
"isRunningOnGae",
"(",
")",
")",
"{",
... | Register the Swift Transport instance.
@param array $config
@return void
@throws \InvalidArgumentException | [
"Register",
"the",
"Swift",
"Transport",
"instance",
"."
] | train | https://github.com/shpasser/GaeSupport/blob/7f37f2bf177a4e8f1cbefdf04f49b51016e85ae3/src/Shpasser/GaeSupport/Mail/GaeMailServiceProvider.php#L16-L30 |
smuuf/phpcb | app/core/PhpBenchmark.php | PhpBenchmark.pathToUrl | public static function pathToUrl($path, $protocol = 'http://') {
if (!isset($_SERVER['HTTP_HOST'])) return $path;
// Correct the slash type
$path = str_replace('\\', '/', $path);
// Remove document root directory from the path
$urlPath = str_replace(rtrim($_SERVER['DOCUMENT_ROOT'], '/'), null, $path);
return $protocol . $_SERVER['HTTP_HOST'] . $urlPath;
} | php | public static function pathToUrl($path, $protocol = 'http://') {
if (!isset($_SERVER['HTTP_HOST'])) return $path;
// Correct the slash type
$path = str_replace('\\', '/', $path);
// Remove document root directory from the path
$urlPath = str_replace(rtrim($_SERVER['DOCUMENT_ROOT'], '/'), null, $path);
return $protocol . $_SERVER['HTTP_HOST'] . $urlPath;
} | [
"public",
"static",
"function",
"pathToUrl",
"(",
"$",
"path",
",",
"$",
"protocol",
"=",
"'http://'",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"_SERVER",
"[",
"'HTTP_HOST'",
"]",
")",
")",
"return",
"$",
"path",
";",
"// Correct the slash type",
"$"... | Helpers | [
"Helpers"
] | train | https://github.com/smuuf/phpcb/blob/e32f599c868ba50d5434d33379820a40b739c039/app/core/PhpBenchmark.php#L94-L106 |
smuuf/phpcb | app/core/PhpBenchmark.php | PhpBenchmark.getSourceCode | private function getSourceCode(\Closure $closure) {
$reflection = new \ReflectionFunction($closure);
$file = $reflection->getFileName();
$source = file($file, FILE_IGNORE_NEW_LINES);
$startLine = $reflection->getStartLine();
$endLine = $reflection->getEndLine() - 1;
return implode(
PHP_EOL,
array_slice($source, $startLine, $endLine - $startLine)
);
} | php | private function getSourceCode(\Closure $closure) {
$reflection = new \ReflectionFunction($closure);
$file = $reflection->getFileName();
$source = file($file, FILE_IGNORE_NEW_LINES);
$startLine = $reflection->getStartLine();
$endLine = $reflection->getEndLine() - 1;
return implode(
PHP_EOL,
array_slice($source, $startLine, $endLine - $startLine)
);
} | [
"private",
"function",
"getSourceCode",
"(",
"\\",
"Closure",
"$",
"closure",
")",
"{",
"$",
"reflection",
"=",
"new",
"\\",
"ReflectionFunction",
"(",
"$",
"closure",
")",
";",
"$",
"file",
"=",
"$",
"reflection",
"->",
"getFileName",
"(",
")",
";",
"$"... | Template helpers | [
"Template",
"helpers"
] | train | https://github.com/smuuf/phpcb/blob/e32f599c868ba50d5434d33379820a40b739c039/app/core/PhpBenchmark.php#L110-L125 |
makinacorpus/drupal-ucms | ucms_search/src/NodeIndexerChain.php | NodeIndexerChain.getIndexer | public function getIndexer($index)
{
if (!isset($this->chain[$index])) {
throw new \InvalidArgumentException(sprintf("Indexer for index '%s' is not registered", $index));
}
return $this->chain[$index];
} | php | public function getIndexer($index)
{
if (!isset($this->chain[$index])) {
throw new \InvalidArgumentException(sprintf("Indexer for index '%s' is not registered", $index));
}
return $this->chain[$index];
} | [
"public",
"function",
"getIndexer",
"(",
"$",
"index",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"chain",
"[",
"$",
"index",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"\"Indexer for index ... | Get a single indexer
@param string $index
@return NodeIndexerInterface | [
"Get",
"a",
"single",
"indexer"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/NodeIndexerChain.php#L56-L63 |
makinacorpus/drupal-ucms | ucms_search/src/NodeIndexerChain.php | NodeIndexerChain.bulkDequeue | public function bulkDequeue($limit = null)
{
$count = 0;
foreach ($this->chain as $indexer) {
$count += $indexer->bulkDequeue($limit);
}
return $count;
} | php | public function bulkDequeue($limit = null)
{
$count = 0;
foreach ($this->chain as $indexer) {
$count += $indexer->bulkDequeue($limit);
}
return $count;
} | [
"public",
"function",
"bulkDequeue",
"(",
"$",
"limit",
"=",
"null",
")",
"{",
"$",
"count",
"=",
"0",
";",
"foreach",
"(",
"$",
"this",
"->",
"chain",
"as",
"$",
"indexer",
")",
"{",
"$",
"count",
"+=",
"$",
"indexer",
"->",
"bulkDequeue",
"(",
"$... | {inheritdoc} | [
"{",
"inheritdoc",
"}"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/NodeIndexerChain.php#L88-L97 |
makinacorpus/drupal-ucms | ucms_search/src/NodeIndexerChain.php | NodeIndexerChain.bulkMarkForReindex | public function bulkMarkForReindex($nidList = null)
{
foreach ($this->chain as $indexer) {
$indexer->bulkMarkForReindex($nidList);
}
} | php | public function bulkMarkForReindex($nidList = null)
{
foreach ($this->chain as $indexer) {
$indexer->bulkMarkForReindex($nidList);
}
} | [
"public",
"function",
"bulkMarkForReindex",
"(",
"$",
"nidList",
"=",
"null",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"chain",
"as",
"$",
"indexer",
")",
"{",
"$",
"indexer",
"->",
"bulkMarkForReindex",
"(",
"$",
"nidList",
")",
";",
"}",
"}"
] | {inheritdoc} | [
"{",
"inheritdoc",
"}"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/NodeIndexerChain.php#L102-L107 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.