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 |
|---|---|---|---|---|---|---|---|---|---|---|
makinacorpus/drupal-ucms | ucms_search/src/Aggs/TopHits.php | TopHits.parseResponse | public function parseResponse(Search $search, Response $response, $raw)
{
$name = $this->getAggregationName();
if (!isset($raw['aggregations'][$name])) {
throw new \RuntimeException(sprintf("Aggregation '%s' is missing from response", $name));
}
$this->results = [];
foreach ($raw['aggregations'][$name]['buckets'] as $bucket) {
$this->counts[$bucket['key']] = $bucket['doc_count'];
foreach ($bucket[$this->getAggregationBucketName()]['hits']['hits'] as $data) {
$this->results[$bucket['key']][] = $data['_id'];
}
}
} | php | public function parseResponse(Search $search, Response $response, $raw)
{
$name = $this->getAggregationName();
if (!isset($raw['aggregations'][$name])) {
throw new \RuntimeException(sprintf("Aggregation '%s' is missing from response", $name));
}
$this->results = [];
foreach ($raw['aggregations'][$name]['buckets'] as $bucket) {
$this->counts[$bucket['key']] = $bucket['doc_count'];
foreach ($bucket[$this->getAggregationBucketName()]['hits']['hits'] as $data) {
$this->results[$bucket['key']][] = $data['_id'];
}
}
} | [
"public",
"function",
"parseResponse",
"(",
"Search",
"$",
"search",
",",
"Response",
"$",
"response",
",",
"$",
"raw",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"getAggregationName",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"raw",
"[",... | {@inheritDoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/Aggs/TopHits.php#L141-L157 |
makinacorpus/drupal-ucms | ucms_user/src/EventDispatcher/UserEventSubscriber.php | UserEventSubscriber.onSiteWebmasterCreate | public function onSiteWebmasterCreate(SiteEvent $event)
{
/* @var UserInterface $user */
$user = $this->entityManager->getStorage('user')->load($event->getArgument('webmaster_id'));
if ($user->status == 0) {
$this->tokenManager->sendTokenMail($user, 'ucms_user', 'new-account-disabled');
} else {
$this->tokenManager->sendTokenMail($user, 'ucms_user', 'new-account-enabled');
}
} | php | public function onSiteWebmasterCreate(SiteEvent $event)
{
/* @var UserInterface $user */
$user = $this->entityManager->getStorage('user')->load($event->getArgument('webmaster_id'));
if ($user->status == 0) {
$this->tokenManager->sendTokenMail($user, 'ucms_user', 'new-account-disabled');
} else {
$this->tokenManager->sendTokenMail($user, 'ucms_user', 'new-account-enabled');
}
} | [
"public",
"function",
"onSiteWebmasterCreate",
"(",
"SiteEvent",
"$",
"event",
")",
"{",
"/* @var UserInterface $user */",
"$",
"user",
"=",
"$",
"this",
"->",
"entityManager",
"->",
"getStorage",
"(",
"'user'",
")",
"->",
"load",
"(",
"$",
"event",
"->",
"get... | Act on webmaster or contributor creation.
@param SiteEvent $event | [
"Act",
"on",
"webmaster",
"or",
"contributor",
"creation",
"."
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_user/src/EventDispatcher/UserEventSubscriber.php#L54-L64 |
aginev/acl | src/Http/Controllers/RoleController.php | RoleController.store | public function store(RoleRequest $request)
{
// Create the role
$role = Role::create($request->all());
// Sync permissions
$permission_ids = $request->get('permission_id', []);
$role->permissions()->sync($permission_ids);
return redirect()->action('\Aginev\Acl\Http\Controllers\RoleController@index')
->with('success', trans('acl::role.create.created'));
} | php | public function store(RoleRequest $request)
{
// Create the role
$role = Role::create($request->all());
// Sync permissions
$permission_ids = $request->get('permission_id', []);
$role->permissions()->sync($permission_ids);
return redirect()->action('\Aginev\Acl\Http\Controllers\RoleController@index')
->with('success', trans('acl::role.create.created'));
} | [
"public",
"function",
"store",
"(",
"RoleRequest",
"$",
"request",
")",
"{",
"// Create the role",
"$",
"role",
"=",
"Role",
"::",
"create",
"(",
"$",
"request",
"->",
"all",
"(",
")",
")",
";",
"// Sync permissions",
"$",
"permission_ids",
"=",
"$",
"requ... | Store a newly created resource in storage.
@param RoleRequest $request
@return Response | [
"Store",
"a",
"newly",
"created",
"resource",
"in",
"storage",
"."
] | train | https://github.com/aginev/acl/blob/7dcbe39c0955c3da7487f5d528423dd6e7ac7fd1/src/Http/Controllers/RoleController.php#L43-L54 |
aginev/acl | src/Http/Controllers/RoleController.php | RoleController.edit | public function edit($id)
{
$role = Role::findOrFail($id);
return view('acl::role.edit', [
'role' => $role,
'role_permissions' => $role->permissions->keyBy('id'),
'permissions' => Permission::all()->groupBy('controller')
]);
} | php | public function edit($id)
{
$role = Role::findOrFail($id);
return view('acl::role.edit', [
'role' => $role,
'role_permissions' => $role->permissions->keyBy('id'),
'permissions' => Permission::all()->groupBy('controller')
]);
} | [
"public",
"function",
"edit",
"(",
"$",
"id",
")",
"{",
"$",
"role",
"=",
"Role",
"::",
"findOrFail",
"(",
"$",
"id",
")",
";",
"return",
"view",
"(",
"'acl::role.edit'",
",",
"[",
"'role'",
"=>",
"$",
"role",
",",
"'role_permissions'",
"=>",
"$",
"r... | Show the form for editing the specified resource.
@param int $id
@return Response | [
"Show",
"the",
"form",
"for",
"editing",
"the",
"specified",
"resource",
"."
] | train | https://github.com/aginev/acl/blob/7dcbe39c0955c3da7487f5d528423dd6e7ac7fd1/src/Http/Controllers/RoleController.php#L75-L84 |
aginev/acl | src/Http/Controllers/RoleController.php | RoleController.update | public function update($id, RoleRequest $request)
{
// Update the role
$role = Role::findOrFail($id);
$role->update($request->all());
// Sync permissions
$permission_ids = $request->get('permission_id', []);
$role->permissions()->sync($permission_ids);
return redirect()->action('\Aginev\Acl\Http\Controllers\RoleController@index')
->with('success', trans('acl::role.edit.updated'));
} | php | public function update($id, RoleRequest $request)
{
// Update the role
$role = Role::findOrFail($id);
$role->update($request->all());
// Sync permissions
$permission_ids = $request->get('permission_id', []);
$role->permissions()->sync($permission_ids);
return redirect()->action('\Aginev\Acl\Http\Controllers\RoleController@index')
->with('success', trans('acl::role.edit.updated'));
} | [
"public",
"function",
"update",
"(",
"$",
"id",
",",
"RoleRequest",
"$",
"request",
")",
"{",
"// Update the role",
"$",
"role",
"=",
"Role",
"::",
"findOrFail",
"(",
"$",
"id",
")",
";",
"$",
"role",
"->",
"update",
"(",
"$",
"request",
"->",
"all",
... | Update the specified resource in storage.
@param int $id
@param RoleRequest $request
@return Response | [
"Update",
"the",
"specified",
"resource",
"in",
"storage",
"."
] | train | https://github.com/aginev/acl/blob/7dcbe39c0955c3da7487f5d528423dd6e7ac7fd1/src/Http/Controllers/RoleController.php#L94-L106 |
aginev/acl | src/Http/Controllers/RoleController.php | RoleController.destroy | public function destroy($id)
{
// Get the first permission that is not this one that we are trying to delete
$default_permission = Role::findOrFail(1);
// Build users model based on Auth config model
$user_model = config('auth.model');
// Update all the users that have this role. Assign them the default role.
$user_model::where('role_id', '=', $id)
->update(['role_id' => $default_permission->id]);
// Delete the requested role.
$role = Role::findOrFail($id);
$role->delete();
return redirect()->action('\Aginev\Acl\Http\Controllers\RoleController@index')
->with('success', trans('acl::role.destroy.deleted'));
} | php | public function destroy($id)
{
// Get the first permission that is not this one that we are trying to delete
$default_permission = Role::findOrFail(1);
// Build users model based on Auth config model
$user_model = config('auth.model');
// Update all the users that have this role. Assign them the default role.
$user_model::where('role_id', '=', $id)
->update(['role_id' => $default_permission->id]);
// Delete the requested role.
$role = Role::findOrFail($id);
$role->delete();
return redirect()->action('\Aginev\Acl\Http\Controllers\RoleController@index')
->with('success', trans('acl::role.destroy.deleted'));
} | [
"public",
"function",
"destroy",
"(",
"$",
"id",
")",
"{",
"// Get the first permission that is not this one that we are trying to delete",
"$",
"default_permission",
"=",
"Role",
"::",
"findOrFail",
"(",
"1",
")",
";",
"// Build users model based on Auth config model",
"$",
... | Remove the specified resource from storage.
@param int $id
@return Response | [
"Remove",
"the",
"specified",
"resource",
"from",
"storage",
"."
] | train | https://github.com/aginev/acl/blob/7dcbe39c0955c3da7487f5d528423dd6e7ac7fd1/src/Http/Controllers/RoleController.php#L115-L132 |
qloog/yaf-library | src/Views/Block.php | Block.begin | public function begin($name, $type = 'replace')
{
$stacks = [$name, $type];
if (!isset($this->opens[$name])) {
$stacks[] = $this->placeholder($name);
} elseif ($this->opens[$name]) {
throw new BlockException($name, 'is opened');
}
$this->opens[$name] = true;
$this->stacks[] = $stacks;
ob_start();
} | php | public function begin($name, $type = 'replace')
{
$stacks = [$name, $type];
if (!isset($this->opens[$name])) {
$stacks[] = $this->placeholder($name);
} elseif ($this->opens[$name]) {
throw new BlockException($name, 'is opened');
}
$this->opens[$name] = true;
$this->stacks[] = $stacks;
ob_start();
} | [
"public",
"function",
"begin",
"(",
"$",
"name",
",",
"$",
"type",
"=",
"'replace'",
")",
"{",
"$",
"stacks",
"=",
"[",
"$",
"name",
",",
"$",
"type",
"]",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"opens",
"[",
"$",
"name",
"]",
... | 模板块开始
@param string $name
@param string $type
@throws BlockException | [
"模板块开始"
] | train | https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Views/Block.php#L47-L59 |
qloog/yaf-library | src/Views/Block.php | Block.parent | public function parent($name)
{
$placeholder = $this->placeholder($name);
return isset($this->blocks[$placeholder]) ? $this->blocks[$placeholder] : '';
} | php | public function parent($name)
{
$placeholder = $this->placeholder($name);
return isset($this->blocks[$placeholder]) ? $this->blocks[$placeholder] : '';
} | [
"public",
"function",
"parent",
"(",
"$",
"name",
")",
"{",
"$",
"placeholder",
"=",
"$",
"this",
"->",
"placeholder",
"(",
"$",
"name",
")",
";",
"return",
"isset",
"(",
"$",
"this",
"->",
"blocks",
"[",
"$",
"placeholder",
"]",
")",
"?",
"$",
"th... | 获取指定父块的内容
@param $name
@return string | [
"获取指定父块的内容"
] | train | https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Views/Block.php#L67-L71 |
qloog/yaf-library | src/Views/Block.php | Block.end | public function end($name)
{
$this->lastOpen = null;
$this->opens[$name] = false;
$last = array_pop($this->stacks);
if ($last[0] != $name) {
throw new BlockException($name, "is unexpected, expected {$last[0]}");
}
$content = ob_get_clean();
if (!isset($this->hasChild[$name])) {
$content = $this->_replace($content);
}
$pre = count($this->stacks) - 1;
if ($pre > -1 && $this->opens[$this->stacks[$pre][0]]) {
$this->hasChild[$this->stacks[$pre][0]] = true;
}
switch ($last[1]) {
case 'replace' : // 默认
break;
case 'append' : // 追加
$content = $this->parent($name) . $content;
break;
case 'prepend' : // 前面增加
$content .= $this->parent($name);
break;
case 'hide' : // 不存在就隐藏
if (!isset($this->blocks[$name])) {
$content = '';
}
break;
default :
throw new BlockException($name, 'undefined action type');
}
$this->blocks[$this->placeholder($name)] = $content;
// 输出占位符
if (isset($last[2])) {
echo $last[2];
}
} | php | public function end($name)
{
$this->lastOpen = null;
$this->opens[$name] = false;
$last = array_pop($this->stacks);
if ($last[0] != $name) {
throw new BlockException($name, "is unexpected, expected {$last[0]}");
}
$content = ob_get_clean();
if (!isset($this->hasChild[$name])) {
$content = $this->_replace($content);
}
$pre = count($this->stacks) - 1;
if ($pre > -1 && $this->opens[$this->stacks[$pre][0]]) {
$this->hasChild[$this->stacks[$pre][0]] = true;
}
switch ($last[1]) {
case 'replace' : // 默认
break;
case 'append' : // 追加
$content = $this->parent($name) . $content;
break;
case 'prepend' : // 前面增加
$content .= $this->parent($name);
break;
case 'hide' : // 不存在就隐藏
if (!isset($this->blocks[$name])) {
$content = '';
}
break;
default :
throw new BlockException($name, 'undefined action type');
}
$this->blocks[$this->placeholder($name)] = $content;
// 输出占位符
if (isset($last[2])) {
echo $last[2];
}
} | [
"public",
"function",
"end",
"(",
"$",
"name",
")",
"{",
"$",
"this",
"->",
"lastOpen",
"=",
"null",
";",
"$",
"this",
"->",
"opens",
"[",
"$",
"name",
"]",
"=",
"false",
";",
"$",
"last",
"=",
"array_pop",
"(",
"$",
"this",
"->",
"stacks",
")",
... | 结束一个块
@param $name
@throws BlockException | [
"结束一个块"
] | train | https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Views/Block.php#L79-L123 |
qloog/yaf-library | src/Views/Block.php | Block._replace | protected function _replace($content)
{
$content = trim($content, "\r\n ");
if (!$this->blocks) {
return $content;
}
return strtr($content, $this->blocks);
} | php | protected function _replace($content)
{
$content = trim($content, "\r\n ");
if (!$this->blocks) {
return $content;
}
return strtr($content, $this->blocks);
} | [
"protected",
"function",
"_replace",
"(",
"$",
"content",
")",
"{",
"$",
"content",
"=",
"trim",
"(",
"$",
"content",
",",
"\"\\r\\n \"",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"blocks",
")",
"{",
"return",
"$",
"content",
";",
"}",
"return",
... | 替换里面的块占位符
@param $content
@return mixed | [
"替换里面的块占位符"
] | train | https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Views/Block.php#L131-L139 |
qloog/yaf-library | src/Views/Block.php | Block.replace | public function replace($content)
{
foreach ($this->hasChild as $name => $value) {
$name = $this->placeholder($name);
$this->blocks[$name] = $this->_replace($this->blocks[$name]);
}
return $this->_replace($content);
} | php | public function replace($content)
{
foreach ($this->hasChild as $name => $value) {
$name = $this->placeholder($name);
$this->blocks[$name] = $this->_replace($this->blocks[$name]);
}
return $this->_replace($content);
} | [
"public",
"function",
"replace",
"(",
"$",
"content",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"hasChild",
"as",
"$",
"name",
"=>",
"$",
"value",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"placeholder",
"(",
"$",
"name",
")",
";",
"$",
"... | 替换里面的块所有占位符
@param $content
@return mixed | [
"替换里面的块所有占位符"
] | train | https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Views/Block.php#L147-L155 |
isfonzar/sentiment-thermometer | src/Providers/SocialNetworks/TwitterProvider.php | TwitterProvider.getByKeyword | public function getByKeyword($keyword)
{
$results = $this->twitterProvider->get("search/tweets", [
"q" => $keyword,
"result_type" => $this->type,
"count" => $this->amount,
]);
return $this->processResults($results);
} | php | public function getByKeyword($keyword)
{
$results = $this->twitterProvider->get("search/tweets", [
"q" => $keyword,
"result_type" => $this->type,
"count" => $this->amount,
]);
return $this->processResults($results);
} | [
"public",
"function",
"getByKeyword",
"(",
"$",
"keyword",
")",
"{",
"$",
"results",
"=",
"$",
"this",
"->",
"twitterProvider",
"->",
"get",
"(",
"\"search/tweets\"",
",",
"[",
"\"q\"",
"=>",
"$",
"keyword",
",",
"\"result_type\"",
"=>",
"$",
"this",
"->",... | @param $keyword
@return array | [
"@param",
"$keyword"
] | train | https://github.com/isfonzar/sentiment-thermometer/blob/457bf2b0b1e6bd287b069f32f8decb77dc5d59fc/src/Providers/SocialNetworks/TwitterProvider.php#L61-L70 |
isfonzar/sentiment-thermometer | src/Providers/SocialNetworks/TwitterProvider.php | TwitterProvider.processResults | private function processResults($results)
{
if (!empty($results->errors))
{
throw new ErrorFetchingTwitter();
}
$response = [];
foreach ($results->statuses as $tweet)
{
$response[] = $tweet->text;
}
return $response;
} | php | private function processResults($results)
{
if (!empty($results->errors))
{
throw new ErrorFetchingTwitter();
}
$response = [];
foreach ($results->statuses as $tweet)
{
$response[] = $tweet->text;
}
return $response;
} | [
"private",
"function",
"processResults",
"(",
"$",
"results",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"results",
"->",
"errors",
")",
")",
"{",
"throw",
"new",
"ErrorFetchingTwitter",
"(",
")",
";",
"}",
"$",
"response",
"=",
"[",
"]",
";",
"for... | @param $results
@return array
@throws \iiiicaro\SentimentThermometer\Providers\Exceptions\ErrorFetchingTwitter | [
"@param",
"$results"
] | train | https://github.com/isfonzar/sentiment-thermometer/blob/457bf2b0b1e6bd287b069f32f8decb77dc5d59fc/src/Providers/SocialNetworks/TwitterProvider.php#L78-L93 |
despark/ignicms | src/Admin/Traits/UploadImagesTrait.php | UploadImagesTrait.saveImages | public function saveImages()
{
$imageFields = $this->getImageFields();
$currentUploadDir = $this->getCurrentUploadDir();
foreach ($imageFields as $imageFieldName => $options) {
if (array_get($this->attributes, $imageFieldName) instanceof UploadedFile) {
$file = Request::file($imageFieldName);
$filename = $file->getClientOriginalName();
$file->move($this->getThumbnailPath('original'), $filename);
foreach ($options['thumbnails'] as $thumbnailName => $thumbnailOptions) {
$image = Image::make($this->getThumbnailPath('original').$filename);
$resizeType = array_get($thumbnailOptions, 'type', 'crop');
switch ($resizeType) {
case 'crop':
$image->fit($thumbnailOptions['width'], $thumbnailOptions['height']);
break;
case 'resize':
$image->resize($thumbnailOptions['width'], $thumbnailOptions['height'],
function ($constraint) {
$constraint->aspectRatio();
});
break;
}
$thumbnailPath = $this->getThumbnailPath($thumbnailName);
if (! File::isDirectory($thumbnailPath)) {
File::makeDirectory($thumbnailPath);
}
$image->save($thumbnailPath.$filename);
}
$this->attributes[$imageFieldName] = $filename;
} elseif ($this->original) {
$this->attributes[$imageFieldName] = $this->original[$imageFieldName];
}
}
} | php | public function saveImages()
{
$imageFields = $this->getImageFields();
$currentUploadDir = $this->getCurrentUploadDir();
foreach ($imageFields as $imageFieldName => $options) {
if (array_get($this->attributes, $imageFieldName) instanceof UploadedFile) {
$file = Request::file($imageFieldName);
$filename = $file->getClientOriginalName();
$file->move($this->getThumbnailPath('original'), $filename);
foreach ($options['thumbnails'] as $thumbnailName => $thumbnailOptions) {
$image = Image::make($this->getThumbnailPath('original').$filename);
$resizeType = array_get($thumbnailOptions, 'type', 'crop');
switch ($resizeType) {
case 'crop':
$image->fit($thumbnailOptions['width'], $thumbnailOptions['height']);
break;
case 'resize':
$image->resize($thumbnailOptions['width'], $thumbnailOptions['height'],
function ($constraint) {
$constraint->aspectRatio();
});
break;
}
$thumbnailPath = $this->getThumbnailPath($thumbnailName);
if (! File::isDirectory($thumbnailPath)) {
File::makeDirectory($thumbnailPath);
}
$image->save($thumbnailPath.$filename);
}
$this->attributes[$imageFieldName] = $filename;
} elseif ($this->original) {
$this->attributes[$imageFieldName] = $this->original[$imageFieldName];
}
}
} | [
"public",
"function",
"saveImages",
"(",
")",
"{",
"$",
"imageFields",
"=",
"$",
"this",
"->",
"getImageFields",
"(",
")",
";",
"$",
"currentUploadDir",
"=",
"$",
"this",
"->",
"getCurrentUploadDir",
"(",
")",
";",
"foreach",
"(",
"$",
"imageFields",
"as",... | Save Image. | [
"Save",
"Image",
"."
] | train | https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/src/Admin/Traits/UploadImagesTrait.php#L24-L69 |
TYPO3-Console/typo3-console-plugin | src/IncludeFile.php | IncludeFile.getIncludeFileContent | protected function getIncludeFileContent(): string
{
$includeFileTemplate = $this->filesystem->normalizePath(__DIR__ . '/../' . self::INCLUDE_FILE_TEMPLATE);
$includeFileContent = file_get_contents($includeFileTemplate);
foreach ($this->tokens as $token) {
$includeFileContent = self::replaceToken($token->getName(), $token->getContent(), $includeFileContent);
}
return $includeFileContent;
} | php | protected function getIncludeFileContent(): string
{
$includeFileTemplate = $this->filesystem->normalizePath(__DIR__ . '/../' . self::INCLUDE_FILE_TEMPLATE);
$includeFileContent = file_get_contents($includeFileTemplate);
foreach ($this->tokens as $token) {
$includeFileContent = self::replaceToken($token->getName(), $token->getContent(), $includeFileContent);
}
return $includeFileContent;
} | [
"protected",
"function",
"getIncludeFileContent",
"(",
")",
":",
"string",
"{",
"$",
"includeFileTemplate",
"=",
"$",
"this",
"->",
"filesystem",
"->",
"normalizePath",
"(",
"__DIR__",
".",
"'/../'",
".",
"self",
"::",
"INCLUDE_FILE_TEMPLATE",
")",
";",
"$",
"... | Constructs the include file content
@throws \RuntimeException
@throws \InvalidArgumentException
@return string | [
"Constructs",
"the",
"include",
"file",
"content"
] | train | https://github.com/TYPO3-Console/typo3-console-plugin/blob/4a80b494adb97306bb19a14c72c214be79b5b079/src/IncludeFile.php#L85-L93 |
makinacorpus/drupal-ucms | ucms_site/src/GroupManager.php | GroupManager.dispatch | private function dispatch(Group $group, $event, $data = [], $userId = null)
{
if (!$this->dispatcher) {
return;
}
$this->dispatcher->dispatch('group:' . $event, new GroupEvent($group, $userId, $data));
} | php | private function dispatch(Group $group, $event, $data = [], $userId = null)
{
if (!$this->dispatcher) {
return;
}
$this->dispatcher->dispatch('group:' . $event, new GroupEvent($group, $userId, $data));
} | [
"private",
"function",
"dispatch",
"(",
"Group",
"$",
"group",
",",
"$",
"event",
",",
"$",
"data",
"=",
"[",
"]",
",",
"$",
"userId",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"dispatcher",
")",
"{",
"return",
";",
"}",
"$",
"t... | Dispatch an event
@param Group $group
@param string $event
@param string $data
@param int $userId | [
"Dispatch",
"an",
"event"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/GroupManager.php#L33-L40 |
makinacorpus/drupal-ucms | ucms_site/src/GroupManager.php | GroupManager.loadGroupsFrom | public function loadGroupsFrom(array $items = [], $withAccess = false)
{
$idList = [];
foreach ($items as $item) {
if (is_numeric($item)) {
$groupId = (int)$item;
} else if ($item instanceof GroupMember) {
$groupId = $item->getGroupId();
} else if ($item instanceof GroupSite) {
$groupId = $item->getGroupId();
} else {
throw new \InvalidArgumentException(sprintf("given input is nor an integer nor a %s nor %s instance", GroupMember::class, GroupSite::class));
}
// Avoid duplicates
$idList[$groupId] = $groupId;
}
if (!$idList) {
return [];
}
return $this->loadAll($idList, $withAccess);
} | php | public function loadGroupsFrom(array $items = [], $withAccess = false)
{
$idList = [];
foreach ($items as $item) {
if (is_numeric($item)) {
$groupId = (int)$item;
} else if ($item instanceof GroupMember) {
$groupId = $item->getGroupId();
} else if ($item instanceof GroupSite) {
$groupId = $item->getGroupId();
} else {
throw new \InvalidArgumentException(sprintf("given input is nor an integer nor a %s nor %s instance", GroupMember::class, GroupSite::class));
}
// Avoid duplicates
$idList[$groupId] = $groupId;
}
if (!$idList) {
return [];
}
return $this->loadAll($idList, $withAccess);
} | [
"public",
"function",
"loadGroupsFrom",
"(",
"array",
"$",
"items",
"=",
"[",
"]",
",",
"$",
"withAccess",
"=",
"false",
")",
"{",
"$",
"idList",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"items",
"as",
"$",
"item",
")",
"{",
"if",
"(",
"is_numeric"... | Load groups from
@param int[]|GroupSite|GroupMember[] $items
@param bool $withAccess
@return Group[] | [
"Load",
"groups",
"from"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/GroupManager.php#L50-L73 |
makinacorpus/drupal-ucms | ucms_site/src/GroupManager.php | GroupManager.findOne | public function findOne($id)
{
$group = $this
->database
->query(
"SELECT * FROM {ucms_group} WHERE id = :id LIMIT 1 OFFSET 0",
[':id' => $id]
)
->fetchObject(Group::class)
;
if (!$group) {
throw new \InvalidArgumentException("Group does not exists");
}
return $group;
} | php | public function findOne($id)
{
$group = $this
->database
->query(
"SELECT * FROM {ucms_group} WHERE id = :id LIMIT 1 OFFSET 0",
[':id' => $id]
)
->fetchObject(Group::class)
;
if (!$group) {
throw new \InvalidArgumentException("Group does not exists");
}
return $group;
} | [
"public",
"function",
"findOne",
"(",
"$",
"id",
")",
"{",
"$",
"group",
"=",
"$",
"this",
"->",
"database",
"->",
"query",
"(",
"\"SELECT * FROM {ucms_group} WHERE id = :id LIMIT 1 OFFSET 0\"",
",",
"[",
"':id'",
"=>",
"$",
"id",
"]",
")",
"->",
"fetchObject"... | Load group by identifier
@param int $id
@return Group
@throws \InvalidArgumentException | [
"Load",
"group",
"by",
"identifier"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/GroupManager.php#L84-L100 |
makinacorpus/drupal-ucms | ucms_site/src/GroupManager.php | GroupManager.loadAll | public function loadAll($idList = [], $withAccess = true)
{
$ret = [];
if (empty($idList)) {
return $ret;
}
$q = $this
->database
->select('ucms_group', 'g')
;
if ($withAccess) {
$q->addTag('ucms_group_access');
}
$groups = $q
->fields('g')
->condition('g.id', $idList)
->execute()
->fetchAll(\PDO::FETCH_CLASS, Group::class)
;
// Ensure order is the same
// FIXME: find a better way
$sort = [];
foreach ($groups as $group) {
$sort[$group->getId()] = $group;
}
foreach ($idList as $id) {
if (isset($sort[$id])) {
$ret[$id] = $sort[$id];
}
}
return $ret;
} | php | public function loadAll($idList = [], $withAccess = true)
{
$ret = [];
if (empty($idList)) {
return $ret;
}
$q = $this
->database
->select('ucms_group', 'g')
;
if ($withAccess) {
$q->addTag('ucms_group_access');
}
$groups = $q
->fields('g')
->condition('g.id', $idList)
->execute()
->fetchAll(\PDO::FETCH_CLASS, Group::class)
;
// Ensure order is the same
// FIXME: find a better way
$sort = [];
foreach ($groups as $group) {
$sort[$group->getId()] = $group;
}
foreach ($idList as $id) {
if (isset($sort[$id])) {
$ret[$id] = $sort[$id];
}
}
return $ret;
} | [
"public",
"function",
"loadAll",
"(",
"$",
"idList",
"=",
"[",
"]",
",",
"$",
"withAccess",
"=",
"true",
")",
"{",
"$",
"ret",
"=",
"[",
"]",
";",
"if",
"(",
"empty",
"(",
"$",
"idList",
")",
")",
"{",
"return",
"$",
"ret",
";",
"}",
"$",
"q"... | Load all groups from the given identifiers
@param array $idList
@param string $withAccess
@return Group[] | [
"Load",
"all",
"groups",
"from",
"the",
"given",
"identifiers"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/GroupManager.php#L110-L147 |
makinacorpus/drupal-ucms | ucms_site/src/GroupManager.php | GroupManager.save | public function save(Group $group, array $fields = null, $userId = null)
{
$eligible = [
'title',
'is_ghost',
'is_meta',
'ts_created',
'ts_changed',
'attributes',
];
if (null === $fields) {
$fields = $eligible;
} else {
$fields = array_intersect($eligible, $fields);
}
$values = [];
foreach ($fields as $field) {
switch ($field) {
case 'attributes':
$attributes = $group->getAttributes();
if (empty($attributes)) {
$values[$field] = null;
} else {
$values[$field] = serialize($attributes);
}
break;
case 'is_ghost':
$values['is_ghost'] = (int)$group->isGhost();
break;
case 'is_meta':
$values['is_meta'] = (int)$group->isMeta();
break;
default:
$values[$field] = $group->{$field}; // @todo uses __get() fixme
}
}
$values['ts_changed'] = $group->touch()->format('Y-m-d H:i:s');
if ($group->getId()) {
$this->dispatch($group, 'preSave', [], $userId);
$this
->database
->merge('ucms_group')
->key(['id' => $group->getId()])
->fields($values)
->execute()
;
$this->dispatch($group, 'save', [], $userId);
} else {
$this->dispatch($group, 'preCreate', [], $userId);
$values['ts_created'] = $values['ts_changed'];
$id = $this
->database
->insert('ucms_group')
->fields($values)
->execute()
;
$group->setId($id);
$this->dispatch($group, 'create', [], $userId);
}
} | php | public function save(Group $group, array $fields = null, $userId = null)
{
$eligible = [
'title',
'is_ghost',
'is_meta',
'ts_created',
'ts_changed',
'attributes',
];
if (null === $fields) {
$fields = $eligible;
} else {
$fields = array_intersect($eligible, $fields);
}
$values = [];
foreach ($fields as $field) {
switch ($field) {
case 'attributes':
$attributes = $group->getAttributes();
if (empty($attributes)) {
$values[$field] = null;
} else {
$values[$field] = serialize($attributes);
}
break;
case 'is_ghost':
$values['is_ghost'] = (int)$group->isGhost();
break;
case 'is_meta':
$values['is_meta'] = (int)$group->isMeta();
break;
default:
$values[$field] = $group->{$field}; // @todo uses __get() fixme
}
}
$values['ts_changed'] = $group->touch()->format('Y-m-d H:i:s');
if ($group->getId()) {
$this->dispatch($group, 'preSave', [], $userId);
$this
->database
->merge('ucms_group')
->key(['id' => $group->getId()])
->fields($values)
->execute()
;
$this->dispatch($group, 'save', [], $userId);
} else {
$this->dispatch($group, 'preCreate', [], $userId);
$values['ts_created'] = $values['ts_changed'];
$id = $this
->database
->insert('ucms_group')
->fields($values)
->execute()
;
$group->setId($id);
$this->dispatch($group, 'create', [], $userId);
}
} | [
"public",
"function",
"save",
"(",
"Group",
"$",
"group",
",",
"array",
"$",
"fields",
"=",
"null",
",",
"$",
"userId",
"=",
"null",
")",
"{",
"$",
"eligible",
"=",
"[",
"'title'",
",",
"'is_ghost'",
",",
"'is_meta'",
",",
"'ts_created'",
",",
"'ts_cha... | Save given group
If the given group has no identifier, its identifier will be set
@param Group $group
@param array $fields
If set, update only the given fields
@param int $userId
Who did this! | [
"Save",
"given",
"group"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/GroupManager.php#L160-L233 |
makinacorpus/drupal-ucms | ucms_site/src/GroupManager.php | GroupManager.delete | public function delete(Group $group, $userId = null)
{
$this->dispatch($group, 'preDelete', [], $userId);
$this->database->delete('ucms_group')->condition('id', $group->getId())->execute();
$this->dispatch($group, 'delete', [], $userId);
} | php | public function delete(Group $group, $userId = null)
{
$this->dispatch($group, 'preDelete', [], $userId);
$this->database->delete('ucms_group')->condition('id', $group->getId())->execute();
$this->dispatch($group, 'delete', [], $userId);
} | [
"public",
"function",
"delete",
"(",
"Group",
"$",
"group",
",",
"$",
"userId",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"dispatch",
"(",
"$",
"group",
",",
"'preDelete'",
",",
"[",
"]",
",",
"$",
"userId",
")",
";",
"$",
"this",
"->",
"database",... | Delete the given group
@param Group $group
@param int $userId
Who did this! | [
"Delete",
"the",
"given",
"group"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/GroupManager.php#L242-L249 |
makinacorpus/drupal-ucms | ucms_site/src/GroupManager.php | GroupManager.touch | public function touch($groupId)
{
$now = new \DateTime();
$this
->database
->query(
"UPDATE {ucms_group} SET ts_changed = :time WHERE id = :id",
[':time' => $now->format('Y-m-d H:i:s'), ':id' => $groupId]
)
;
} | php | public function touch($groupId)
{
$now = new \DateTime();
$this
->database
->query(
"UPDATE {ucms_group} SET ts_changed = :time WHERE id = :id",
[':time' => $now->format('Y-m-d H:i:s'), ':id' => $groupId]
)
;
} | [
"public",
"function",
"touch",
"(",
"$",
"groupId",
")",
"{",
"$",
"now",
"=",
"new",
"\\",
"DateTime",
"(",
")",
";",
"$",
"this",
"->",
"database",
"->",
"query",
"(",
"\"UPDATE {ucms_group} SET ts_changed = :time WHERE id = :id\"",
",",
"[",
"':time'",
"=>"... | Touch (flag as modified, no other modifications) a group
@param int $groupId | [
"Touch",
"(",
"flag",
"as",
"modified",
"no",
"other",
"modifications",
")",
"a",
"group"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/GroupManager.php#L256-L267 |
makinacorpus/drupal-ucms | ucms_site/src/GroupManager.php | GroupManager.getSiteGroup | public function getSiteGroup(Site $site)
{
$groupId = $site->getGroupId();
if ($groupId) {
return $this->findOne($groupId);
}
} | php | public function getSiteGroup(Site $site)
{
$groupId = $site->getGroupId();
if ($groupId) {
return $this->findOne($groupId);
}
} | [
"public",
"function",
"getSiteGroup",
"(",
"Site",
"$",
"site",
")",
"{",
"$",
"groupId",
"=",
"$",
"site",
"->",
"getGroupId",
"(",
")",
";",
"if",
"(",
"$",
"groupId",
")",
"{",
"return",
"$",
"this",
"->",
"findOne",
"(",
"$",
"groupId",
")",
";... | Get site groups
@param Site $site
@return Group | [
"Get",
"site",
"groups"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/GroupManager.php#L284-L291 |
makinacorpus/drupal-ucms | ucms_site/src/GroupManager.php | GroupManager.addSite | public function addSite($groupId, $siteId, $allowChange = false)
{
$ret = false;
$currentGroupId = (int)$this
->database
->query(
"SELECT group_id FROM {ucms_site} WHERE id = :site",
[':site' => $siteId]
)
->fetchField()
;
if (!$allowChange && $currentGroupId && $currentGroupId !== (int)$groupId) {
throw new GroupMoveDisallowedException("site group change is not allowed");
}
if ($currentGroupId !== (int)$groupId) {
$this
->database
->query(
"UPDATE {ucms_site} SET group_id = :group WHERE id = :site",
[':site' => $siteId, ':group' => $groupId]
)
;
$ret = true;
}
$this->touch($groupId);
// @todo dispatch event
return $ret;
} | php | public function addSite($groupId, $siteId, $allowChange = false)
{
$ret = false;
$currentGroupId = (int)$this
->database
->query(
"SELECT group_id FROM {ucms_site} WHERE id = :site",
[':site' => $siteId]
)
->fetchField()
;
if (!$allowChange && $currentGroupId && $currentGroupId !== (int)$groupId) {
throw new GroupMoveDisallowedException("site group change is not allowed");
}
if ($currentGroupId !== (int)$groupId) {
$this
->database
->query(
"UPDATE {ucms_site} SET group_id = :group WHERE id = :site",
[':site' => $siteId, ':group' => $groupId]
)
;
$ret = true;
}
$this->touch($groupId);
// @todo dispatch event
return $ret;
} | [
"public",
"function",
"addSite",
"(",
"$",
"groupId",
",",
"$",
"siteId",
",",
"$",
"allowChange",
"=",
"false",
")",
"{",
"$",
"ret",
"=",
"false",
";",
"$",
"currentGroupId",
"=",
"(",
"int",
")",
"$",
"this",
"->",
"database",
"->",
"query",
"(",
... | Add site to group
@param int $groupId
@param int $siteId
@param boolean $allowChange
If set to false and site does already belong to a group, throw
an exception
@return bool
True if user was really added, false if site is already in group | [
"Add",
"site",
"to",
"group"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/GroupManager.php#L305-L339 |
makinacorpus/drupal-ucms | ucms_site/src/GroupManager.php | GroupManager.removeSite | public function removeSite($groupId, $siteId)
{
$currentGroupId = (int)$this
->database
->query(
"SELECT group_id FROM {ucms_site} WHERE id = :site",
[':site' => $siteId]
)
->fetchField()
;
if ($currentGroupId !== (int)$groupId) {
throw new GroupMoveDisallowedException(sprintf("%s site is not in group %s", $siteId, $groupId));
}
$this
->database
->query(
"UPDATE {ucms_site} SET group_id = NULL WHERE id = :site",
[':site' => $siteId]
)
;
// @todo dispatch event
$this->touch($groupId);
} | php | public function removeSite($groupId, $siteId)
{
$currentGroupId = (int)$this
->database
->query(
"SELECT group_id FROM {ucms_site} WHERE id = :site",
[':site' => $siteId]
)
->fetchField()
;
if ($currentGroupId !== (int)$groupId) {
throw new GroupMoveDisallowedException(sprintf("%s site is not in group %s", $siteId, $groupId));
}
$this
->database
->query(
"UPDATE {ucms_site} SET group_id = NULL WHERE id = :site",
[':site' => $siteId]
)
;
// @todo dispatch event
$this->touch($groupId);
} | [
"public",
"function",
"removeSite",
"(",
"$",
"groupId",
",",
"$",
"siteId",
")",
"{",
"$",
"currentGroupId",
"=",
"(",
"int",
")",
"$",
"this",
"->",
"database",
"->",
"query",
"(",
"\"SELECT group_id FROM {ucms_site} WHERE id = :site\"",
",",
"[",
"':site'",
... | Remote site from group
@param int $groupId
@param int $siteId | [
"Remote",
"site",
"from",
"group"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/GroupManager.php#L347-L373 |
makinacorpus/drupal-ucms | ucms_site/src/GroupManager.php | GroupManager.userIsMember | public function userIsMember(AccountInterface $account, Group $group)
{
// @todo fix this, cache that
return (bool)$this
->database
->query(
"SELECT 1 FROM {ucms_group_access} WHERE group_id = :group AND user_id = :user",
[':group' => $group->getId(), ':user' => $account->id()]
)
->fetchField()
;
} | php | public function userIsMember(AccountInterface $account, Group $group)
{
// @todo fix this, cache that
return (bool)$this
->database
->query(
"SELECT 1 FROM {ucms_group_access} WHERE group_id = :group AND user_id = :user",
[':group' => $group->getId(), ':user' => $account->id()]
)
->fetchField()
;
} | [
"public",
"function",
"userIsMember",
"(",
"AccountInterface",
"$",
"account",
",",
"Group",
"$",
"group",
")",
"{",
"// @todo fix this, cache that",
"return",
"(",
"bool",
")",
"$",
"this",
"->",
"database",
"->",
"query",
"(",
"\"SELECT 1 FROM {ucms_group_access} ... | Is user member of the given group
@param AccountInterface $account
@param Group $group
@return bool | [
"Is",
"user",
"member",
"of",
"the",
"given",
"group"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/GroupManager.php#L383-L394 |
makinacorpus/drupal-ucms | ucms_site/src/GroupManager.php | GroupManager.getUserGroups | public function getUserGroups(AccountInterface $account)
{
$userId = $account->id();
if (!isset($this->accessCache[$userId])) {
$this->accessCache[$userId] = [];
$q = $this
->database
->select('ucms_group_access', 'gu')
->fields('gu', ['group_id', 'user_id', 'role'])
->condition('gu.user_id', $userId)
;
// This will populate the PartialUserInterface information without
// the need to join on the user table. Performance for the win.
// This will always remain true as long as we have a foreign key
// constraint on the user table, we are sure that the user actually
// exists, and since we have the instance, it's all good!
$q->addExpression(':name', 'name', [':name' => $account->getAccountName()]);
$q->addExpression(':mail', 'mail', [':mail' => $account->getEmail()]);
$q->addExpression(':status', 'status', [':status' => $account->status]);
$r = $q->execute();
$r->setFetchMode(\PDO::FETCH_CLASS, GroupMember::class);
// Can't use fetchAllAssoc() because properties are private on the
// objects built by PDO
$this->accessCache[$userId] = [];
foreach ($r as $record) {
$this->accessCache[$userId][] = $record;
}
}
return $this->accessCache[$userId];
} | php | public function getUserGroups(AccountInterface $account)
{
$userId = $account->id();
if (!isset($this->accessCache[$userId])) {
$this->accessCache[$userId] = [];
$q = $this
->database
->select('ucms_group_access', 'gu')
->fields('gu', ['group_id', 'user_id', 'role'])
->condition('gu.user_id', $userId)
;
// This will populate the PartialUserInterface information without
// the need to join on the user table. Performance for the win.
// This will always remain true as long as we have a foreign key
// constraint on the user table, we are sure that the user actually
// exists, and since we have the instance, it's all good!
$q->addExpression(':name', 'name', [':name' => $account->getAccountName()]);
$q->addExpression(':mail', 'mail', [':mail' => $account->getEmail()]);
$q->addExpression(':status', 'status', [':status' => $account->status]);
$r = $q->execute();
$r->setFetchMode(\PDO::FETCH_CLASS, GroupMember::class);
// Can't use fetchAllAssoc() because properties are private on the
// objects built by PDO
$this->accessCache[$userId] = [];
foreach ($r as $record) {
$this->accessCache[$userId][] = $record;
}
}
return $this->accessCache[$userId];
} | [
"public",
"function",
"getUserGroups",
"(",
"AccountInterface",
"$",
"account",
")",
"{",
"$",
"userId",
"=",
"$",
"account",
"->",
"id",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"accessCache",
"[",
"$",
"userId",
"]",
")",
")"... | Get user groups
@param AccountInterface $account
@return GroupMember[] | [
"Get",
"user",
"groups"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/GroupManager.php#L403-L439 |
makinacorpus/drupal-ucms | ucms_site/src/GroupManager.php | GroupManager.addMember | public function addMember($groupId, $userId)
{
$exists = (bool)$this
->database
->query(
"SELECT 1 FROM {ucms_group_access} WHERE group_id = :group AND user_id = :user",
[':group' => $groupId, ':user' => $userId]
)
->fetchField()
;
if ($exists) {
return false;
}
$this
->database
->merge('ucms_group_access')
->key([
'group_id' => $groupId,
'user_id' => $userId,
])
->execute()
;
// @todo dispatch event
$this->touch($groupId);
$this->resetCache();
return true;
} | php | public function addMember($groupId, $userId)
{
$exists = (bool)$this
->database
->query(
"SELECT 1 FROM {ucms_group_access} WHERE group_id = :group AND user_id = :user",
[':group' => $groupId, ':user' => $userId]
)
->fetchField()
;
if ($exists) {
return false;
}
$this
->database
->merge('ucms_group_access')
->key([
'group_id' => $groupId,
'user_id' => $userId,
])
->execute()
;
// @todo dispatch event
$this->touch($groupId);
$this->resetCache();
return true;
} | [
"public",
"function",
"addMember",
"(",
"$",
"groupId",
",",
"$",
"userId",
")",
"{",
"$",
"exists",
"=",
"(",
"bool",
")",
"$",
"this",
"->",
"database",
"->",
"query",
"(",
"\"SELECT 1 FROM {ucms_group_access} WHERE group_id = :group AND user_id = :user\"",
",",
... | Add member to group
@param int $groupId
@param int $userId
@return bool
True if user was really added, false if user is already a member | [
"Add",
"member",
"to",
"group"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/GroupManager.php#L450-L482 |
makinacorpus/drupal-ucms | ucms_site/src/GroupManager.php | GroupManager.removeMember | public function removeMember($groupId, $userId)
{
$this
->database
->delete('ucms_group_access')
->condition('group_id', $groupId)
->condition('user_id', $userId)
->execute()
;
// @todo dispatch event
$this->touch($groupId);
$this->resetCache();
} | php | public function removeMember($groupId, $userId)
{
$this
->database
->delete('ucms_group_access')
->condition('group_id', $groupId)
->condition('user_id', $userId)
->execute()
;
// @todo dispatch event
$this->touch($groupId);
$this->resetCache();
} | [
"public",
"function",
"removeMember",
"(",
"$",
"groupId",
",",
"$",
"userId",
")",
"{",
"$",
"this",
"->",
"database",
"->",
"delete",
"(",
"'ucms_group_access'",
")",
"->",
"condition",
"(",
"'group_id'",
",",
"$",
"groupId",
")",
"->",
"condition",
"(",... | Remove member from group
If association does not exists, this will silently do nothing
@param int $groupId
@param int $userId | [
"Remove",
"member",
"from",
"group"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/GroupManager.php#L492-L507 |
despark/ignicms | public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Utf8.php | CI_Utf8.clean_string | function clean_string($str)
{
if ($this->_is_ascii($str) === FALSE)
{
$str = @iconv('UTF-8', 'UTF-8//IGNORE', $str);
}
return $str;
} | php | function clean_string($str)
{
if ($this->_is_ascii($str) === FALSE)
{
$str = @iconv('UTF-8', 'UTF-8//IGNORE', $str);
}
return $str;
} | [
"function",
"clean_string",
"(",
"$",
"str",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_is_ascii",
"(",
"$",
"str",
")",
"===",
"FALSE",
")",
"{",
"$",
"str",
"=",
"@",
"iconv",
"(",
"'UTF-8'",
",",
"'UTF-8//IGNORE'",
",",
"$",
"str",
")",
";",
"}... | Clean UTF-8 strings
Ensures strings are UTF-8
@access public
@param string
@return string | [
"Clean",
"UTF",
"-",
"8",
"strings"
] | train | https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Utf8.php#L85-L93 |
despark/ignicms | public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Utf8.php | CI_Utf8.convert_to_utf8 | function convert_to_utf8($str, $encoding)
{
if (function_exists('iconv'))
{
$str = @iconv($encoding, 'UTF-8', $str);
}
elseif (function_exists('mb_convert_encoding'))
{
$str = @mb_convert_encoding($str, 'UTF-8', $encoding);
}
else
{
return FALSE;
}
return $str;
} | php | function convert_to_utf8($str, $encoding)
{
if (function_exists('iconv'))
{
$str = @iconv($encoding, 'UTF-8', $str);
}
elseif (function_exists('mb_convert_encoding'))
{
$str = @mb_convert_encoding($str, 'UTF-8', $encoding);
}
else
{
return FALSE;
}
return $str;
} | [
"function",
"convert_to_utf8",
"(",
"$",
"str",
",",
"$",
"encoding",
")",
"{",
"if",
"(",
"function_exists",
"(",
"'iconv'",
")",
")",
"{",
"$",
"str",
"=",
"@",
"iconv",
"(",
"$",
"encoding",
",",
"'UTF-8'",
",",
"$",
"str",
")",
";",
"}",
"elsei... | Convert to UTF-8
Attempts to convert a string to UTF-8
@access public
@param string
@param string - input encoding
@return string | [
"Convert",
"to",
"UTF",
"-",
"8"
] | train | https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Utf8.php#L125-L141 |
makinacorpus/drupal-ucms | ucms_seo/src/Widget/SiteMapWidget.php | SiteMapWidget.render | public function render(EntityInterface $entity, Site $site, $options = [], $formatterOptions = [], Request $request)
{
if (!$site) {
return '';
}
$items = [];
$menus = $this->treeManager->getMenuStorage()->loadWithConditions(['site_id' => $site->getId()]);
/** @var \MakinaCorpus\Umenu\Menu $menu */
foreach ($menus as $menu) {
if ($menu->isSiteMain() || !$menu->hasRole()) {
$tree = $this->treeManager->buildTree($menu->getId(), true);
if (!$tree->isEmpty()) {
$items[$menu->getTitle()] = $tree;
}
}
}
return ['#theme' => 'ucms_seo_sitemap', '#menus' => $items];
} | php | public function render(EntityInterface $entity, Site $site, $options = [], $formatterOptions = [], Request $request)
{
if (!$site) {
return '';
}
$items = [];
$menus = $this->treeManager->getMenuStorage()->loadWithConditions(['site_id' => $site->getId()]);
/** @var \MakinaCorpus\Umenu\Menu $menu */
foreach ($menus as $menu) {
if ($menu->isSiteMain() || !$menu->hasRole()) {
$tree = $this->treeManager->buildTree($menu->getId(), true);
if (!$tree->isEmpty()) {
$items[$menu->getTitle()] = $tree;
}
}
}
return ['#theme' => 'ucms_seo_sitemap', '#menus' => $items];
} | [
"public",
"function",
"render",
"(",
"EntityInterface",
"$",
"entity",
",",
"Site",
"$",
"site",
",",
"$",
"options",
"=",
"[",
"]",
",",
"$",
"formatterOptions",
"=",
"[",
"]",
",",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"!",
"$",
"site",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/Widget/SiteMapWidget.php#L31-L51 |
potsky/microsoft-translator-php-sdk | src/MicrosoftTranslator/Auth.php | Auth.getAccessToken | public function getAccessToken($force_new = false)
{
if ($this->guard->hasAccessToken()) {
$access_token = $this->guard->getAccessToken();
return $access_token;
}
return $this->generateAndStoreNewAccessToken();
} | php | public function getAccessToken($force_new = false)
{
if ($this->guard->hasAccessToken()) {
$access_token = $this->guard->getAccessToken();
return $access_token;
}
return $this->generateAndStoreNewAccessToken();
} | [
"public",
"function",
"getAccessToken",
"(",
"$",
"force_new",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"guard",
"->",
"hasAccessToken",
"(",
")",
")",
"{",
"$",
"access_token",
"=",
"$",
"this",
"->",
"guard",
"->",
"getAccessToken",
"(",
... | Get an access token
If available, the stored access token will be used
If not available or if $force_new is true, a new one will be generated
@param bool|false $force_new
@return array|string
@throws \MicrosoftTranslator\Exception | [
"Get",
"an",
"access",
"token"
] | train | https://github.com/potsky/microsoft-translator-php-sdk/blob/102f2411be5abb0e57a73c475f8e9e185a9f4859/src/MicrosoftTranslator/Auth.php#L107-L116 |
makinacorpus/drupal-ucms | ucms_site/src/EventDispatcher/AllowListEvent.php | AllowListEvent.remove | public function remove($item)
{
foreach ($this->currentList as $index => $candidate) {
if ($candidate === $item) {
unset($this->currentList[$index]);
}
}
} | php | public function remove($item)
{
foreach ($this->currentList as $index => $candidate) {
if ($candidate === $item) {
unset($this->currentList[$index]);
}
}
} | [
"public",
"function",
"remove",
"(",
"$",
"item",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"currentList",
"as",
"$",
"index",
"=>",
"$",
"candidate",
")",
"{",
"if",
"(",
"$",
"candidate",
"===",
"$",
"item",
")",
"{",
"unset",
"(",
"$",
"this"... | Remove item from list
@param string $item | [
"Remove",
"item",
"from",
"list"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/EventDispatcher/AllowListEvent.php#L56-L63 |
makinacorpus/drupal-ucms | ucms_site/src/EventDispatcher/AllowListEvent.php | AllowListEvent.add | public function add($item)
{
// Disallow items outside of original boundaries
if (!in_array($item, $this->originalList)) {
return;
}
if (!in_array($item, $this->currentList)) {
$this->currentList[] = $item;
}
} | php | public function add($item)
{
// Disallow items outside of original boundaries
if (!in_array($item, $this->originalList)) {
return;
}
if (!in_array($item, $this->currentList)) {
$this->currentList[] = $item;
}
} | [
"public",
"function",
"add",
"(",
"$",
"item",
")",
"{",
"// Disallow items outside of original boundaries",
"if",
"(",
"!",
"in_array",
"(",
"$",
"item",
",",
"$",
"this",
"->",
"originalList",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"in_array"... | Add item into list
@param string $item | [
"Add",
"item",
"into",
"list"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/EventDispatcher/AllowListEvent.php#L70-L79 |
makinacorpus/drupal-ucms | ucms_site/src/Action/WebmasterActionProvider.php | WebmasterActionProvider.getActions | public function getActions($item, $primaryOnly = false, array $groups = [])
{
if ($item->getUserId() == $this->currentUser->id()) {
return [];
}
$relativeRoles = $this->manager->getAccess()->collectRelativeRoles();
$actions = [];
if (count($relativeRoles) > 2) {
$actions[] = $this->createChangeRoleAction($item);
} else {
if ($item->getRole() === Access::ROLE_WEBMASTER) {
$path = $this->buildWebmasterUri($item, 'demote');
$actions[] = new Action($this->t("Demote as contributor"), $path, 'dialog', 'circle-arrow-down', 50, true, true);
}
elseif ($item->getRole() === Access::ROLE_CONTRIB) {
$path = $this->buildWebmasterUri($item, 'promote');
$actions[] = new Action($this->t("Promote as webmaster"), $path, 'dialog', 'circle-arrow-up', 50, true, true);
}
}
$actions[] = $this->createDeleteAction($item);
return $actions;
} | php | public function getActions($item, $primaryOnly = false, array $groups = [])
{
if ($item->getUserId() == $this->currentUser->id()) {
return [];
}
$relativeRoles = $this->manager->getAccess()->collectRelativeRoles();
$actions = [];
if (count($relativeRoles) > 2) {
$actions[] = $this->createChangeRoleAction($item);
} else {
if ($item->getRole() === Access::ROLE_WEBMASTER) {
$path = $this->buildWebmasterUri($item, 'demote');
$actions[] = new Action($this->t("Demote as contributor"), $path, 'dialog', 'circle-arrow-down', 50, true, true);
}
elseif ($item->getRole() === Access::ROLE_CONTRIB) {
$path = $this->buildWebmasterUri($item, 'promote');
$actions[] = new Action($this->t("Promote as webmaster"), $path, 'dialog', 'circle-arrow-up', 50, true, true);
}
}
$actions[] = $this->createDeleteAction($item);
return $actions;
} | [
"public",
"function",
"getActions",
"(",
"$",
"item",
",",
"$",
"primaryOnly",
"=",
"false",
",",
"array",
"$",
"groups",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"$",
"item",
"->",
"getUserId",
"(",
")",
"==",
"$",
"this",
"->",
"currentUser",
"->",
"i... | {@inheritdoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Action/WebmasterActionProvider.php#L13-L39 |
makinacorpus/drupal-ucms | ucms_site/src/Action/WebmasterActionProvider.php | WebmasterActionProvider.supports | public function supports($item)
{
// We act only on the roles known by ucms_site and let other modules
// provide actions for their own roles.
$roles = [Access::ROLE_WEBMASTER, Access::ROLE_CONTRIB];
return parent::supports($item) && in_array($item->getRole(), $roles);
} | php | public function supports($item)
{
// We act only on the roles known by ucms_site and let other modules
// provide actions for their own roles.
$roles = [Access::ROLE_WEBMASTER, Access::ROLE_CONTRIB];
return parent::supports($item) && in_array($item->getRole(), $roles);
} | [
"public",
"function",
"supports",
"(",
"$",
"item",
")",
"{",
"// We act only on the roles known by ucms_site and let other modules",
"// provide actions for their own roles.",
"$",
"roles",
"=",
"[",
"Access",
"::",
"ROLE_WEBMASTER",
",",
"Access",
"::",
"ROLE_CONTRIB",
"]... | {@inheritdoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Action/WebmasterActionProvider.php#L44-L51 |
PHPixie/HTTP | src/PHPixie/HTTP/Output.php | Output.response | public function response($response, $context = null)
{
$responseMessage = $response->asResponseMessage($context);
$this->responseMessage($responseMessage);
} | php | public function response($response, $context = null)
{
$responseMessage = $response->asResponseMessage($context);
$this->responseMessage($responseMessage);
} | [
"public",
"function",
"response",
"(",
"$",
"response",
",",
"$",
"context",
"=",
"null",
")",
"{",
"$",
"responseMessage",
"=",
"$",
"response",
"->",
"asResponseMessage",
"(",
"$",
"context",
")",
";",
"$",
"this",
"->",
"responseMessage",
"(",
"$",
"r... | Output a HTTP response with optional context
@param Responses\Response $response
@param Context $context
@return void | [
"Output",
"a",
"HTTP",
"response",
"with",
"optional",
"context"
] | train | https://github.com/PHPixie/HTTP/blob/581c0df452fd07ca4ea0b3e24e8ddee8dddc2912/src/PHPixie/HTTP/Output.php#L17-L21 |
PHPixie/HTTP | src/PHPixie/HTTP/Output.php | Output.responseMessage | public function responseMessage($responseMessage)
{
$this->statusHeader(
$responseMessage->getStatusCode(),
$responseMessage->getReasonPhrase(),
$responseMessage->getProtocolVersion()
);
$this->headers($responseMessage->getHeaders());
$this->body($responseMessage->getBody());
} | php | public function responseMessage($responseMessage)
{
$this->statusHeader(
$responseMessage->getStatusCode(),
$responseMessage->getReasonPhrase(),
$responseMessage->getProtocolVersion()
);
$this->headers($responseMessage->getHeaders());
$this->body($responseMessage->getBody());
} | [
"public",
"function",
"responseMessage",
"(",
"$",
"responseMessage",
")",
"{",
"$",
"this",
"->",
"statusHeader",
"(",
"$",
"responseMessage",
"->",
"getStatusCode",
"(",
")",
",",
"$",
"responseMessage",
"->",
"getReasonPhrase",
"(",
")",
",",
"$",
"response... | Output a PSR 7 response message
@param Messages\Message\Response $responseMessage | [
"Output",
"a",
"PSR",
"7",
"response",
"message"
] | train | https://github.com/PHPixie/HTTP/blob/581c0df452fd07ca4ea0b3e24e8ddee8dddc2912/src/PHPixie/HTTP/Output.php#L27-L37 |
PHPixie/HTTP | src/PHPixie/HTTP/Output.php | Output.headers | protected function headers($headers)
{
foreach($headers as $name => $lines) {
foreach($lines as $key => $line) {
$this->header("$name: $line", false);
}
}
} | php | protected function headers($headers)
{
foreach($headers as $name => $lines) {
foreach($lines as $key => $line) {
$this->header("$name: $line", false);
}
}
} | [
"protected",
"function",
"headers",
"(",
"$",
"headers",
")",
"{",
"foreach",
"(",
"$",
"headers",
"as",
"$",
"name",
"=>",
"$",
"lines",
")",
"{",
"foreach",
"(",
"$",
"lines",
"as",
"$",
"key",
"=>",
"$",
"line",
")",
"{",
"$",
"this",
"->",
"h... | Output headers
@param array $headers | [
"Output",
"headers"
] | train | https://github.com/PHPixie/HTTP/blob/581c0df452fd07ca4ea0b3e24e8ddee8dddc2912/src/PHPixie/HTTP/Output.php#L43-L50 |
potsky/microsoft-translator-php-sdk | src/MicrosoftTranslator/Client.php | Client.translate | public function translate($text, $to, $from = null, $contentType = 'text/plain', $category = 'general')
{
$query_parameters = [
'text' => $text,
'to' => $to,
'contentType' => $contentType,
'category' => $category,
];
if (! is_null($from)) {
$query_parameters['from'] = $from;
}
return $this->get('/Translate', [], $query_parameters);
} | php | public function translate($text, $to, $from = null, $contentType = 'text/plain', $category = 'general')
{
$query_parameters = [
'text' => $text,
'to' => $to,
'contentType' => $contentType,
'category' => $category,
];
if (! is_null($from)) {
$query_parameters['from'] = $from;
}
return $this->get('/Translate', [], $query_parameters);
} | [
"public",
"function",
"translate",
"(",
"$",
"text",
",",
"$",
"to",
",",
"$",
"from",
"=",
"null",
",",
"$",
"contentType",
"=",
"'text/plain'",
",",
"$",
"category",
"=",
"'general'",
")",
"{",
"$",
"query_parameters",
"=",
"[",
"'text'",
"=>",
"$",
... | Translates a text string from one language to another.
@param string $text Required. A string representing the text to translate. The size of the text must
not exceed 10000 characters.
@param string $to Required. A string representing the language code to translate the text into.
@param string|null $from Optional. A string representing the language code of the translation text.
@param string $contentType Optional. The format of the text being translated. The supported formats are
"text/plain" and "text/html". Any HTML needs to be well-formed.
@param string $category Optional. A string containing the category (domain) of the translation. Defaults
to "general".
The language codes are available at https://msdn.microsoft.com/en-us/library/hh456380.aspx
The API endpoint documentation is available at https://msdn.microsoft.com/en-us/library/ff512421.aspx
@return \MicrosoftTranslator\Response
@throws \MicrosoftTranslator\Exception | [
"Translates",
"a",
"text",
"string",
"from",
"one",
"language",
"to",
"another",
"."
] | train | https://github.com/potsky/microsoft-translator-php-sdk/blob/102f2411be5abb0e57a73c475f8e9e185a9f4859/src/MicrosoftTranslator/Client.php#L162-L176 |
potsky/microsoft-translator-php-sdk | src/MicrosoftTranslator/Client.php | Client.TransformText | public function TransformText($text, $from, $category = 'general')
{
$query_parameters = [
'sentence' => $text,
'language' => $from,
'category' => $category,
];
return $this->get('/TransformText', [], $query_parameters, true, 'http://api.microsofttranslator.com/V3/json/');
} | php | public function TransformText($text, $from, $category = 'general')
{
$query_parameters = [
'sentence' => $text,
'language' => $from,
'category' => $category,
];
return $this->get('/TransformText', [], $query_parameters, true, 'http://api.microsofttranslator.com/V3/json/');
} | [
"public",
"function",
"TransformText",
"(",
"$",
"text",
",",
"$",
"from",
",",
"$",
"category",
"=",
"'general'",
")",
"{",
"$",
"query_parameters",
"=",
"[",
"'sentence'",
"=>",
"$",
"text",
",",
"'language'",
"=>",
"$",
"from",
",",
"'category'",
"=>"... | The TransformText method is a text normalization function for social media, which returns a normalized form of
the input. The method can be used as a preprocessing step in Machine Translation or other applications, which
expect clean input text than is typically found in social media or user-generated content. The function
currently works only with English input.
@param string $text Required. A string representing the text to translate. The size of the text must
not exceed 10000 characters.
@param string $from Required. A string representing the language code. This parameter supports only
English with "en" as the language name.
@param string|null $category Optional. A string containing the category or domain of the translation. This
parameter supports only the default option general.
The language codes are available at https://msdn.microsoft.com/en-us/library/hh456380.aspx
The API endpoint documentation is available at https://msdn.microsoft.com/en-us/library/dn876735.aspx
@return \MicrosoftTranslator\Response
@throws \MicrosoftTranslator\Exception | [
"The",
"TransformText",
"method",
"is",
"a",
"text",
"normalization",
"function",
"for",
"social",
"media",
"which",
"returns",
"a",
"normalized",
"form",
"of",
"the",
"input",
".",
"The",
"method",
"can",
"be",
"used",
"as",
"a",
"preprocessing",
"step",
"i... | train | https://github.com/potsky/microsoft-translator-php-sdk/blob/102f2411be5abb0e57a73c475f8e9e185a9f4859/src/MicrosoftTranslator/Client.php#L222-L231 |
potsky/microsoft-translator-php-sdk | src/MicrosoftTranslator/Client.php | Client.translateArray | public function translateArray(array $texts, $to, $from = null, $contentType = 'text/plain', $category = 'general')
{
$requestXml = "<TranslateArrayRequest>"."<AppId/>"."<From>$from</From>"."<Options>"."<Category xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">$category</Category>"."<ContentType xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">$contentType</ContentType>"."<ReservedFlags xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />"."<State xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />"."<Uri xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />"."<User xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />"."</Options>"."<Texts>";
foreach ($texts as $text) {
$requestXml .= "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\"><![CDATA[$text]]></string>";
}
$requestXml .= "</Texts>"."<To>$to</To>"."</TranslateArrayRequest>";
return $this->post('/TranslateArray', [], $requestXml, true, $texts);
} | php | public function translateArray(array $texts, $to, $from = null, $contentType = 'text/plain', $category = 'general')
{
$requestXml = "<TranslateArrayRequest>"."<AppId/>"."<From>$from</From>"."<Options>"."<Category xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">$category</Category>"."<ContentType xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">$contentType</ContentType>"."<ReservedFlags xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />"."<State xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />"."<Uri xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />"."<User xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />"."</Options>"."<Texts>";
foreach ($texts as $text) {
$requestXml .= "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\"><![CDATA[$text]]></string>";
}
$requestXml .= "</Texts>"."<To>$to</To>"."</TranslateArrayRequest>";
return $this->post('/TranslateArray', [], $requestXml, true, $texts);
} | [
"public",
"function",
"translateArray",
"(",
"array",
"$",
"texts",
",",
"$",
"to",
",",
"$",
"from",
"=",
"null",
",",
"$",
"contentType",
"=",
"'text/plain'",
",",
"$",
"category",
"=",
"'general'",
")",
"{",
"$",
"requestXml",
"=",
"\"<TranslateArrayReq... | Use the TranslateArray method to retrieve translations for multiple source texts.
@param array $texts Required. An array containing the texts for translation. All strings must be of
the same language. The total of all texts to be translated must not exceed 10000
characters. The maximum number of array elements is 2000.
@param string $to Required. A string representing the language code to translate the text into.
@param string|null $from Optional. A string representing the language code of the translation text.
@param string $contentType Optional. The format of the text being translated. The supported formats are
"text/plain" and "text/html". Any HTML needs to be well-formed.
@param string $category Optional. A string containing the category (domain) of the translation. Defaults
to "general".
The language codes are available at https://msdn.microsoft.com/en-us/library/hh456380.aspx
The API endpoint documentation is available at https://msdn.microsoft.com/en-us/library/ff512422.aspx
@return \MicrosoftTranslator\Response
@throws \MicrosoftTranslator\Exception | [
"Use",
"the",
"TranslateArray",
"method",
"to",
"retrieve",
"translations",
"for",
"multiple",
"source",
"texts",
"."
] | train | https://github.com/potsky/microsoft-translator-php-sdk/blob/102f2411be5abb0e57a73c475f8e9e185a9f4859/src/MicrosoftTranslator/Client.php#L253-L262 |
potsky/microsoft-translator-php-sdk | src/MicrosoftTranslator/Client.php | Client.getLanguageNames | public function getLanguageNames($locale, $languageCodes)
{
if (is_string($languageCodes)) {
$languageCodes = [$languageCodes];
}
/** @noinspection XmlUnusedNamespaceDeclaration */
$requestXml = '<ArrayOfstring xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">';
if (sizeof($languageCodes) > 0) {
foreach ($languageCodes as $codes) {
$requestXml .= "<string>$codes</string>";
}
} else {
throw new Exception('$languageCodes array is empty.');
}
$requestXml .= '</ArrayOfstring>';
return $this->post('/GetLanguageNames?locale='.$locale, [], $requestXml, true, $languageCodes);
} | php | public function getLanguageNames($locale, $languageCodes)
{
if (is_string($languageCodes)) {
$languageCodes = [$languageCodes];
}
/** @noinspection XmlUnusedNamespaceDeclaration */
$requestXml = '<ArrayOfstring xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">';
if (sizeof($languageCodes) > 0) {
foreach ($languageCodes as $codes) {
$requestXml .= "<string>$codes</string>";
}
} else {
throw new Exception('$languageCodes array is empty.');
}
$requestXml .= '</ArrayOfstring>';
return $this->post('/GetLanguageNames?locale='.$locale, [], $requestXml, true, $languageCodes);
} | [
"public",
"function",
"getLanguageNames",
"(",
"$",
"locale",
",",
"$",
"languageCodes",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"languageCodes",
")",
")",
"{",
"$",
"languageCodes",
"=",
"[",
"$",
"languageCodes",
"]",
";",
"}",
"/** @noinspection XmlUn... | Retrieves friendly names for the languages passed in as the parameter languageCodes, and localized using the
passed locale language.
@param string $locale Required. A string representing a combination of an ISO 639 two-letter
lowercase culture code associated with a language and an ISO 3166 two-letter
uppercase subculture code to localize the language names or a ISO 639
lowercase culture code by itself.
@param string|array $languageCodes Required. A string or an array representing the ISO 639-1 language codes to
retrieve the friendly name for.
The language codes are available at https://msdn.microsoft.com/en-us/library/hh456380.aspx
The API endpoint documentation is available at https://msdn.microsoft.com/en-us/library/ff512414.aspx
@return \MicrosoftTranslator\Response
@throws \MicrosoftTranslator\Exception | [
"Retrieves",
"friendly",
"names",
"for",
"the",
"languages",
"passed",
"in",
"as",
"the",
"parameter",
"languageCodes",
"and",
"localized",
"using",
"the",
"passed",
"locale",
"language",
"."
] | train | https://github.com/potsky/microsoft-translator-php-sdk/blob/102f2411be5abb0e57a73c475f8e9e185a9f4859/src/MicrosoftTranslator/Client.php#L282-L300 |
potsky/microsoft-translator-php-sdk | src/MicrosoftTranslator/Client.php | Client.detectArray | public function detectArray(array $texts)
{
/** @noinspection XmlUnusedNamespaceDeclaration */
$requestXml = '<ArrayOfstring xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">';
if (sizeof($texts) > 0) {
foreach ($texts as $str) {
$requestXml .= "<string>$str</string>";
}
} else {
throw new Exception('$texts array is empty.');
}
$requestXml .= '</ArrayOfstring>';
return $this->post('/DetectArray', [], $requestXml, true, $texts);
} | php | public function detectArray(array $texts)
{
/** @noinspection XmlUnusedNamespaceDeclaration */
$requestXml = '<ArrayOfstring xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">';
if (sizeof($texts) > 0) {
foreach ($texts as $str) {
$requestXml .= "<string>$str</string>";
}
} else {
throw new Exception('$texts array is empty.');
}
$requestXml .= '</ArrayOfstring>';
return $this->post('/DetectArray', [], $requestXml, true, $texts);
} | [
"public",
"function",
"detectArray",
"(",
"array",
"$",
"texts",
")",
"{",
"/** @noinspection XmlUnusedNamespaceDeclaration */",
"$",
"requestXml",
"=",
"'<ArrayOfstring xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\... | Use the DetectArray Method to identify the language of an array of string at once. Performs independent
detection of each individual array element and returns a result for each row of the array.
@param array $texts Required. A string array representing the text from an unknown language. The size of the
text must not exceed 10000 characters.
The API endpoint documentation is available at https://msdn.microsoft.com/en-us/library/ff512412.aspx
@return \MicrosoftTranslator\Response
@throws \MicrosoftTranslator\Exception | [
"Use",
"the",
"DetectArray",
"Method",
"to",
"identify",
"the",
"language",
"of",
"an",
"array",
"of",
"string",
"at",
"once",
".",
"Performs",
"independent",
"detection",
"of",
"each",
"individual",
"array",
"element",
"and",
"returns",
"a",
"result",
"for",
... | train | https://github.com/potsky/microsoft-translator-php-sdk/blob/102f2411be5abb0e57a73c475f8e9e185a9f4859/src/MicrosoftTranslator/Client.php#L345-L359 |
potsky/microsoft-translator-php-sdk | src/MicrosoftTranslator/Client.php | Client.buildUrl | private function buildUrl($endpoint, $url_parameters = [], $special_url = null)
{
foreach ($url_parameters as $key => $value) {
//@codeCoverageIgnoreStart
$endpoint = str_replace('{'.$key.'}', $value, $endpoint);
//@codeCoverageIgnoreEnd
}
if (is_null($special_url)) {
$url = trim($this->api_base_url, "/ \t\n\r\0\x0B");
} else {
$url = $special_url;
}
$url = $url.'/'.trim($endpoint, "/ \t\n\r\0\x0B");
return $url;
} | php | private function buildUrl($endpoint, $url_parameters = [], $special_url = null)
{
foreach ($url_parameters as $key => $value) {
//@codeCoverageIgnoreStart
$endpoint = str_replace('{'.$key.'}', $value, $endpoint);
//@codeCoverageIgnoreEnd
}
if (is_null($special_url)) {
$url = trim($this->api_base_url, "/ \t\n\r\0\x0B");
} else {
$url = $special_url;
}
$url = $url.'/'.trim($endpoint, "/ \t\n\r\0\x0B");
return $url;
} | [
"private",
"function",
"buildUrl",
"(",
"$",
"endpoint",
",",
"$",
"url_parameters",
"=",
"[",
"]",
",",
"$",
"special_url",
"=",
"null",
")",
"{",
"foreach",
"(",
"$",
"url_parameters",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"//@codeCoverageIgn... | Build the URL according to endpoint by replacing URL parameters
@param string $endpoint
@param array $url_parameters
@param string|null $special_url
@return string | [
"Build",
"the",
"URL",
"according",
"to",
"endpoint",
"by",
"replacing",
"URL",
"parameters"
] | train | https://github.com/potsky/microsoft-translator-php-sdk/blob/102f2411be5abb0e57a73c475f8e9e185a9f4859/src/MicrosoftTranslator/Client.php#L370-L386 |
potsky/microsoft-translator-php-sdk | src/MicrosoftTranslator/Client.php | Client.getResponseObject | private function getResponseObject($endpoint, $url_parameters, $query_parameters, $try_to_auth, $url, $result, $originalData = null)
{
if ((isset($result['http_code'])) && (substr(strval($result['http_code']), 0, 1) !== '2')) {
throw new Exception($result);
}
if (isset($result['http_body'])) {
if (Tools::startsWith($result['http_body'], '<string ')) {
$xmlObj = simplexml_load_string($result['http_body']);
$result['http_body'] = strval($xmlObj[0]);
} else {
if (Tools::startsWith($result['http_body'], '<ArrayOfTranslateArrayResponse ')) {
$xmlObj = simplexml_load_string($result['http_body']);
$array = [];
$i = 0;
/** @noinspection PhpUndefinedFieldInspection */
foreach ($xmlObj->TranslateArrayResponse as $translatedArrObj) {
if (@isset($originalData[$i])) {
/** @noinspection PhpUndefinedFieldInspection */
$array[$originalData[$i]] = strval($translatedArrObj->TranslatedText);
} //@codeCoverageIgnoreStart
else {
/** @noinspection PhpUndefinedFieldInspection */
$array[] = strval($translatedArrObj->TranslatedText);
}
//@codeCoverageIgnoreEnd
$i++;
}
$result['http_body'] = $array;
} else {
if (Tools::startsWith($result['http_body'], '<ArrayOfstring ')) {
$xmlObj = simplexml_load_string($result['http_body']);
$array = [];
$i = 0;
/** @noinspection PhpUndefinedFieldInspection */
foreach ($xmlObj->string as $language) {
if (@isset($originalData[$i])) {
$array[$originalData[$i]] = strval($language);
} else {
$array[] = strval($language);
}
$i++;
}
$result['http_body'] = $array;
} else {
if (Tools::startsWith($result['http_body'], '<ArrayOfint ')) {
$xmlObj = simplexml_load_string($result['http_body']);
$array = [];
$i = 1;
$startLen = 0;
/** @noinspection PhpUndefinedFieldInspection */
foreach ($xmlObj->int as $strLen) {
$endLen = (int) $strLen;
$array[] = substr($query_parameters['text'], $startLen, $endLen);
$startLen += $endLen;
$i++;
}
$result['http_body'] = $array;
} else {
if (! is_null($json = json_decode(Tools::removeUtf8Bom($result['http_body']), true))) {
$result['http_body'] = $json;
}
}
}
}
}
}
return new Response($endpoint, $url_parameters, $query_parameters, $try_to_auth, $url, $result);
} | php | private function getResponseObject($endpoint, $url_parameters, $query_parameters, $try_to_auth, $url, $result, $originalData = null)
{
if ((isset($result['http_code'])) && (substr(strval($result['http_code']), 0, 1) !== '2')) {
throw new Exception($result);
}
if (isset($result['http_body'])) {
if (Tools::startsWith($result['http_body'], '<string ')) {
$xmlObj = simplexml_load_string($result['http_body']);
$result['http_body'] = strval($xmlObj[0]);
} else {
if (Tools::startsWith($result['http_body'], '<ArrayOfTranslateArrayResponse ')) {
$xmlObj = simplexml_load_string($result['http_body']);
$array = [];
$i = 0;
/** @noinspection PhpUndefinedFieldInspection */
foreach ($xmlObj->TranslateArrayResponse as $translatedArrObj) {
if (@isset($originalData[$i])) {
/** @noinspection PhpUndefinedFieldInspection */
$array[$originalData[$i]] = strval($translatedArrObj->TranslatedText);
} //@codeCoverageIgnoreStart
else {
/** @noinspection PhpUndefinedFieldInspection */
$array[] = strval($translatedArrObj->TranslatedText);
}
//@codeCoverageIgnoreEnd
$i++;
}
$result['http_body'] = $array;
} else {
if (Tools::startsWith($result['http_body'], '<ArrayOfstring ')) {
$xmlObj = simplexml_load_string($result['http_body']);
$array = [];
$i = 0;
/** @noinspection PhpUndefinedFieldInspection */
foreach ($xmlObj->string as $language) {
if (@isset($originalData[$i])) {
$array[$originalData[$i]] = strval($language);
} else {
$array[] = strval($language);
}
$i++;
}
$result['http_body'] = $array;
} else {
if (Tools::startsWith($result['http_body'], '<ArrayOfint ')) {
$xmlObj = simplexml_load_string($result['http_body']);
$array = [];
$i = 1;
$startLen = 0;
/** @noinspection PhpUndefinedFieldInspection */
foreach ($xmlObj->int as $strLen) {
$endLen = (int) $strLen;
$array[] = substr($query_parameters['text'], $startLen, $endLen);
$startLen += $endLen;
$i++;
}
$result['http_body'] = $array;
} else {
if (! is_null($json = json_decode(Tools::removeUtf8Bom($result['http_body']), true))) {
$result['http_body'] = $json;
}
}
}
}
}
}
return new Response($endpoint, $url_parameters, $query_parameters, $try_to_auth, $url, $result);
} | [
"private",
"function",
"getResponseObject",
"(",
"$",
"endpoint",
",",
"$",
"url_parameters",
",",
"$",
"query_parameters",
",",
"$",
"try_to_auth",
",",
"$",
"url",
",",
"$",
"result",
",",
"$",
"originalData",
"=",
"null",
")",
"{",
"if",
"(",
"(",
"is... | @param string $endpoint
@param array $url_parameters
@param array $query_parameters
@param bool $try_to_auth
@param string $url
@param string $result
@param mixed|null $originalData
@return \MicrosoftTranslator\Response
@throws \MicrosoftTranslator\Exception | [
"@param",
"string",
"$endpoint",
"@param",
"array",
"$url_parameters",
"@param",
"array",
"$query_parameters",
"@param",
"bool",
"$try_to_auth",
"@param",
"string",
"$url",
"@param",
"string",
"$result",
"@param",
"mixed|null",
"$originalData"
] | train | https://github.com/potsky/microsoft-translator-php-sdk/blob/102f2411be5abb0e57a73c475f8e9e185a9f4859/src/MicrosoftTranslator/Client.php#L400-L474 |
potsky/microsoft-translator-php-sdk | src/MicrosoftTranslator/Client.php | Client.get | private function get($endpoint, $url_parameters = [], $query_parameters = [], $try_to_auth = true, $special_url = null)
{
$url = $this->buildUrl($endpoint, $url_parameters, $special_url);
$api_access_token = ($try_to_auth === true) ? (is_null($this->api_access_token)) ? $this->auth->getAccessToken() : $this->api_access_token : '';
$query_parameters = $this->fixQueryParameters($query_parameters);
return $this->getResponseObject($endpoint, $url_parameters, $query_parameters, $try_to_auth, $url, $this->http->get($url, $api_access_token, $query_parameters));
} | php | private function get($endpoint, $url_parameters = [], $query_parameters = [], $try_to_auth = true, $special_url = null)
{
$url = $this->buildUrl($endpoint, $url_parameters, $special_url);
$api_access_token = ($try_to_auth === true) ? (is_null($this->api_access_token)) ? $this->auth->getAccessToken() : $this->api_access_token : '';
$query_parameters = $this->fixQueryParameters($query_parameters);
return $this->getResponseObject($endpoint, $url_parameters, $query_parameters, $try_to_auth, $url, $this->http->get($url, $api_access_token, $query_parameters));
} | [
"private",
"function",
"get",
"(",
"$",
"endpoint",
",",
"$",
"url_parameters",
"=",
"[",
"]",
",",
"$",
"query_parameters",
"=",
"[",
"]",
",",
"$",
"try_to_auth",
"=",
"true",
",",
"$",
"special_url",
"=",
"null",
")",
"{",
"$",
"url",
"=",
"$",
... | @param string $endpoint
@param array $url_parameters
@param array $query_parameters
@param bool $try_to_auth if set to false, no access token will be used
@param null $special_url new url instead of api url
@return \MicrosoftTranslator\Response
@throws \MicrosoftTranslator\Exception | [
"@param",
"string",
"$endpoint",
"@param",
"array",
"$url_parameters",
"@param",
"array",
"$query_parameters",
"@param",
"bool",
"$try_to_auth",
"if",
"set",
"to",
"false",
"no",
"access",
"token",
"will",
"be",
"used",
"@param",
"null",
"$special_url",
"new",
"ur... | train | https://github.com/potsky/microsoft-translator-php-sdk/blob/102f2411be5abb0e57a73c475f8e9e185a9f4859/src/MicrosoftTranslator/Client.php#L486-L493 |
platformsh/console-form | src/Field/Field.php | Field.set | public function set($key, $value)
{
switch ($key) {
case 'validator':
$this->validators[] = $value;
break;
case 'normalizer':
$this->normalizers[] = $value;
break;
default:
if (!property_exists($this, $key)) {
throw new \InvalidArgumentException("Unrecognized config key: $key");
}
$this->$key = $value;
}
return $this;
} | php | public function set($key, $value)
{
switch ($key) {
case 'validator':
$this->validators[] = $value;
break;
case 'normalizer':
$this->normalizers[] = $value;
break;
default:
if (!property_exists($this, $key)) {
throw new \InvalidArgumentException("Unrecognized config key: $key");
}
$this->$key = $value;
}
return $this;
} | [
"public",
"function",
"set",
"(",
"$",
"key",
",",
"$",
"value",
")",
"{",
"switch",
"(",
"$",
"key",
")",
"{",
"case",
"'validator'",
":",
"$",
"this",
"->",
"validators",
"[",
"]",
"=",
"$",
"value",
";",
"break",
";",
"case",
"'normalizer'",
":"... | Set or modify a configuration value.
@param string $key
@param mixed $value
@return self | [
"Set",
"or",
"modify",
"a",
"configuration",
"value",
"."
] | train | https://github.com/platformsh/console-form/blob/5263fe8c6c976e10f4495c9e00c92cc2d410a673/src/Field/Field.php#L191-L210 |
platformsh/console-form | src/Field/Field.php | Field.normalize | protected function normalize($value)
{
if ($value === null) {
return $value;
}
foreach ($this->normalizers as $normalizer) {
$value = $normalizer($value);
}
return $value;
} | php | protected function normalize($value)
{
if ($value === null) {
return $value;
}
foreach ($this->normalizers as $normalizer) {
$value = $normalizer($value);
}
return $value;
} | [
"protected",
"function",
"normalize",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"return",
"$",
"value",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"normalizers",
"as",
"$",
"normalizer",
")",
"{",
"$",
"value",
... | Normalize user input.
@param mixed $value
@return mixed | [
"Normalize",
"user",
"input",
"."
] | train | https://github.com/platformsh/console-form/blob/5263fe8c6c976e10f4495c9e00c92cc2d410a673/src/Field/Field.php#L256-L266 |
platformsh/console-form | src/Field/Field.php | Field.validate | public function validate($value)
{
if ($value === null) {
return;
}
$normalized = $this->normalize($value);
foreach ($this->validators as $validator) {
$result = call_user_func($validator, $normalized);
if (is_string($result)) {
throw new InvalidValueException($result);
} elseif ($result === false) {
throw new InvalidValueException("Invalid value for '{$this->name}': $value");
}
}
} | php | public function validate($value)
{
if ($value === null) {
return;
}
$normalized = $this->normalize($value);
foreach ($this->validators as $validator) {
$result = call_user_func($validator, $normalized);
if (is_string($result)) {
throw new InvalidValueException($result);
} elseif ($result === false) {
throw new InvalidValueException("Invalid value for '{$this->name}': $value");
}
}
} | [
"public",
"function",
"validate",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"return",
";",
"}",
"$",
"normalized",
"=",
"$",
"this",
"->",
"normalize",
"(",
"$",
"value",
")",
";",
"foreach",
"(",
"$",
"this",
... | Validate the field.
@throws InvalidValueException if the input was invalid.
@param mixed $value
The user-entered value. | [
"Validate",
"the",
"field",
"."
] | train | https://github.com/platformsh/console-form/blob/5263fe8c6c976e10f4495c9e00c92cc2d410a673/src/Field/Field.php#L276-L291 |
platformsh/console-form | src/Field/Field.php | Field.getAsOption | public function getAsOption()
{
return new InputOption(
$this->getOptionName(),
$this->shortcut,
$this->getOptionMode(),
$this->getDescription(),
$this->default
);
} | php | public function getAsOption()
{
return new InputOption(
$this->getOptionName(),
$this->shortcut,
$this->getOptionMode(),
$this->getDescription(),
$this->default
);
} | [
"public",
"function",
"getAsOption",
"(",
")",
"{",
"return",
"new",
"InputOption",
"(",
"$",
"this",
"->",
"getOptionName",
"(",
")",
",",
"$",
"this",
"->",
"shortcut",
",",
"$",
"this",
"->",
"getOptionMode",
"(",
")",
",",
"$",
"this",
"->",
"getDe... | Get the field as a Console input option.
@return InputOption | [
"Get",
"the",
"field",
"as",
"a",
"Console",
"input",
"option",
"."
] | train | https://github.com/platformsh/console-form/blob/5263fe8c6c976e10f4495c9e00c92cc2d410a673/src/Field/Field.php#L320-L329 |
platformsh/console-form | src/Field/Field.php | Field.getQuestionHeader | protected function getQuestionHeader($includeDefault = true)
{
$header = '';
if ($this->isRequired()) {
$header .= $this->requiredMarker;
}
$header .= '<fg=green>' . $this->name . '</> (--' . $this->getOptionName() . ')';
if ($this->questionLine === null && !empty($this->description)) {
$header .= "\n" . $this->description;
} elseif (!empty($this->questionLine)) {
$header .= "\n" . $this->questionLine;
}
if ($includeDefault && $this->default !== null) {
$header .= "\n" . 'Default: <question>' . $this->formatDefault($this->default) . '</question>';
}
return $header;
} | php | protected function getQuestionHeader($includeDefault = true)
{
$header = '';
if ($this->isRequired()) {
$header .= $this->requiredMarker;
}
$header .= '<fg=green>' . $this->name . '</> (--' . $this->getOptionName() . ')';
if ($this->questionLine === null && !empty($this->description)) {
$header .= "\n" . $this->description;
} elseif (!empty($this->questionLine)) {
$header .= "\n" . $this->questionLine;
}
if ($includeDefault && $this->default !== null) {
$header .= "\n" . 'Default: <question>' . $this->formatDefault($this->default) . '</question>';
}
return $header;
} | [
"protected",
"function",
"getQuestionHeader",
"(",
"$",
"includeDefault",
"=",
"true",
")",
"{",
"$",
"header",
"=",
"''",
";",
"if",
"(",
"$",
"this",
"->",
"isRequired",
"(",
")",
")",
"{",
"$",
"header",
".=",
"$",
"this",
"->",
"requiredMarker",
";... | Get the header text for an interactive question.
@param bool $includeDefault
@return string | [
"Get",
"the",
"header",
"text",
"for",
"an",
"interactive",
"question",
"."
] | train | https://github.com/platformsh/console-form/blob/5263fe8c6c976e10f4495c9e00c92cc2d410a673/src/Field/Field.php#L348-L365 |
platformsh/console-form | src/Field/Field.php | Field.getAsQuestion | public function getAsQuestion()
{
$question = new Question($this->getQuestionText(), $this->default);
$question->setMaxAttempts($this->maxAttempts);
$question->setValidator(function ($value) {
if ($this->isEmpty($value) && $this->isRequired()) {
throw new MissingValueException("'{$this->name}' is required");
}
$this->validate($value);
return $value;
});
$question->setAutocompleterValues($this->autoCompleterValues);
return $question;
} | php | public function getAsQuestion()
{
$question = new Question($this->getQuestionText(), $this->default);
$question->setMaxAttempts($this->maxAttempts);
$question->setValidator(function ($value) {
if ($this->isEmpty($value) && $this->isRequired()) {
throw new MissingValueException("'{$this->name}' is required");
}
$this->validate($value);
return $value;
});
$question->setAutocompleterValues($this->autoCompleterValues);
return $question;
} | [
"public",
"function",
"getAsQuestion",
"(",
")",
"{",
"$",
"question",
"=",
"new",
"Question",
"(",
"$",
"this",
"->",
"getQuestionText",
"(",
")",
",",
"$",
"this",
"->",
"default",
")",
";",
"$",
"question",
"->",
"setMaxAttempts",
"(",
"$",
"this",
... | Get the field as a Console question.
@return Question | [
"Get",
"the",
"field",
"as",
"a",
"Console",
"question",
"."
] | train | https://github.com/platformsh/console-form/blob/5263fe8c6c976e10f4495c9e00c92cc2d410a673/src/Field/Field.php#L372-L387 |
platformsh/console-form | src/Field/Field.php | Field.getValueFromInput | public function getValueFromInput(InputInterface $input, $normalize = true)
{
$optionName = $this->getOptionName();
if (!$input->hasOption($optionName)) {
return null;
}
$value = $input->getOption($optionName);
if ($this->isEmpty($value)) {
return null;
}
if ($input->getParameterOption('--' . $optionName) === false && $value === $this->default) {
return null;
}
return $normalize ? $this->normalize($value) : $value;
} | php | public function getValueFromInput(InputInterface $input, $normalize = true)
{
$optionName = $this->getOptionName();
if (!$input->hasOption($optionName)) {
return null;
}
$value = $input->getOption($optionName);
if ($this->isEmpty($value)) {
return null;
}
if ($input->getParameterOption('--' . $optionName) === false && $value === $this->default) {
return null;
}
return $normalize ? $this->normalize($value) : $value;
} | [
"public",
"function",
"getValueFromInput",
"(",
"InputInterface",
"$",
"input",
",",
"$",
"normalize",
"=",
"true",
")",
"{",
"$",
"optionName",
"=",
"$",
"this",
"->",
"getOptionName",
"(",
")",
";",
"if",
"(",
"!",
"$",
"input",
"->",
"hasOption",
"(",... | Get the value the user entered for this field.
@param InputInterface $input
@param bool $normalize
@return mixed|null
The raw value, or null if the user did not enter anything. The value
will be normalized if $normalize is set. | [
"Get",
"the",
"value",
"the",
"user",
"entered",
"for",
"this",
"field",
"."
] | train | https://github.com/platformsh/console-form/blob/5263fe8c6c976e10f4495c9e00c92cc2d410a673/src/Field/Field.php#L449-L464 |
platformsh/console-form | src/Field/Field.php | Field.onChange | public function onChange(array $previousValues)
{
if (isset($this->defaultCallback)) {
$callback = $this->defaultCallback;
$this->default = $callback($previousValues);
}
} | php | public function onChange(array $previousValues)
{
if (isset($this->defaultCallback)) {
$callback = $this->defaultCallback;
$this->default = $callback($previousValues);
}
} | [
"public",
"function",
"onChange",
"(",
"array",
"$",
"previousValues",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"defaultCallback",
")",
")",
"{",
"$",
"callback",
"=",
"$",
"this",
"->",
"defaultCallback",
";",
"$",
"this",
"->",
"default",
... | React to a change in user input.
@param array $previousValues | [
"React",
"to",
"a",
"change",
"in",
"user",
"input",
"."
] | train | https://github.com/platformsh/console-form/blob/5263fe8c6c976e10f4495c9e00c92cc2d410a673/src/Field/Field.php#L504-L510 |
amphp/loop | lib/EventLoop.php | EventLoop.dispatch | protected function dispatch($blocking) {
$this->handle->loop($blocking ? \EventBase::LOOP_ONCE : \EventBase::LOOP_ONCE | \EventBase::LOOP_NONBLOCK);
} | php | protected function dispatch($blocking) {
$this->handle->loop($blocking ? \EventBase::LOOP_ONCE : \EventBase::LOOP_ONCE | \EventBase::LOOP_NONBLOCK);
} | [
"protected",
"function",
"dispatch",
"(",
"$",
"blocking",
")",
"{",
"$",
"this",
"->",
"handle",
"->",
"loop",
"(",
"$",
"blocking",
"?",
"\\",
"EventBase",
"::",
"LOOP_ONCE",
":",
"\\",
"EventBase",
"::",
"LOOP_ONCE",
"|",
"\\",
"EventBase",
"::",
"LOO... | {@inheritdoc} | [
"{"
] | train | https://github.com/amphp/loop/blob/c7fbdfb7125e03b5653b13db1950fb45344e8e1b/lib/EventLoop.php#L108-L110 |
amphp/loop | lib/EventLoop.php | EventLoop.activate | protected function activate(array $watchers) {
foreach ($watchers as $watcher) {
if (!isset($this->events[$id = $watcher->id])) {
switch ($watcher->type) {
case Watcher::READABLE:
$this->events[$id] = new \Event(
$this->handle,
$watcher->value,
\Event::READ | \Event::PERSIST,
$this->ioCallback,
$watcher
);
break;
case Watcher::WRITABLE:
$this->events[$id] = new \Event(
$this->handle,
$watcher->value,
\Event::WRITE | \Event::PERSIST,
$this->ioCallback,
$watcher
);
break;
case Watcher::DELAY:
case Watcher::REPEAT:
$this->events[$id] = new \Event(
$this->handle,
-1,
\Event::TIMEOUT | \Event::PERSIST,
$this->timerCallback,
$watcher
);
break;
case Watcher::SIGNAL:
$this->events[$id] = new \Event(
$this->handle,
$watcher->value,
\Event::SIGNAL | \Event::PERSIST,
$this->signalCallback,
$watcher
);
break;
default:
throw new \DomainException("Unknown watcher type");
}
}
switch ($watcher->type) {
case Watcher::DELAY:
case Watcher::REPEAT:
$this->events[$id]->add($watcher->value / self::MILLISEC_PER_SEC);
break;
case Watcher::SIGNAL:
$this->signals[$id] = $this->events[$id];
// No break
default:
$this->events[$id]->add();
break;
}
}
} | php | protected function activate(array $watchers) {
foreach ($watchers as $watcher) {
if (!isset($this->events[$id = $watcher->id])) {
switch ($watcher->type) {
case Watcher::READABLE:
$this->events[$id] = new \Event(
$this->handle,
$watcher->value,
\Event::READ | \Event::PERSIST,
$this->ioCallback,
$watcher
);
break;
case Watcher::WRITABLE:
$this->events[$id] = new \Event(
$this->handle,
$watcher->value,
\Event::WRITE | \Event::PERSIST,
$this->ioCallback,
$watcher
);
break;
case Watcher::DELAY:
case Watcher::REPEAT:
$this->events[$id] = new \Event(
$this->handle,
-1,
\Event::TIMEOUT | \Event::PERSIST,
$this->timerCallback,
$watcher
);
break;
case Watcher::SIGNAL:
$this->events[$id] = new \Event(
$this->handle,
$watcher->value,
\Event::SIGNAL | \Event::PERSIST,
$this->signalCallback,
$watcher
);
break;
default:
throw new \DomainException("Unknown watcher type");
}
}
switch ($watcher->type) {
case Watcher::DELAY:
case Watcher::REPEAT:
$this->events[$id]->add($watcher->value / self::MILLISEC_PER_SEC);
break;
case Watcher::SIGNAL:
$this->signals[$id] = $this->events[$id];
// No break
default:
$this->events[$id]->add();
break;
}
}
} | [
"protected",
"function",
"activate",
"(",
"array",
"$",
"watchers",
")",
"{",
"foreach",
"(",
"$",
"watchers",
"as",
"$",
"watcher",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"events",
"[",
"$",
"id",
"=",
"$",
"watcher",
"->",
"id... | {@inheritdoc} | [
"{"
] | train | https://github.com/amphp/loop/blob/c7fbdfb7125e03b5653b13db1950fb45344e8e1b/lib/EventLoop.php#L115-L180 |
amphp/loop | lib/EventLoop.php | EventLoop.cancel | public function cancel($watcherIdentifier) {
parent::cancel($watcherIdentifier);
if (isset($this->events[$watcherIdentifier])) {
$this->events[$watcherIdentifier]->free();
unset($this->events[$watcherIdentifier]);
}
} | php | public function cancel($watcherIdentifier) {
parent::cancel($watcherIdentifier);
if (isset($this->events[$watcherIdentifier])) {
$this->events[$watcherIdentifier]->free();
unset($this->events[$watcherIdentifier]);
}
} | [
"public",
"function",
"cancel",
"(",
"$",
"watcherIdentifier",
")",
"{",
"parent",
"::",
"cancel",
"(",
"$",
"watcherIdentifier",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"events",
"[",
"$",
"watcherIdentifier",
"]",
")",
")",
"{",
"$",
"t... | {@inheritdoc} | [
"{"
] | train | https://github.com/amphp/loop/blob/c7fbdfb7125e03b5653b13db1950fb45344e8e1b/lib/EventLoop.php#L198-L205 |
makinacorpus/drupal-ucms | ucms_group/src/Form/GroupSiteAdd.php | GroupSiteAdd.buildForm | public function buildForm(array $form, FormStateInterface $form_state, Group $group = null)
{
if (null === $group) {
return $form;
}
$form['#form_horizontal'] = true;
$form['name'] = [
'#type' => 'textfield',
'#title' => $this->t("Title, administrative title, hostname..."),
'#description' => $this->t("Please make your choice in the suggestions list."),
'#autocomplete_path' => 'admin/dashboard/group/' . $group->getId() . '/sites-add-ac',
'#required' => true,
];
$form['group'] = [
'#type' => 'value',
'#value' => $group->getId(),
];
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t("Add"),
];
return $form;
} | php | public function buildForm(array $form, FormStateInterface $form_state, Group $group = null)
{
if (null === $group) {
return $form;
}
$form['#form_horizontal'] = true;
$form['name'] = [
'#type' => 'textfield',
'#title' => $this->t("Title, administrative title, hostname..."),
'#description' => $this->t("Please make your choice in the suggestions list."),
'#autocomplete_path' => 'admin/dashboard/group/' . $group->getId() . '/sites-add-ac',
'#required' => true,
];
$form['group'] = [
'#type' => 'value',
'#value' => $group->getId(),
];
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t("Add"),
];
return $form;
} | [
"public",
"function",
"buildForm",
"(",
"array",
"$",
"form",
",",
"FormStateInterface",
"$",
"form_state",
",",
"Group",
"$",
"group",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"group",
")",
"{",
"return",
"$",
"form",
";",
"}",
"$",
"fo... | {@inheritdoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_group/src/Form/GroupSiteAdd.php#L52-L80 |
makinacorpus/drupal-ucms | ucms_group/src/Form/GroupSiteAdd.php | GroupSiteAdd.validateForm | public function validateForm(array &$form, FormStateInterface $form_state)
{
$string = $form_state->getValue('name');
$matches = [];
if (preg_match('/\[(\d+)\]$/', $string, $matches) !== 1 || $matches[1] < 2) {
$form_state->setErrorByName('name', $this->t("The site can't be identified."));
} else {
$site = $this->siteManager->getStorage()->findOne($matches[1]);
if (null === $site) {
$form_state->setErrorByName('name', $this->t("The site doesn't exist."));
} else {
$form_state->setTemporaryValue('site', $site);
}
}
} | php | public function validateForm(array &$form, FormStateInterface $form_state)
{
$string = $form_state->getValue('name');
$matches = [];
if (preg_match('/\[(\d+)\]$/', $string, $matches) !== 1 || $matches[1] < 2) {
$form_state->setErrorByName('name', $this->t("The site can't be identified."));
} else {
$site = $this->siteManager->getStorage()->findOne($matches[1]);
if (null === $site) {
$form_state->setErrorByName('name', $this->t("The site doesn't exist."));
} else {
$form_state->setTemporaryValue('site', $site);
}
}
} | [
"public",
"function",
"validateForm",
"(",
"array",
"&",
"$",
"form",
",",
"FormStateInterface",
"$",
"form_state",
")",
"{",
"$",
"string",
"=",
"$",
"form_state",
"->",
"getValue",
"(",
"'name'",
")",
";",
"$",
"matches",
"=",
"[",
"]",
";",
"if",
"(... | {@inheritdoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_group/src/Form/GroupSiteAdd.php#L85-L100 |
makinacorpus/drupal-ucms | ucms_group/src/Form/GroupSiteAdd.php | GroupSiteAdd.submitForm | public function submitForm(array &$form, FormStateInterface $form_state)
{
/** @var \MakinaCorpus\Ucms\Site\Site $site */
$site = $form_state->getTemporaryValue('site');
$groupÎd = $form_state->getValue('group');
$group = $this->groupManager->findOne($groupÎd);
if ($this->groupManager->addSite($groupÎd, $site->getId())) {
drupal_set_message($this->t("%name has been added to group %group.", [
'%name' => $site->getAdminTitle(),
'%group' => $group->getTitle(),
]));
} else {
drupal_set_message($this->t("%name is already in this group %group.", [
'%name' => $site->getAdminTitle(),
'%group' => $group->getTitle(),
]));
}
} | php | public function submitForm(array &$form, FormStateInterface $form_state)
{
/** @var \MakinaCorpus\Ucms\Site\Site $site */
$site = $form_state->getTemporaryValue('site');
$groupÎd = $form_state->getValue('group');
$group = $this->groupManager->findOne($groupÎd);
if ($this->groupManager->addSite($groupÎd, $site->getId())) {
drupal_set_message($this->t("%name has been added to group %group.", [
'%name' => $site->getAdminTitle(),
'%group' => $group->getTitle(),
]));
} else {
drupal_set_message($this->t("%name is already in this group %group.", [
'%name' => $site->getAdminTitle(),
'%group' => $group->getTitle(),
]));
}
} | [
"public",
"function",
"submitForm",
"(",
"array",
"&",
"$",
"form",
",",
"FormStateInterface",
"$",
"form_state",
")",
"{",
"/** @var \\MakinaCorpus\\Ucms\\Site\\Site $site */",
"$",
"site",
"=",
"$",
"form_state",
"->",
"getTemporaryValue",
"(",
"'site'",
")",
";",... | {@inheritdoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_group/src/Form/GroupSiteAdd.php#L105-L123 |
scriptotek/php-oai-pmh-client | src/Records.php | Records.fetchMore | private function fetchMore()
{
if (is_null($this->resumptionToken)) {
$args = array(
'from' => $this->from,
'until' => $this->until,
'set' => $this->set,
);
} else {
$args = array(
'resumptionToken' => $this->resumptionToken,
'metadataPrefix' => null,
);
}
$attempt = 0;
while (true) {
$body = $this->client->request('ListRecords', $args);
try {
$this->lastResponse = new ListRecordsResponse($body);
break;
} catch (\Danmichaelo\QuiteSimpleXMLElement\InvalidXMLException $e) {
$this->emit('request.error', array(
'message' => $e->getMessage(),
));
$attempt++;
if ($attempt > $this->client->maxRetries) {
// Give up
throw new ConnectionError('Failed to get a valid XML response from the server.', null, $e);
}
time_nanosleep(intval($this->client->sleepTimeOnError), intval($this->client->sleepTimeOnError * 1000000000));
}
}
$this->data = $this->lastResponse->records;
if (!is_null($this->lastResponse->numberOfRecords)) {
$this->numberOfRecords = $this->lastResponse->numberOfRecords;
if (!is_null($this->lastResponse->cursor)) {
$this->position = $this->lastResponse->cursor + 1;
}
}
if (isset($this->lastResponse->resumptionToken)) {
$this->resumptionToken = $this->lastResponse->resumptionToken;
} else {
$this->resumptionToken = null;
}
} | php | private function fetchMore()
{
if (is_null($this->resumptionToken)) {
$args = array(
'from' => $this->from,
'until' => $this->until,
'set' => $this->set,
);
} else {
$args = array(
'resumptionToken' => $this->resumptionToken,
'metadataPrefix' => null,
);
}
$attempt = 0;
while (true) {
$body = $this->client->request('ListRecords', $args);
try {
$this->lastResponse = new ListRecordsResponse($body);
break;
} catch (\Danmichaelo\QuiteSimpleXMLElement\InvalidXMLException $e) {
$this->emit('request.error', array(
'message' => $e->getMessage(),
));
$attempt++;
if ($attempt > $this->client->maxRetries) {
// Give up
throw new ConnectionError('Failed to get a valid XML response from the server.', null, $e);
}
time_nanosleep(intval($this->client->sleepTimeOnError), intval($this->client->sleepTimeOnError * 1000000000));
}
}
$this->data = $this->lastResponse->records;
if (!is_null($this->lastResponse->numberOfRecords)) {
$this->numberOfRecords = $this->lastResponse->numberOfRecords;
if (!is_null($this->lastResponse->cursor)) {
$this->position = $this->lastResponse->cursor + 1;
}
}
if (isset($this->lastResponse->resumptionToken)) {
$this->resumptionToken = $this->lastResponse->resumptionToken;
} else {
$this->resumptionToken = null;
}
} | [
"private",
"function",
"fetchMore",
"(",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"resumptionToken",
")",
")",
"{",
"$",
"args",
"=",
"array",
"(",
"'from'",
"=>",
"$",
"this",
"->",
"from",
",",
"'until'",
"=>",
"$",
"this",
"->",
"... | Fetch more records from the service | [
"Fetch",
"more",
"records",
"from",
"the",
"service"
] | train | https://github.com/scriptotek/php-oai-pmh-client/blob/c1da394ccad86962d0f1c2bc120152092e4c1c88/src/Records.php#L105-L153 |
scriptotek/php-oai-pmh-client | src/Records.php | Records.rewind | public function rewind()
{
if ($this->position != $this->initialPosition) {
$this->position = $this->initialPosition;
$this->resumptionToken = $this->initialResumptionToken;
$this->data = array();
$this->fetchMore();
}
} | php | public function rewind()
{
if ($this->position != $this->initialPosition) {
$this->position = $this->initialPosition;
$this->resumptionToken = $this->initialResumptionToken;
$this->data = array();
$this->fetchMore();
}
} | [
"public",
"function",
"rewind",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"position",
"!=",
"$",
"this",
"->",
"initialPosition",
")",
"{",
"$",
"this",
"->",
"position",
"=",
"$",
"this",
"->",
"initialPosition",
";",
"$",
"this",
"->",
"resumption... | Rewind the Iterator to the first element | [
"Rewind",
"the",
"Iterator",
"to",
"the",
"first",
"element"
] | train | https://github.com/scriptotek/php-oai-pmh-client/blob/c1da394ccad86962d0f1c2bc120152092e4c1c88/src/Records.php#L178-L186 |
scriptotek/php-oai-pmh-client | src/Records.php | Records.next | public function next()
{
if (count($this->data) > 0) {
array_shift($this->data);
}
++$this->position;
if (count($this->data) == 0 && !is_null($this->resumptionToken)) {
$this->fetchMore();
}
if (count($this->data) == 0) {
return null;
}
} | php | public function next()
{
if (count($this->data) > 0) {
array_shift($this->data);
}
++$this->position;
if (count($this->data) == 0 && !is_null($this->resumptionToken)) {
$this->fetchMore();
}
if (count($this->data) == 0) {
return null;
}
} | [
"public",
"function",
"next",
"(",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"data",
")",
">",
"0",
")",
"{",
"array_shift",
"(",
"$",
"this",
"->",
"data",
")",
";",
"}",
"++",
"$",
"this",
"->",
"position",
";",
"if",
"(",
"count"... | Move forward to next element | [
"Move",
"forward",
"to",
"next",
"element"
] | train | https://github.com/scriptotek/php-oai-pmh-client/blob/c1da394ccad86962d0f1c2bc120152092e4c1c88/src/Records.php#L191-L205 |
runcmf/runbb | src/RunBB/Core/Parser.php | Parser.configureParser | private function configureParser()
{
$renderer = $parser = null;
$model = new \RunBB\Model\Admin\Parser();
$configurator = new \s9e\TextFormatter\Configurator();
$plugins = unserialize(User::get()->g_parser_plugins);
$useSmilies = false;
foreach ($plugins as $k => $plugin) {
$configurator->plugins->load($plugin);
if ($plugin === 'Emoticons') {
$useSmilies = true;
}
}
if ($useSmilies) {
foreach ($model->getSmilies() as $k => $v) {
$configurator->Emoticons->add($k, $v['html']);
}
}
$configurator->registeredVars['cacheDir'] = ForumEnv::get('FORUM_CACHE_DIR');
// Get an instance of the parser and the renderer
extract($configurator->finalize());
// We save the parser and the renderer to the disk for easy reuse
Utils::checkDir($this->cacheDir);
file_put_contents($this->cacheDir.'/'.User::get()->g_title.'Parser.php', serialize($parser));
file_put_contents($this->cacheDir.'/'.User::get()->g_title.'Renderer.php', serialize($renderer));
$this->parser = $parser;
$this->renderer = $renderer;
} | php | private function configureParser()
{
$renderer = $parser = null;
$model = new \RunBB\Model\Admin\Parser();
$configurator = new \s9e\TextFormatter\Configurator();
$plugins = unserialize(User::get()->g_parser_plugins);
$useSmilies = false;
foreach ($plugins as $k => $plugin) {
$configurator->plugins->load($plugin);
if ($plugin === 'Emoticons') {
$useSmilies = true;
}
}
if ($useSmilies) {
foreach ($model->getSmilies() as $k => $v) {
$configurator->Emoticons->add($k, $v['html']);
}
}
$configurator->registeredVars['cacheDir'] = ForumEnv::get('FORUM_CACHE_DIR');
// Get an instance of the parser and the renderer
extract($configurator->finalize());
// We save the parser and the renderer to the disk for easy reuse
Utils::checkDir($this->cacheDir);
file_put_contents($this->cacheDir.'/'.User::get()->g_title.'Parser.php', serialize($parser));
file_put_contents($this->cacheDir.'/'.User::get()->g_title.'Renderer.php', serialize($renderer));
$this->parser = $parser;
$this->renderer = $renderer;
} | [
"private",
"function",
"configureParser",
"(",
")",
"{",
"$",
"renderer",
"=",
"$",
"parser",
"=",
"null",
";",
"$",
"model",
"=",
"new",
"\\",
"RunBB",
"\\",
"Model",
"\\",
"Admin",
"\\",
"Parser",
"(",
")",
";",
"$",
"configurator",
"=",
"new",
"\\... | Build bundle for user group | [
"Build",
"bundle",
"for",
"user",
"group"
] | train | https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Core/Parser.php#L46-L81 |
runcmf/runbb | src/RunBB/Core/Parser.php | Parser.parseMessage | public function parseMessage($text, $hide_smilies = 0)
{
if (ForumSettings::get('o_censoring') == '1') {
$text = Utils::censor($text);
}
// FIXME check text length
if ($hide_smilies) {
$this->parser->disablePlugin('Emoticons');
}
if (ForumSettings::get('p_message_img_tag') !== '1' ||
ForumSettings::get('p_sig_img_tag') !== '1' ||
User::get()['show_img'] !== '1' ||
User::get()['show_img_sig'] !== '1'
) {
$this->parser->disablePlugin('Autoimage');
$this->parser->disablePlugin('Autovideo');
}
$xml = $this->parser->parse($text);
$html = $this->renderer->render($xml);
return $html;
} | php | public function parseMessage($text, $hide_smilies = 0)
{
if (ForumSettings::get('o_censoring') == '1') {
$text = Utils::censor($text);
}
// FIXME check text length
if ($hide_smilies) {
$this->parser->disablePlugin('Emoticons');
}
if (ForumSettings::get('p_message_img_tag') !== '1' ||
ForumSettings::get('p_sig_img_tag') !== '1' ||
User::get()['show_img'] !== '1' ||
User::get()['show_img_sig'] !== '1'
) {
$this->parser->disablePlugin('Autoimage');
$this->parser->disablePlugin('Autovideo');
}
$xml = $this->parser->parse($text);
$html = $this->renderer->render($xml);
return $html;
} | [
"public",
"function",
"parseMessage",
"(",
"$",
"text",
",",
"$",
"hide_smilies",
"=",
"0",
")",
"{",
"if",
"(",
"ForumSettings",
"::",
"get",
"(",
"'o_censoring'",
")",
"==",
"'1'",
")",
"{",
"$",
"text",
"=",
"Utils",
"::",
"censor",
"(",
"$",
"tex... | Parse message, post or signature message text.
@param string $text
@param integer $hide_smilies
@return string html | [
"Parse",
"message",
"post",
"or",
"signature",
"message",
"text",
"."
] | train | https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Core/Parser.php#L90-L112 |
runcmf/runbb | src/RunBB/Core/Parser.php | Parser.parseForSave | public function parseForSave($text, &$errors, $is_signature = false)
{
// FIXME check text length
if ($is_signature && (ForumSettings::get('p_sig_img_tag') !== '1' || User::get()['show_img_sig'] !== '1')) {
$this->parser->disablePlugin('Autoimage');
$this->parser->disablePlugin('Autovideo');
}
$xml = $this->parser->parse($text);
// $html = $this->renderer->render($xml);
// TODO check parser errors ??? not found problems in parser
// TODO check nestingLimit ??? not found problems in parser
// TODO check $is_signature limits
// $parserErrors = $this->parser->getLogger()->get();
// if (!empty($parserErrors)) {
//tdie($parserErrors);
// }
return \s9e\TextFormatter\Unparser::unparse($xml);
} | php | public function parseForSave($text, &$errors, $is_signature = false)
{
// FIXME check text length
if ($is_signature && (ForumSettings::get('p_sig_img_tag') !== '1' || User::get()['show_img_sig'] !== '1')) {
$this->parser->disablePlugin('Autoimage');
$this->parser->disablePlugin('Autovideo');
}
$xml = $this->parser->parse($text);
// $html = $this->renderer->render($xml);
// TODO check parser errors ??? not found problems in parser
// TODO check nestingLimit ??? not found problems in parser
// TODO check $is_signature limits
// $parserErrors = $this->parser->getLogger()->get();
// if (!empty($parserErrors)) {
//tdie($parserErrors);
// }
return \s9e\TextFormatter\Unparser::unparse($xml);
} | [
"public",
"function",
"parseForSave",
"(",
"$",
"text",
",",
"&",
"$",
"errors",
",",
"$",
"is_signature",
"=",
"false",
")",
"{",
"// FIXME check text length",
"if",
"(",
"$",
"is_signature",
"&&",
"(",
"ForumSettings",
"::",
"get",
"(",
"'p_sig_img_tag'",
... | Parse message, post or signature message text.
Check errors
@param string $text
@return string | [
"Parse",
"message",
"post",
"or",
"signature",
"message",
"text",
".",
"Check",
"errors"
] | train | https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Core/Parser.php#L121-L140 |
tremendus/amazon-mws | src/MarketplaceWebService/Model.php | MarketplaceWebService_Model.fromAssociativeArray | private function fromAssociativeArray(array $array)
{
foreach ($this->fields as $fieldName => $field) {
$fieldType = $field['FieldType'];
if (is_array($fieldType)) {
if ($this->isComplexType($fieldType[0])) {
if (array_key_exists($fieldName, $array)) {
$elements = $array[$fieldName];
if (!$this->isNumericArray($elements)) {
$elements = array($elements);
}
if (count ($elements) >= 1) {
require_once (str_replace('_', DIRECTORY_SEPARATOR, $fieldType[0]) . ".php");
foreach ($elements as $element) {
$this->fields[$fieldName]['FieldValue'][] = new $fieldType[0]($element);
}
}
}
} else {
if (array_key_exists($fieldName, $array)) {
$elements = $array[$fieldName];
if (!$this->isNumericArray($elements)) {
$elements = array($elements);
}
if (count ($elements) >= 1) {
foreach ($elements as $element) {
$this->fields[$fieldName]['FieldValue'][] = $element;
}
}
}
}
} else {
if ($this->isComplexType($fieldType)) {
if (array_key_exists($fieldName, $array)) {
require_once (str_replace('_', DIRECTORY_SEPARATOR, $fieldType) . ".php");
$this->fields[$fieldName]['FieldValue'] = new $fieldType($array[$fieldName]);
}
} else {
if (array_key_exists($fieldName, $array)) {
$this->fields[$fieldName]['FieldValue'] = $array[$fieldName];
}
}
}
}
} | php | private function fromAssociativeArray(array $array)
{
foreach ($this->fields as $fieldName => $field) {
$fieldType = $field['FieldType'];
if (is_array($fieldType)) {
if ($this->isComplexType($fieldType[0])) {
if (array_key_exists($fieldName, $array)) {
$elements = $array[$fieldName];
if (!$this->isNumericArray($elements)) {
$elements = array($elements);
}
if (count ($elements) >= 1) {
require_once (str_replace('_', DIRECTORY_SEPARATOR, $fieldType[0]) . ".php");
foreach ($elements as $element) {
$this->fields[$fieldName]['FieldValue'][] = new $fieldType[0]($element);
}
}
}
} else {
if (array_key_exists($fieldName, $array)) {
$elements = $array[$fieldName];
if (!$this->isNumericArray($elements)) {
$elements = array($elements);
}
if (count ($elements) >= 1) {
foreach ($elements as $element) {
$this->fields[$fieldName]['FieldValue'][] = $element;
}
}
}
}
} else {
if ($this->isComplexType($fieldType)) {
if (array_key_exists($fieldName, $array)) {
require_once (str_replace('_', DIRECTORY_SEPARATOR, $fieldType) . ".php");
$this->fields[$fieldName]['FieldValue'] = new $fieldType($array[$fieldName]);
}
} else {
if (array_key_exists($fieldName, $array)) {
$this->fields[$fieldName]['FieldValue'] = $array[$fieldName];
}
}
}
}
} | [
"private",
"function",
"fromAssociativeArray",
"(",
"array",
"$",
"array",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"fields",
"as",
"$",
"fieldName",
"=>",
"$",
"field",
")",
"{",
"$",
"fieldType",
"=",
"$",
"field",
"[",
"'FieldType'",
"]",
";",
"... | Construct from Associative Array
@param array $array associative array to construct from | [
"Construct",
"from",
"Associative",
"Array"
] | train | https://github.com/tremendus/amazon-mws/blob/465312b0b75fb91ff9ae4ce63b6c299b6f7e030d/src/MarketplaceWebService/Model.php#L222-L266 |
makinacorpus/drupal-ucms | ucms_seo/src/Controller/SitemapController.php | SitemapController.displayAction | public function displayAction($display = 'html')
{
$site = $this->get('ucms_site.manager')->getContext();
$menus = $this->get('umenu.menu_storage')->loadWithConditions(['site_id' => $site->getId()]);
if ('xml' === $display) {
return $this->displayXML($menus);
}
return $this->displayHTML($menus);
} | php | public function displayAction($display = 'html')
{
$site = $this->get('ucms_site.manager')->getContext();
$menus = $this->get('umenu.menu_storage')->loadWithConditions(['site_id' => $site->getId()]);
if ('xml' === $display) {
return $this->displayXML($menus);
}
return $this->displayHTML($menus);
} | [
"public",
"function",
"displayAction",
"(",
"$",
"display",
"=",
"'html'",
")",
"{",
"$",
"site",
"=",
"$",
"this",
"->",
"get",
"(",
"'ucms_site.manager'",
")",
"->",
"getContext",
"(",
")",
";",
"$",
"menus",
"=",
"$",
"this",
"->",
"get",
"(",
"'u... | Display site map action | [
"Display",
"site",
"map",
"action"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/Controller/SitemapController.php#L26-L36 |
makinacorpus/drupal-ucms | ucms_seo/src/Controller/SitemapController.php | SitemapController.displayXML | private function displayXML($menus)
{
$treeList = [];
$manager = $this->getTreeManager();
/** @var \MakinaCorpus\Umenu\Menu $menu */
foreach ($menus as $menu) {
$tree = $manager->buildTree($menu->getId(), true);
if (!$tree->isEmpty()) {
$treeList[] = $tree;
}
}
$output = $this->renderView('@ucms_seo/views/sitemap.xml.twig', ['menus_tree' => $treeList]);
return new Response($output, 200, ['content-type' => 'application/xml']);
} | php | private function displayXML($menus)
{
$treeList = [];
$manager = $this->getTreeManager();
/** @var \MakinaCorpus\Umenu\Menu $menu */
foreach ($menus as $menu) {
$tree = $manager->buildTree($menu->getId(), true);
if (!$tree->isEmpty()) {
$treeList[] = $tree;
}
}
$output = $this->renderView('@ucms_seo/views/sitemap.xml.twig', ['menus_tree' => $treeList]);
return new Response($output, 200, ['content-type' => 'application/xml']);
} | [
"private",
"function",
"displayXML",
"(",
"$",
"menus",
")",
"{",
"$",
"treeList",
"=",
"[",
"]",
";",
"$",
"manager",
"=",
"$",
"this",
"->",
"getTreeManager",
"(",
")",
";",
"/** @var \\MakinaCorpus\\Umenu\\Menu $menu */",
"foreach",
"(",
"$",
"menus",
"as... | Display site map as XML
@param Menu[]
@return string | [
"Display",
"site",
"map",
"as",
"XML"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/Controller/SitemapController.php#L45-L61 |
makinacorpus/drupal-ucms | ucms_seo/src/Controller/SitemapController.php | SitemapController.displayHTML | private function displayHTML($menus)
{
$build = [];
$manager = $this->getTreeManager();
/** @var \MakinaCorpus\Umenu\Menu $menu */
foreach ($menus as $menu) {
if ($menu->isSiteMain() || !$menu->hasRole()) {
$tree = $manager->buildTree($menu->getId(), true);
if (!$tree->isEmpty()) {
$build[$menu->getTitle()] = $tree;
}
}
}
return theme('ucms_seo_sitemap', ['menus' => $build]);
} | php | private function displayHTML($menus)
{
$build = [];
$manager = $this->getTreeManager();
/** @var \MakinaCorpus\Umenu\Menu $menu */
foreach ($menus as $menu) {
if ($menu->isSiteMain() || !$menu->hasRole()) {
$tree = $manager->buildTree($menu->getId(), true);
if (!$tree->isEmpty()) {
$build[$menu->getTitle()] = $tree;
}
}
}
return theme('ucms_seo_sitemap', ['menus' => $build]);
} | [
"private",
"function",
"displayHTML",
"(",
"$",
"menus",
")",
"{",
"$",
"build",
"=",
"[",
"]",
";",
"$",
"manager",
"=",
"$",
"this",
"->",
"getTreeManager",
"(",
")",
";",
"/** @var \\MakinaCorpus\\Umenu\\Menu $menu */",
"foreach",
"(",
"$",
"menus",
"as",... | Display site map as HTML
@param Menu[]
@return string | [
"Display",
"site",
"map",
"as",
"HTML"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/Controller/SitemapController.php#L70-L86 |
makinacorpus/drupal-ucms | ucms_seo/src/EventDispatcher/SiteEventSubscriber.php | SiteEventSubscriber.onInit | public function onInit(SiteInitEvent $event)
{
// Naive alias lookup for the current page
$site = $event->getSite();
$request = $event->getRequest();
$incomming = $request->query->get('q');
$nodeId = $this->service->getAliasManager()->matchPath($incomming, $site->getId());
if ($nodeId) {
// $_GET['q'] reference will be useless for Drupal 8
$_GET['q'] = $incomming = 'node/' . $nodeId;
$request->query->set('q', $incomming);
$request->attributes->set('_route', $incomming);
}
// Set current context to the alias manager
$this
->service
->getAliasCacheLookup()
->setEnvironment(
$site->getId(),
$incomming,
$request->query->all()
)
;
} | php | public function onInit(SiteInitEvent $event)
{
// Naive alias lookup for the current page
$site = $event->getSite();
$request = $event->getRequest();
$incomming = $request->query->get('q');
$nodeId = $this->service->getAliasManager()->matchPath($incomming, $site->getId());
if ($nodeId) {
// $_GET['q'] reference will be useless for Drupal 8
$_GET['q'] = $incomming = 'node/' . $nodeId;
$request->query->set('q', $incomming);
$request->attributes->set('_route', $incomming);
}
// Set current context to the alias manager
$this
->service
->getAliasCacheLookup()
->setEnvironment(
$site->getId(),
$incomming,
$request->query->all()
)
;
} | [
"public",
"function",
"onInit",
"(",
"SiteInitEvent",
"$",
"event",
")",
"{",
"// Naive alias lookup for the current page",
"$",
"site",
"=",
"$",
"event",
"->",
"getSite",
"(",
")",
";",
"$",
"request",
"=",
"$",
"event",
"->",
"getRequest",
"(",
")",
";",
... | Site is being initialized, and hopefully at this stage current menu
item has never been loaded, so alter the current path to something
else, before Drupal router gets to us. | [
"Site",
"is",
"being",
"initialized",
"and",
"hopefully",
"at",
"this",
"stage",
"current",
"menu",
"item",
"has",
"never",
"been",
"loaded",
"so",
"alter",
"the",
"current",
"path",
"to",
"something",
"else",
"before",
"Drupal",
"router",
"gets",
"to",
"us"... | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/EventDispatcher/SiteEventSubscriber.php#L55-L80 |
makinacorpus/drupal-ucms | ucms_seo/src/EventDispatcher/SiteEventSubscriber.php | SiteEventSubscriber.onMasterInit | public function onMasterInit(MasterInitEvent $event)
{
$request = $event->getRequest();
$this
->service
->getAliasCacheLookup()
->setEnvironment(
null,
$request->query->get('q'),
$request->query->all()
)
;
} | php | public function onMasterInit(MasterInitEvent $event)
{
$request = $event->getRequest();
$this
->service
->getAliasCacheLookup()
->setEnvironment(
null,
$request->query->get('q'),
$request->query->all()
)
;
} | [
"public",
"function",
"onMasterInit",
"(",
"MasterInitEvent",
"$",
"event",
")",
"{",
"$",
"request",
"=",
"$",
"event",
"->",
"getRequest",
"(",
")",
";",
"$",
"this",
"->",
"service",
"->",
"getAliasCacheLookup",
"(",
")",
"->",
"setEnvironment",
"(",
"n... | We have no site context, we are in admin. | [
"We",
"have",
"no",
"site",
"context",
"we",
"are",
"in",
"admin",
"."
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/EventDispatcher/SiteEventSubscriber.php#L85-L98 |
makinacorpus/drupal-ucms | ucms_search/src/Lucene/CollectionQuery.php | CollectionQuery.removeElement | protected function removeElement(AbstractQuery $element)
{
foreach ($this->elements as $key => $existing) {
if ($existing === $element) {
unset($this->elements[$key]);
}
}
return $this;
} | php | protected function removeElement(AbstractQuery $element)
{
foreach ($this->elements as $key => $existing) {
if ($existing === $element) {
unset($this->elements[$key]);
}
}
return $this;
} | [
"protected",
"function",
"removeElement",
"(",
"AbstractQuery",
"$",
"element",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"elements",
"as",
"$",
"key",
"=>",
"$",
"existing",
")",
"{",
"if",
"(",
"$",
"existing",
"===",
"$",
"element",
")",
"{",
"un... | Remove element
@param AbstractQuery $element
@return CollectionQuery | [
"Remove",
"element"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/Lucene/CollectionQuery.php#L62-L71 |
makinacorpus/drupal-ucms | ucms_search/src/Lucene/CollectionQuery.php | CollectionQuery.setOperator | public function setOperator($operator)
{
if ($operator !== null && $operator !== Query::OP_AND && $operator !== Query::OP_OR) {
throw new \InvalidArgumentException("Operator must be Query::OP_AND or Query::OP_OR");
}
$this->operator = $operator;
return $this;
} | php | public function setOperator($operator)
{
if ($operator !== null && $operator !== Query::OP_AND && $operator !== Query::OP_OR) {
throw new \InvalidArgumentException("Operator must be Query::OP_AND or Query::OP_OR");
}
$this->operator = $operator;
return $this;
} | [
"public",
"function",
"setOperator",
"(",
"$",
"operator",
")",
"{",
"if",
"(",
"$",
"operator",
"!==",
"null",
"&&",
"$",
"operator",
"!==",
"Query",
"::",
"OP_AND",
"&&",
"$",
"operator",
"!==",
"Query",
"::",
"OP_OR",
")",
"{",
"throw",
"new",
"\\",... | Set default operator
@param string $operator
@return CollectionQuery | [
"Set",
"default",
"operator"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/Lucene/CollectionQuery.php#L80-L89 |
makinacorpus/drupal-ucms | ucms_search/src/Lucene/CollectionQuery.php | CollectionQuery.toRawString | protected function toRawString()
{
if (empty($this->elements)) {
return '';
}
if (count($this->elements) > 1) {
$operator = ($this->operator ? (' ' . $this->operator . ' ') : ' ');
return '(' . implode($operator, $this->elements) . ')';
} else {
reset($this->elements);
return (string)current($this->elements);
}
} | php | protected function toRawString()
{
if (empty($this->elements)) {
return '';
}
if (count($this->elements) > 1) {
$operator = ($this->operator ? (' ' . $this->operator . ' ') : ' ');
return '(' . implode($operator, $this->elements) . ')';
} else {
reset($this->elements);
return (string)current($this->elements);
}
} | [
"protected",
"function",
"toRawString",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"elements",
")",
")",
"{",
"return",
"''",
";",
"}",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"elements",
")",
">",
"1",
")",
"{",
"$",
"operato... | {@inheritdoc} | [
"{"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/Lucene/CollectionQuery.php#L104-L116 |
despark/ignicms | public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Exceptions.php | CI_Exceptions.log_exception | function log_exception($severity, $message, $filepath, $line)
{
$severity = ( ! isset($this->levels[$severity])) ? $severity : $this->levels[$severity];
log_message('error', 'Severity: '.$severity.' --> '.$message. ' '.$filepath.' '.$line, TRUE);
} | php | function log_exception($severity, $message, $filepath, $line)
{
$severity = ( ! isset($this->levels[$severity])) ? $severity : $this->levels[$severity];
log_message('error', 'Severity: '.$severity.' --> '.$message. ' '.$filepath.' '.$line, TRUE);
} | [
"function",
"log_exception",
"(",
"$",
"severity",
",",
"$",
"message",
",",
"$",
"filepath",
",",
"$",
"line",
")",
"{",
"$",
"severity",
"=",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"levels",
"[",
"$",
"severity",
"]",
")",
")",
"?",
"$",
"s... | Exception Logger
This function logs PHP generated error messages
@access private
@param string the error severity
@param string the error string
@param string the error filepath
@param string the error line number
@return string | [
"Exception",
"Logger"
] | train | https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Exceptions.php#L87-L92 |
despark/ignicms | public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Exceptions.php | CI_Exceptions.show_404 | function show_404($page = '', $log_error = TRUE)
{
$heading = "404 Page Not Found";
$message = "The page you requested was not found.";
// By default we log this, but allow a dev to skip it
if ($log_error)
{
log_message('error', '404 Page Not Found --> '.$page);
}
echo $this->show_error($heading, $message, 'error_404', 404);
exit;
} | php | function show_404($page = '', $log_error = TRUE)
{
$heading = "404 Page Not Found";
$message = "The page you requested was not found.";
// By default we log this, but allow a dev to skip it
if ($log_error)
{
log_message('error', '404 Page Not Found --> '.$page);
}
echo $this->show_error($heading, $message, 'error_404', 404);
exit;
} | [
"function",
"show_404",
"(",
"$",
"page",
"=",
"''",
",",
"$",
"log_error",
"=",
"TRUE",
")",
"{",
"$",
"heading",
"=",
"\"404 Page Not Found\"",
";",
"$",
"message",
"=",
"\"The page you requested was not found.\"",
";",
"// By default we log this, but allow a dev to... | 404 Page Not Found Handler
@access private
@param string the page
@param bool log error yes/no
@return string | [
"404",
"Page",
"Not",
"Found",
"Handler"
] | train | https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Exceptions.php#L104-L117 |
despark/ignicms | public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Exceptions.php | CI_Exceptions.show_error | function show_error($heading, $message, $template = 'error_general', $status_code = 500)
{
set_status_header($status_code);
$message = '<p>'.implode('</p><p>', ( ! is_array($message)) ? array($message) : $message).'</p>';
if (ob_get_level() > $this->ob_level + 1)
{
ob_end_flush();
}
ob_start();
include(APPPATH.'errors/'.$template.'.php');
$buffer = ob_get_contents();
ob_end_clean();
return $buffer;
} | php | function show_error($heading, $message, $template = 'error_general', $status_code = 500)
{
set_status_header($status_code);
$message = '<p>'.implode('</p><p>', ( ! is_array($message)) ? array($message) : $message).'</p>';
if (ob_get_level() > $this->ob_level + 1)
{
ob_end_flush();
}
ob_start();
include(APPPATH.'errors/'.$template.'.php');
$buffer = ob_get_contents();
ob_end_clean();
return $buffer;
} | [
"function",
"show_error",
"(",
"$",
"heading",
",",
"$",
"message",
",",
"$",
"template",
"=",
"'error_general'",
",",
"$",
"status_code",
"=",
"500",
")",
"{",
"set_status_header",
"(",
"$",
"status_code",
")",
";",
"$",
"message",
"=",
"'<p>'",
".",
"i... | General Error Page
This function takes an error message as input
(either as a string or an array) and displays
it using the specified template.
@access private
@param string the heading
@param string the message
@param string the template name
@param int the status code
@return string | [
"General",
"Error",
"Page"
] | train | https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Exceptions.php#L135-L150 |
despark/ignicms | public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Exceptions.php | CI_Exceptions.show_php_error | function show_php_error($severity, $message, $filepath, $line)
{
$severity = ( ! isset($this->levels[$severity])) ? $severity : $this->levels[$severity];
$filepath = str_replace("\\", "/", $filepath);
// For safety reasons we do not show the full file path
if (FALSE !== strpos($filepath, '/'))
{
$x = explode('/', $filepath);
$filepath = $x[count($x)-2].'/'.end($x);
}
if (ob_get_level() > $this->ob_level + 1)
{
ob_end_flush();
}
ob_start();
include(APPPATH.'errors/error_php.php');
$buffer = ob_get_contents();
ob_end_clean();
echo $buffer;
} | php | function show_php_error($severity, $message, $filepath, $line)
{
$severity = ( ! isset($this->levels[$severity])) ? $severity : $this->levels[$severity];
$filepath = str_replace("\\", "/", $filepath);
// For safety reasons we do not show the full file path
if (FALSE !== strpos($filepath, '/'))
{
$x = explode('/', $filepath);
$filepath = $x[count($x)-2].'/'.end($x);
}
if (ob_get_level() > $this->ob_level + 1)
{
ob_end_flush();
}
ob_start();
include(APPPATH.'errors/error_php.php');
$buffer = ob_get_contents();
ob_end_clean();
echo $buffer;
} | [
"function",
"show_php_error",
"(",
"$",
"severity",
",",
"$",
"message",
",",
"$",
"filepath",
",",
"$",
"line",
")",
"{",
"$",
"severity",
"=",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"levels",
"[",
"$",
"severity",
"]",
")",
")",
"?",
"$",
"... | Native PHP error handler
@access private
@param string the error severity
@param string the error string
@param string the error filepath
@param string the error line number
@return string | [
"Native",
"PHP",
"error",
"handler"
] | train | https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Exceptions.php#L164-L186 |
makinacorpus/drupal-ucms | ucms_seo/src/SeoService.php | SeoService.getNodeAliasMap | protected function getNodeAliasMap(array $nodeIdList) : array
{
return $this
->database
->select('ucms_seo_node', 'n')
->fields('n', ['nid', 'alias_segment'])
->condition('n.nid', $nodeIdList)
->execute()
->fetchAllKeyed()
;
} | php | protected function getNodeAliasMap(array $nodeIdList) : array
{
return $this
->database
->select('ucms_seo_node', 'n')
->fields('n', ['nid', 'alias_segment'])
->condition('n.nid', $nodeIdList)
->execute()
->fetchAllKeyed()
;
} | [
"protected",
"function",
"getNodeAliasMap",
"(",
"array",
"$",
"nodeIdList",
")",
":",
"array",
"{",
"return",
"$",
"this",
"->",
"database",
"->",
"select",
"(",
"'ucms_seo_node'",
",",
"'n'",
")",
"->",
"fields",
"(",
"'n'",
",",
"[",
"'nid'",
",",
"'a... | Get aliases for the given nodes
@return string[]
Keys are node identifiers, values are alias segment for each node,
order is no guaranted, non existing nodes or node without a segment
will be excluded from the return array | [
"Get",
"aliases",
"for",
"the",
"given",
"nodes"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/SeoService.php#L125-L135 |
makinacorpus/drupal-ucms | ucms_seo/src/SeoService.php | SeoService.userCanEditSiteSeo | public function userCanEditSiteSeo(AccountInterface $account, Site $site) : bool
{
return
$this->isGranted(Permission::VIEW, $site, $account) && (
$account->hasPermission(SeoService::PERM_SEO_GLOBAL) ||
$account->hasPermission(SeoService::PERM_SEO_CONTENT_ALL) ||
$this->siteManager->getAccess()->userIsWebmaster($account, $site)
)
;
} | php | public function userCanEditSiteSeo(AccountInterface $account, Site $site) : bool
{
return
$this->isGranted(Permission::VIEW, $site, $account) && (
$account->hasPermission(SeoService::PERM_SEO_GLOBAL) ||
$account->hasPermission(SeoService::PERM_SEO_CONTENT_ALL) ||
$this->siteManager->getAccess()->userIsWebmaster($account, $site)
)
;
} | [
"public",
"function",
"userCanEditSiteSeo",
"(",
"AccountInterface",
"$",
"account",
",",
"Site",
"$",
"site",
")",
":",
"bool",
"{",
"return",
"$",
"this",
"->",
"isGranted",
"(",
"Permission",
"::",
"VIEW",
",",
"$",
"site",
",",
"$",
"account",
")",
"... | Can user edit SEO parameters for site | [
"Can",
"user",
"edit",
"SEO",
"parameters",
"for",
"site"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/SeoService.php#L140-L149 |
makinacorpus/drupal-ucms | ucms_seo/src/SeoService.php | SeoService.userCanEditNodeSeo | public function userCanEditNodeSeo(AccountInterface $account, NodeInterface $node) : bool
{
return
!$this->isNodeBlacklisted($node) && (
($account->hasPermission(SeoService::PERM_SEO_CONTENT_OWN) && $node->access('update', $account)) ||
($account->hasPermission(SeoService::PERM_SEO_CONTENT_ALL) && $node->access('view', $account))
)
;
} | php | public function userCanEditNodeSeo(AccountInterface $account, NodeInterface $node) : bool
{
return
!$this->isNodeBlacklisted($node) && (
($account->hasPermission(SeoService::PERM_SEO_CONTENT_OWN) && $node->access('update', $account)) ||
($account->hasPermission(SeoService::PERM_SEO_CONTENT_ALL) && $node->access('view', $account))
)
;
} | [
"public",
"function",
"userCanEditNodeSeo",
"(",
"AccountInterface",
"$",
"account",
",",
"NodeInterface",
"$",
"node",
")",
":",
"bool",
"{",
"return",
"!",
"$",
"this",
"->",
"isNodeBlacklisted",
"(",
"$",
"node",
")",
"&&",
"(",
"(",
"$",
"account",
"->... | Can user edit SEO parameters for node | [
"Can",
"user",
"edit",
"SEO",
"parameters",
"for",
"node"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/SeoService.php#L154-L162 |
makinacorpus/drupal-ucms | ucms_seo/src/SeoService.php | SeoService.isNodeTypeBlacklisted | public function isNodeTypeBlacklisted(string $type) : bool
{
return $this->nodeTypeBlacklist && isset($this->nodeTypeBlacklist[$type]);
} | php | public function isNodeTypeBlacklisted(string $type) : bool
{
return $this->nodeTypeBlacklist && isset($this->nodeTypeBlacklist[$type]);
} | [
"public",
"function",
"isNodeTypeBlacklisted",
"(",
"string",
"$",
"type",
")",
":",
"bool",
"{",
"return",
"$",
"this",
"->",
"nodeTypeBlacklist",
"&&",
"isset",
"(",
"$",
"this",
"->",
"nodeTypeBlacklist",
"[",
"$",
"type",
"]",
")",
";",
"}"
] | Is node type blacklisted for SEO handling | [
"Is",
"node",
"type",
"blacklisted",
"for",
"SEO",
"handling"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/SeoService.php#L167-L170 |
makinacorpus/drupal-ucms | ucms_seo/src/SeoService.php | SeoService.isNodeBlacklisted | public function isNodeBlacklisted(NodeInterface $node) : bool
{
return $this->nodeTypeBlacklist && isset($this->nodeTypeBlacklist[$node->bundle()]);
} | php | public function isNodeBlacklisted(NodeInterface $node) : bool
{
return $this->nodeTypeBlacklist && isset($this->nodeTypeBlacklist[$node->bundle()]);
} | [
"public",
"function",
"isNodeBlacklisted",
"(",
"NodeInterface",
"$",
"node",
")",
":",
"bool",
"{",
"return",
"$",
"this",
"->",
"nodeTypeBlacklist",
"&&",
"isset",
"(",
"$",
"this",
"->",
"nodeTypeBlacklist",
"[",
"$",
"node",
"->",
"bundle",
"(",
")",
"... | Is node blacklisted for SEO handling | [
"Is",
"node",
"blacklisted",
"for",
"SEO",
"handling"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/SeoService.php#L175-L178 |
makinacorpus/drupal-ucms | ucms_seo/src/SeoService.php | SeoService.setNodeMeta | public function setNodeMeta(NodeInterface $node, array $values = []) : void
{
if ($this->isNodeBlacklisted($node)) {
return;
}
$sqlValues = [];
foreach ($values as $key => $value) {
if (empty($value)) {
$value = null;
}
switch ($key) {
case 'title':
case 'description':
$sqlValues['meta_' . $key] = $value;
break;
default:
continue;
}
}
if (empty($values)) {
return;
}
$this
->database
->update('ucms_seo_node')
->fields($sqlValues)
->condition('nid', $node->id())
->execute()
;
// @todo clear page cache
} | php | public function setNodeMeta(NodeInterface $node, array $values = []) : void
{
if ($this->isNodeBlacklisted($node)) {
return;
}
$sqlValues = [];
foreach ($values as $key => $value) {
if (empty($value)) {
$value = null;
}
switch ($key) {
case 'title':
case 'description':
$sqlValues['meta_' . $key] = $value;
break;
default:
continue;
}
}
if (empty($values)) {
return;
}
$this
->database
->update('ucms_seo_node')
->fields($sqlValues)
->condition('nid', $node->id())
->execute()
;
// @todo clear page cache
} | [
"public",
"function",
"setNodeMeta",
"(",
"NodeInterface",
"$",
"node",
",",
"array",
"$",
"values",
"=",
"[",
"]",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"isNodeBlacklisted",
"(",
"$",
"node",
")",
")",
"{",
"return",
";",
"}",
"$",
... | Set node meta information
@param NodeInterface $node
@param string[] $values
Keys are meta tag title, values are meta tag content | [
"Set",
"node",
"meta",
"information"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/SeoService.php#L187-L226 |
makinacorpus/drupal-ucms | ucms_seo/src/SeoService.php | SeoService.getNodeMeta | public function getNodeMeta(NodeInterface $node) : array
{
if ($this->isNodeBlacklisted($node)) {
return [];
}
return (array)$this->database->query("SELECT meta_title AS title, meta_description AS description FROM {ucms_seo_node} WHERE nid = ?", [$node->id()])->fetchAssoc();
} | php | public function getNodeMeta(NodeInterface $node) : array
{
if ($this->isNodeBlacklisted($node)) {
return [];
}
return (array)$this->database->query("SELECT meta_title AS title, meta_description AS description FROM {ucms_seo_node} WHERE nid = ?", [$node->id()])->fetchAssoc();
} | [
"public",
"function",
"getNodeMeta",
"(",
"NodeInterface",
"$",
"node",
")",
":",
"array",
"{",
"if",
"(",
"$",
"this",
"->",
"isNodeBlacklisted",
"(",
"$",
"node",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"return",
"(",
"array",
")",
"$",
"this"... | Get node meta information
@param NodeInterface $node
@return string[] $values
Keys are meta tag title, values are meta tag content | [
"Get",
"node",
"meta",
"information"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/SeoService.php#L236-L243 |
makinacorpus/drupal-ucms | ucms_seo/src/SeoService.php | SeoService.getNodeLocalCanonical | public function getNodeLocalCanonical(NodeInterface $node) : ?string
{
if ($this->isNodeBlacklisted($node)) {
return 'node/' . $node->id();
}
if ($this->siteManager->hasContext()) {
return $this->aliasManager->getPathAlias($node->id(), $this->siteManager->getContext()->getId());
}
} | php | public function getNodeLocalCanonical(NodeInterface $node) : ?string
{
if ($this->isNodeBlacklisted($node)) {
return 'node/' . $node->id();
}
if ($this->siteManager->hasContext()) {
return $this->aliasManager->getPathAlias($node->id(), $this->siteManager->getContext()->getId());
}
} | [
"public",
"function",
"getNodeLocalCanonical",
"(",
"NodeInterface",
"$",
"node",
")",
":",
"?",
"string",
"{",
"if",
"(",
"$",
"this",
"->",
"isNodeBlacklisted",
"(",
"$",
"node",
")",
")",
"{",
"return",
"'node/'",
".",
"$",
"node",
"->",
"id",
"(",
... | Get node canonical alias for the current site | [
"Get",
"node",
"canonical",
"alias",
"for",
"the",
"current",
"site"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/SeoService.php#L248-L257 |
makinacorpus/drupal-ucms | ucms_seo/src/SeoService.php | SeoService.getNodeCanonical | public function getNodeCanonical(NodeInterface $node) : ?string
{
if ($this->isNodeBlacklisted($node)) {
return null;
}
$site = null;
$alias = null;
if ($this->shareCanonicalAcrossSites) {
$storage = $this->siteManager->getStorage();
// Very fist site is the right one for canonical URL
if ($node->site_id) {
$site = $storage->findOne($node->site_id);
if ($site->getState() !== SiteState::ON) {
$site = null;
}
}
}
// If no site, fetch on the current site
if (!$site) {
if ($this->siteManager->hasContext()) {
$site = $this->siteManager->getContext();
}
}
if ($site) {
$alias = $this->aliasManager->getPathAlias($node->id(), $site->getId());
}
if (!$alias) {
// No alias at all means that the canonical is the node URL in the
// current site, I am sorry I can't provide more any magic here...
return url('node/' . $node->id(), ['absolute' => true]);
}
return $this->siteManager->getUrlGenerator()->generateUrl($site, $alias, ['absolute' => true], true);
} | php | public function getNodeCanonical(NodeInterface $node) : ?string
{
if ($this->isNodeBlacklisted($node)) {
return null;
}
$site = null;
$alias = null;
if ($this->shareCanonicalAcrossSites) {
$storage = $this->siteManager->getStorage();
// Very fist site is the right one for canonical URL
if ($node->site_id) {
$site = $storage->findOne($node->site_id);
if ($site->getState() !== SiteState::ON) {
$site = null;
}
}
}
// If no site, fetch on the current site
if (!$site) {
if ($this->siteManager->hasContext()) {
$site = $this->siteManager->getContext();
}
}
if ($site) {
$alias = $this->aliasManager->getPathAlias($node->id(), $site->getId());
}
if (!$alias) {
// No alias at all means that the canonical is the node URL in the
// current site, I am sorry I can't provide more any magic here...
return url('node/' . $node->id(), ['absolute' => true]);
}
return $this->siteManager->getUrlGenerator()->generateUrl($site, $alias, ['absolute' => true], true);
} | [
"public",
"function",
"getNodeCanonical",
"(",
"NodeInterface",
"$",
"node",
")",
":",
"?",
"string",
"{",
"if",
"(",
"$",
"this",
"->",
"isNodeBlacklisted",
"(",
"$",
"node",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"site",
"=",
"null",
";",
... | Get node canonical URL | [
"Get",
"node",
"canonical",
"URL"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/SeoService.php#L262-L301 |
makinacorpus/drupal-ucms | ucms_seo/src/SeoService.php | SeoService.getNodeSegment | public function getNodeSegment(NodeInterface $node) : ?string
{
if ($node->isNew()) {
return null;
}
if ($this->isNodeBlacklisted($node)) {
return null;
}
$map = $this->getNodeAliasMap([$node->id()]);
if ($map) {
return reset($map);
}
} | php | public function getNodeSegment(NodeInterface $node) : ?string
{
if ($node->isNew()) {
return null;
}
if ($this->isNodeBlacklisted($node)) {
return null;
}
$map = $this->getNodeAliasMap([$node->id()]);
if ($map) {
return reset($map);
}
} | [
"public",
"function",
"getNodeSegment",
"(",
"NodeInterface",
"$",
"node",
")",
":",
"?",
"string",
"{",
"if",
"(",
"$",
"node",
"->",
"isNew",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"isNodeBlacklisted",
"(",
"$... | Get node alias segment
@param NodeInterface $node
@return string | [
"Get",
"node",
"alias",
"segment"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/SeoService.php#L310-L325 |
makinacorpus/drupal-ucms | ucms_seo/src/SeoService.php | SeoService.normalizeSegment | public function normalizeSegment(string $value, int $maxLength = UCMS_SEO_SEGMENT_TRIM_LENGTH) : string
{
// Transliterate first
if (class_exists('URLify')) {
$value = \URLify::filter($value, $maxLength);
}
// Only lowercase characters
$value = strtolower($value);
// All special characters to be replaced by '-' and doubles stripped
// to only one occurence
$value = preg_replace('/[^a-z0-9\-]+/', '-', $value);
$value = preg_replace('/-+/', '-', $value);
// Trim leading and trailing '-' characters
$value = trim($value, '-');
// @todo stopwords
return $value;
} | php | public function normalizeSegment(string $value, int $maxLength = UCMS_SEO_SEGMENT_TRIM_LENGTH) : string
{
// Transliterate first
if (class_exists('URLify')) {
$value = \URLify::filter($value, $maxLength);
}
// Only lowercase characters
$value = strtolower($value);
// All special characters to be replaced by '-' and doubles stripped
// to only one occurence
$value = preg_replace('/[^a-z0-9\-]+/', '-', $value);
$value = preg_replace('/-+/', '-', $value);
// Trim leading and trailing '-' characters
$value = trim($value, '-');
// @todo stopwords
return $value;
} | [
"public",
"function",
"normalizeSegment",
"(",
"string",
"$",
"value",
",",
"int",
"$",
"maxLength",
"=",
"UCMS_SEO_SEGMENT_TRIM_LENGTH",
")",
":",
"string",
"{",
"// Transliterate first",
"if",
"(",
"class_exists",
"(",
"'URLify'",
")",
")",
"{",
"$",
"value",
... | Normalize given URL segment
@param string $value
@param int $maxLength
@return string | [
"Normalize",
"given",
"URL",
"segment"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/SeoService.php#L335-L356 |
makinacorpus/drupal-ucms | ucms_seo/src/SeoService.php | SeoService.setNodeSegment | public function setNodeSegment(NodeInterface $node, string $segment, ?string $previous = null) : void
{
if ($this->isNodeBlacklisted($node)) {
return;
}
if (!$previous) {
$previous = $this->getNodeSegment($node);
}
if (empty($segment)) {
$segment = null;
}
if ($previous === $segment) {
return; // Nothing to do
}
$this
->database
->merge('ucms_seo_node')
->key(['nid' => $node->id()])
->fields(['alias_segment' => $segment])
->execute()
;
if (empty($segment)) {
$this->onAliasChange([$node->id()]);
} else {
$this->onAliasChange([$node->id()]);
}
} | php | public function setNodeSegment(NodeInterface $node, string $segment, ?string $previous = null) : void
{
if ($this->isNodeBlacklisted($node)) {
return;
}
if (!$previous) {
$previous = $this->getNodeSegment($node);
}
if (empty($segment)) {
$segment = null;
}
if ($previous === $segment) {
return; // Nothing to do
}
$this
->database
->merge('ucms_seo_node')
->key(['nid' => $node->id()])
->fields(['alias_segment' => $segment])
->execute()
;
if (empty($segment)) {
$this->onAliasChange([$node->id()]);
} else {
$this->onAliasChange([$node->id()]);
}
} | [
"public",
"function",
"setNodeSegment",
"(",
"NodeInterface",
"$",
"node",
",",
"string",
"$",
"segment",
",",
"?",
"string",
"$",
"previous",
"=",
"null",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"isNodeBlacklisted",
"(",
"$",
"node",
")",
... | Change the node segment
@param NodeInterface $node
@param string $segment
New node segment
@param string $previous
If by any chance you are sure you know the previous one, set it here
to save a SQL query | [
"Change",
"the",
"node",
"segment"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/SeoService.php#L368-L398 |
makinacorpus/drupal-ucms | ucms_seo/src/SeoService.php | SeoService.onAliasChange | public function onAliasChange(array $nodeIdList) : void
{
$this->aliasManager->invalidateRelated($nodeIdList);
$this->aliasCacheLookup->refresh();
} | php | public function onAliasChange(array $nodeIdList) : void
{
$this->aliasManager->invalidateRelated($nodeIdList);
$this->aliasCacheLookup->refresh();
} | [
"public",
"function",
"onAliasChange",
"(",
"array",
"$",
"nodeIdList",
")",
":",
"void",
"{",
"$",
"this",
"->",
"aliasManager",
"->",
"invalidateRelated",
"(",
"$",
"nodeIdList",
")",
";",
"$",
"this",
"->",
"aliasCacheLookup",
"->",
"refresh",
"(",
")",
... | Set all impacted aliases as outdated
@param array $nodeIdList | [
"Set",
"all",
"impacted",
"aliases",
"as",
"outdated"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/SeoService.php#L405-L409 |
makinacorpus/drupal-ucms | ucms_seo/src/SeoService.php | SeoService.onMenuChange | public function onMenuChange(Menu $menu) : void
{
$this->aliasManager->invalidate(['site_id' => $menu->getSiteId()]);
$this->aliasCacheLookup->refresh();
} | php | public function onMenuChange(Menu $menu) : void
{
$this->aliasManager->invalidate(['site_id' => $menu->getSiteId()]);
$this->aliasCacheLookup->refresh();
} | [
"public",
"function",
"onMenuChange",
"(",
"Menu",
"$",
"menu",
")",
":",
"void",
"{",
"$",
"this",
"->",
"aliasManager",
"->",
"invalidate",
"(",
"[",
"'site_id'",
"=>",
"$",
"menu",
"->",
"getSiteId",
"(",
")",
"]",
")",
";",
"$",
"this",
"->",
"al... | Set all impacted aliases as outdated
@param int $menuId | [
"Set",
"all",
"impacted",
"aliases",
"as",
"outdated"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/SeoService.php#L416-L420 |
makinacorpus/drupal-ucms | ucms_site/src/SiteUrlGenerator.php | SiteUrlGenerator.forceSiteUrl | public function forceSiteUrl(&$options, $site)
{
if (!$site instanceof Site) {
$site = $this->storage->findOne($site);
}
if ($GLOBALS['is_https']) {
$options['https'] = !$site->isHttpsAllowed();
} else if (variable_get('https', false)) {
$options['https'] = !$site->isHttpAllowed();
} else {
// Sorry, HTTPS is disabled at the Drupal level, note that it is not
// mandatory to this because url() will do the check by itself, but
// because there is in here one code path in which we are going to
// manually set the base URL, we need to compute that by ourselves.
$options['https'] = false;
}
// Warning, this is a INTERNAL url() function behavior, so we have
// to reproduce a few other behaviours to go along with it, such as
// manual http vs https handling. Please see the variable_get('https')
// documentation above.
$options['base_url'] = ($options['https'] ? 'https://' : 'http://') . $site->getHostname();
$options['absolute'] = true;
} | php | public function forceSiteUrl(&$options, $site)
{
if (!$site instanceof Site) {
$site = $this->storage->findOne($site);
}
if ($GLOBALS['is_https']) {
$options['https'] = !$site->isHttpsAllowed();
} else if (variable_get('https', false)) {
$options['https'] = !$site->isHttpAllowed();
} else {
// Sorry, HTTPS is disabled at the Drupal level, note that it is not
// mandatory to this because url() will do the check by itself, but
// because there is in here one code path in which we are going to
// manually set the base URL, we need to compute that by ourselves.
$options['https'] = false;
}
// Warning, this is a INTERNAL url() function behavior, so we have
// to reproduce a few other behaviours to go along with it, such as
// manual http vs https handling. Please see the variable_get('https')
// documentation above.
$options['base_url'] = ($options['https'] ? 'https://' : 'http://') . $site->getHostname();
$options['absolute'] = true;
} | [
"public",
"function",
"forceSiteUrl",
"(",
"&",
"$",
"options",
",",
"$",
"site",
")",
"{",
"if",
"(",
"!",
"$",
"site",
"instanceof",
"Site",
")",
"{",
"$",
"site",
"=",
"$",
"this",
"->",
"storage",
"->",
"findOne",
"(",
"$",
"site",
")",
";",
... | Alter parameters for the url outbound alter hook
@param mixed[] $options
Link options, see url()
@param int|Site $site
Site identifier, if site is null | [
"Alter",
"parameters",
"for",
"the",
"url",
"outbound",
"alter",
"hook"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/SiteUrlGenerator.php#L38-L62 |
makinacorpus/drupal-ucms | ucms_site/src/SiteUrlGenerator.php | SiteUrlGenerator.getRouteAndParams | public function getRouteAndParams($site, $path = null, $options = [], $ignoreSso = false, $dropDestination = false)
{
if (!$site instanceof Site) {
$site = $this->storage->findOne($site);
}
// Avoid reentrancy in ucms_site_url_outbound_alter().
$options['ucms_processed'] = true;
$options['ucms_site'] = $site->getId();
// Site is the same, URL should not be absolute; or if it asked that it
// might be, then let Drupal work his own base URL, since it's the right
// site already, ignore 'https' directive too because we cannot give the
// user pages with insecure mixed mode links within.
if ($this->manager->hasContext() && $this->manager->getContext()->getId() == $site->getId()) {
return [$path, $options];
}
// @todo Should bypass this if user is not logged in
// Reaching here means that we do asked for an absolute URL.
if ($ignoreSso || !$this->ssoEnabled) {
$this->forceSiteUrl($options, $site);
return [$path, $options];
}
if (!$dropDestination) {
if (isset($_GET['destination'])) {
$options['query']['form_redirect'] = $_GET['destination'];
unset($_GET['destination']);
} else if (isset($options['query']['destination'])) {
$options['query']['form_redirect'] = $options['query']['destination'];
}
}
// Strip path when front page, avoid a potentially useless destination
// parameter and normalize all different front possible paths.
if ($path && '<front>' !== $path && $path !== variable_get('site_frontpage', 'node')) {
$options['query']['destination'] = $path;
}
return ['sso/goto/' . $site->getId(), $options];
} | php | public function getRouteAndParams($site, $path = null, $options = [], $ignoreSso = false, $dropDestination = false)
{
if (!$site instanceof Site) {
$site = $this->storage->findOne($site);
}
// Avoid reentrancy in ucms_site_url_outbound_alter().
$options['ucms_processed'] = true;
$options['ucms_site'] = $site->getId();
// Site is the same, URL should not be absolute; or if it asked that it
// might be, then let Drupal work his own base URL, since it's the right
// site already, ignore 'https' directive too because we cannot give the
// user pages with insecure mixed mode links within.
if ($this->manager->hasContext() && $this->manager->getContext()->getId() == $site->getId()) {
return [$path, $options];
}
// @todo Should bypass this if user is not logged in
// Reaching here means that we do asked for an absolute URL.
if ($ignoreSso || !$this->ssoEnabled) {
$this->forceSiteUrl($options, $site);
return [$path, $options];
}
if (!$dropDestination) {
if (isset($_GET['destination'])) {
$options['query']['form_redirect'] = $_GET['destination'];
unset($_GET['destination']);
} else if (isset($options['query']['destination'])) {
$options['query']['form_redirect'] = $options['query']['destination'];
}
}
// Strip path when front page, avoid a potentially useless destination
// parameter and normalize all different front possible paths.
if ($path && '<front>' !== $path && $path !== variable_get('site_frontpage', 'node')) {
$options['query']['destination'] = $path;
}
return ['sso/goto/' . $site->getId(), $options];
} | [
"public",
"function",
"getRouteAndParams",
"(",
"$",
"site",
",",
"$",
"path",
"=",
"null",
",",
"$",
"options",
"=",
"[",
"]",
",",
"$",
"ignoreSso",
"=",
"false",
",",
"$",
"dropDestination",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"$",
"site",
"... | Get URL in site
@param int|Site $site
Site identifier, if site is null
@param string $path
Drupal path to hit in site
@param mixed[] $options
Link options, see url()
@param boolean $dropDestination
If you're sure you are NOT in a form, just set this to true
@return mixed
First value is the string path
Second value are updates $options | [
"Get",
"URL",
"in",
"site"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/SiteUrlGenerator.php#L80-L122 |
makinacorpus/drupal-ucms | ucms_site/src/SiteUrlGenerator.php | SiteUrlGenerator.generateUrl | public function generateUrl($site, $path = null, $options = [], $ignoreSso = false, $dropDestination = false)
{
return call_user_func_array('url', $this->getRouteAndParams($site, $path, $options, $ignoreSso, $dropDestination));
} | php | public function generateUrl($site, $path = null, $options = [], $ignoreSso = false, $dropDestination = false)
{
return call_user_func_array('url', $this->getRouteAndParams($site, $path, $options, $ignoreSso, $dropDestination));
} | [
"public",
"function",
"generateUrl",
"(",
"$",
"site",
",",
"$",
"path",
"=",
"null",
",",
"$",
"options",
"=",
"[",
"]",
",",
"$",
"ignoreSso",
"=",
"false",
",",
"$",
"dropDestination",
"=",
"false",
")",
"{",
"return",
"call_user_func_array",
"(",
"... | Alias of getRouteAndParams() that returns the generated URL
@param int|Site $site
Site identifier, if site is null
@param string $path
Drupal path to hit in site
@param mixed[] $options
Link options, see url()
@param boolean $dropDestination
If you're sure you are NOT in a form, just set this to true
@return string | [
"Alias",
"of",
"getRouteAndParams",
"()",
"that",
"returns",
"the",
"generated",
"URL"
] | train | https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/SiteUrlGenerator.php#L138-L141 |
shopgate/cart-integration-sdk | src/models/catalog/Stock.php | Shopgate_Model_Catalog_Stock.asXml | public function asXml(Shopgate_Model_XmlResultObject $itemNode)
{
/**
* @var Shopgate_Model_XmlResultObject $stockNode
*/
$stockNode = $itemNode->addChild('stock');
$stockNode->addChild('is_saleable', (int)$this->getIsSaleable());
$stockNode->addChild('backorders', (int)$this->getBackorders());
$stockNode->addChild('use_stock', (int)$this->getUseStock());
$stockNode->addChild('stock_quantity', $this->getStockQuantity());
$stockNode->addChild('minimum_order_quantity', $this->getMinimumOrderQuantity(), null, false);
$stockNode->addChild('maximum_order_quantity', $this->getMaximumOrderQuantity(), null, false);
$stockNode->addChildWithCDATA('availability_text', $this->getAvailabilityText(), false);
return $itemNode;
} | php | public function asXml(Shopgate_Model_XmlResultObject $itemNode)
{
/**
* @var Shopgate_Model_XmlResultObject $stockNode
*/
$stockNode = $itemNode->addChild('stock');
$stockNode->addChild('is_saleable', (int)$this->getIsSaleable());
$stockNode->addChild('backorders', (int)$this->getBackorders());
$stockNode->addChild('use_stock', (int)$this->getUseStock());
$stockNode->addChild('stock_quantity', $this->getStockQuantity());
$stockNode->addChild('minimum_order_quantity', $this->getMinimumOrderQuantity(), null, false);
$stockNode->addChild('maximum_order_quantity', $this->getMaximumOrderQuantity(), null, false);
$stockNode->addChildWithCDATA('availability_text', $this->getAvailabilityText(), false);
return $itemNode;
} | [
"public",
"function",
"asXml",
"(",
"Shopgate_Model_XmlResultObject",
"$",
"itemNode",
")",
"{",
"/**\n * @var Shopgate_Model_XmlResultObject $stockNode\n */",
"$",
"stockNode",
"=",
"$",
"itemNode",
"->",
"addChild",
"(",
"'stock'",
")",
";",
"$",
"stockN... | @param Shopgate_Model_XmlResultObject $itemNode
@return Shopgate_Model_XmlResultObject | [
"@param",
"Shopgate_Model_XmlResultObject",
"$itemNode"
] | train | https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/models/catalog/Stock.php#L71-L86 |
PHPixie/HTTP | src/PHPixie/HTTP/Request.php | Request.server | public function server()
{
if($this->server === null) {
$data = $this->serverRequest->getServerParams();
$this->server = $this->builder->serverData($data);
}
return $this->server;
} | php | public function server()
{
if($this->server === null) {
$data = $this->serverRequest->getServerParams();
$this->server = $this->builder->serverData($data);
}
return $this->server;
} | [
"public",
"function",
"server",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"server",
"===",
"null",
")",
"{",
"$",
"data",
"=",
"$",
"this",
"->",
"serverRequest",
"->",
"getServerParams",
"(",
")",
";",
"$",
"this",
"->",
"server",
"=",
"$",
"th... | Server data (e.g. $_SERVER)
@return \PHPixie\HTTP\Data\Server | [
"Server",
"data",
"(",
"e",
".",
"g",
".",
"$_SERVER",
")"
] | train | https://github.com/PHPixie/HTTP/blob/581c0df452fd07ca4ea0b3e24e8ddee8dddc2912/src/PHPixie/HTTP/Request.php#L95-L103 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.