repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1
value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
smartboxgroup/integration-framework-bundle | Tools/Evaluator/CustomExpressionLanguageProvider.php | CustomExpressionLanguageProvider.createImplodeFunction | protected function createImplodeFunction()
{
return new ExpressionFunction(
'implode',
function ($glue, $pieces) {
return sprintf('implode(%s,%s)', $glue, $pieces);
},
function ($arguments, $glue, $pieces) {
return implode($glue, $pieces);
}
);
} | php | protected function createImplodeFunction()
{
return new ExpressionFunction(
'implode',
function ($glue, $pieces) {
return sprintf('implode(%s,%s)', $glue, $pieces);
},
function ($arguments, $glue, $pieces) {
return implode($glue, $pieces);
}
);
} | [
"protected",
"function",
"createImplodeFunction",
"(",
")",
"{",
"return",
"new",
"ExpressionFunction",
"(",
"'implode'",
",",
"function",
"(",
"$",
"glue",
",",
"$",
"pieces",
")",
"{",
"return",
"sprintf",
"(",
"'implode(%s,%s)'",
",",
"$",
"glue",
",",
"$... | Implode an array to a string.
@return ExpressionFunction | [
"Implode",
"an",
"array",
"to",
"a",
"string",
"."
] | 5f0bf8ff86337a51f6d208bd38df39017643b905 | https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Tools/Evaluator/CustomExpressionLanguageProvider.php#L271-L282 | train |
cedx/coveralls.php | lib/GitData.php | GitData.fromJson | static function fromJson(object $map): self {
return new static(
isset($map->head) && is_object($map->head) ? GitCommit::fromJson($map->head) : null,
isset($map->branch) && is_string($map->branch) ? $map->branch : '',
isset($map->remotes) && is_array($map->remotes) ? array_map([GitRemote::class, 'fromJson'], $map->remotes) : []
);
} | php | static function fromJson(object $map): self {
return new static(
isset($map->head) && is_object($map->head) ? GitCommit::fromJson($map->head) : null,
isset($map->branch) && is_string($map->branch) ? $map->branch : '',
isset($map->remotes) && is_array($map->remotes) ? array_map([GitRemote::class, 'fromJson'], $map->remotes) : []
);
} | [
"static",
"function",
"fromJson",
"(",
"object",
"$",
"map",
")",
":",
"self",
"{",
"return",
"new",
"static",
"(",
"isset",
"(",
"$",
"map",
"->",
"head",
")",
"&&",
"is_object",
"(",
"$",
"map",
"->",
"head",
")",
"?",
"GitCommit",
"::",
"fromJson"... | Creates a new Git data from the specified JSON map.
@param object $map A JSON map representing a Git data.
@return static The instance corresponding to the specified JSON map. | [
"Creates",
"a",
"new",
"Git",
"data",
"from",
"the",
"specified",
"JSON",
"map",
"."
] | c196de0f92e06d5143ba90ebab18c8e384316cc0 | https://github.com/cedx/coveralls.php/blob/c196de0f92e06d5143ba90ebab18c8e384316cc0/lib/GitData.php#L33-L39 | train |
cedx/coveralls.php | lib/GitData.php | GitData.fromRepository | static function fromRepository(string $path = ''): self {
$workingDir = getcwd() ?: '.';
if (!mb_strlen($path)) $path = $workingDir;
chdir($path);
$commands = (object) array_map(function($command) { return trim(`git $command`); }, [
'author_email' => 'log -1 --pretty=format:%ae',
'author_name' => 'log -1 --pretty=format:%aN',
'branch' => 'rev-parse --abbrev-ref HEAD',
'committer_email' => 'log -1 --pretty=format:%ce',
'committer_name' => 'log -1 --pretty=format:%cN',
'id' => 'log -1 --pretty=format:%H',
'message' => 'log -1 --pretty=format:%s',
'remotes' => 'remote -v'
]);
$remotes = [];
foreach (preg_split('/\r?\n/', $commands->remotes) ?: [] as $remote) {
$parts = explode(' ', (string) preg_replace('/\s+/', ' ', $remote));
if (!isset($remotes[$parts[0]])) $remotes[$parts[0]] = new GitRemote($parts[0], count($parts) > 1 ? $parts[1] : null);
}
chdir($workingDir);
return new static(GitCommit::fromJson($commands), $commands->branch, array_values($remotes));
} | php | static function fromRepository(string $path = ''): self {
$workingDir = getcwd() ?: '.';
if (!mb_strlen($path)) $path = $workingDir;
chdir($path);
$commands = (object) array_map(function($command) { return trim(`git $command`); }, [
'author_email' => 'log -1 --pretty=format:%ae',
'author_name' => 'log -1 --pretty=format:%aN',
'branch' => 'rev-parse --abbrev-ref HEAD',
'committer_email' => 'log -1 --pretty=format:%ce',
'committer_name' => 'log -1 --pretty=format:%cN',
'id' => 'log -1 --pretty=format:%H',
'message' => 'log -1 --pretty=format:%s',
'remotes' => 'remote -v'
]);
$remotes = [];
foreach (preg_split('/\r?\n/', $commands->remotes) ?: [] as $remote) {
$parts = explode(' ', (string) preg_replace('/\s+/', ' ', $remote));
if (!isset($remotes[$parts[0]])) $remotes[$parts[0]] = new GitRemote($parts[0], count($parts) > 1 ? $parts[1] : null);
}
chdir($workingDir);
return new static(GitCommit::fromJson($commands), $commands->branch, array_values($remotes));
} | [
"static",
"function",
"fromRepository",
"(",
"string",
"$",
"path",
"=",
"''",
")",
":",
"self",
"{",
"$",
"workingDir",
"=",
"getcwd",
"(",
")",
"?",
":",
"'.'",
";",
"if",
"(",
"!",
"mb_strlen",
"(",
"$",
"path",
")",
")",
"$",
"path",
"=",
"$"... | Creates a new Git data from a local repository.
This method relies on the availability of the Git executable in the system path.
@param string $path The path to the repository folder. Defaults to the current working directory.
@return static The newly created Git data. | [
"Creates",
"a",
"new",
"Git",
"data",
"from",
"a",
"local",
"repository",
".",
"This",
"method",
"relies",
"on",
"the",
"availability",
"of",
"the",
"Git",
"executable",
"in",
"the",
"system",
"path",
"."
] | c196de0f92e06d5143ba90ebab18c8e384316cc0 | https://github.com/cedx/coveralls.php/blob/c196de0f92e06d5143ba90ebab18c8e384316cc0/lib/GitData.php#L47-L71 | train |
Prezent/prezent-crud-bundle | src/Model/Configuration.php | Configuration.getDefaultName | private function getDefaultName(Request $request)
{
if (!preg_match('/Bundle\\\\Controller\\\\([\w\\\\]+)Controller:/', $request->attributes->get('_controller'), $match)) {
throw new \RuntimeException('Unable to determine controller name');
}
return strtolower(str_replace('\\', '_', $match[1]));
} | php | private function getDefaultName(Request $request)
{
if (!preg_match('/Bundle\\\\Controller\\\\([\w\\\\]+)Controller:/', $request->attributes->get('_controller'), $match)) {
throw new \RuntimeException('Unable to determine controller name');
}
return strtolower(str_replace('\\', '_', $match[1]));
} | [
"private",
"function",
"getDefaultName",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"!",
"preg_match",
"(",
"'/Bundle\\\\\\\\Controller\\\\\\\\([\\w\\\\\\\\]+)Controller:/'",
",",
"$",
"request",
"->",
"attributes",
"->",
"get",
"(",
"'_controller'",
")",
... | Get the default controller name
@param Request $request
@return string | [
"Get",
"the",
"default",
"controller",
"name"
] | bb8bcf92cecc2acae08b8a672876b4972175ca24 | https://github.com/Prezent/prezent-crud-bundle/blob/bb8bcf92cecc2acae08b8a672876b4972175ca24/src/Model/Configuration.php#L519-L526 | train |
Prezent/prezent-crud-bundle | src/Model/Configuration.php | Configuration.getDefaultAction | private function getDefaultAction(Request $request)
{
if (!preg_match('/(\w+)Action$/', $request->attributes->get('_controller'), $match)) {
throw new \RuntimeException('Unable to determine controller name');
}
return strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $match[1]));
} | php | private function getDefaultAction(Request $request)
{
if (!preg_match('/(\w+)Action$/', $request->attributes->get('_controller'), $match)) {
throw new \RuntimeException('Unable to determine controller name');
}
return strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $match[1]));
} | [
"private",
"function",
"getDefaultAction",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"!",
"preg_match",
"(",
"'/(\\w+)Action$/'",
",",
"$",
"request",
"->",
"attributes",
"->",
"get",
"(",
"'_controller'",
")",
",",
"$",
"match",
")",
")",
"{",
... | Get the default controller action
@param Request $request
@return string | [
"Get",
"the",
"default",
"controller",
"action"
] | bb8bcf92cecc2acae08b8a672876b4972175ca24 | https://github.com/Prezent/prezent-crud-bundle/blob/bb8bcf92cecc2acae08b8a672876b4972175ca24/src/Model/Configuration.php#L534-L541 | train |
netgen/site-bundle | bundle/Controller/MenuController.php | MenuController.renderMenu | public function renderMenu(Request $request, string $menuName): Response
{
$menu = $this->menuProvider->get($menuName);
$menu->setChildrenAttribute('class', $request->attributes->get('ulClass') ?: 'nav navbar-nav');
$menuOptions = [
'firstClass' => $request->attributes->get('firstClass') ?: 'firstli',
'currentClass' => $request->attributes->get('currentClass') ?: 'active',
'lastClass' => $request->attributes->get('lastClass') ?: 'lastli',
'template' => $this->getConfigResolver()->getParameter('template.menu', 'ngsite'),
];
if ($request->attributes->has('template')) {
$menuOptions['template'] = $request->attributes->get('template');
}
$response = new Response();
$menuLocationId = $menu->getAttribute('location-id');
if (!empty($menuLocationId)) {
$this->tagHandler->addTags(['location-' . $menuLocationId]);
}
$this->processCacheSettings($request, $response);
$response->setContent($this->menuRenderer->get()->render($menu, $menuOptions));
return $response;
} | php | public function renderMenu(Request $request, string $menuName): Response
{
$menu = $this->menuProvider->get($menuName);
$menu->setChildrenAttribute('class', $request->attributes->get('ulClass') ?: 'nav navbar-nav');
$menuOptions = [
'firstClass' => $request->attributes->get('firstClass') ?: 'firstli',
'currentClass' => $request->attributes->get('currentClass') ?: 'active',
'lastClass' => $request->attributes->get('lastClass') ?: 'lastli',
'template' => $this->getConfigResolver()->getParameter('template.menu', 'ngsite'),
];
if ($request->attributes->has('template')) {
$menuOptions['template'] = $request->attributes->get('template');
}
$response = new Response();
$menuLocationId = $menu->getAttribute('location-id');
if (!empty($menuLocationId)) {
$this->tagHandler->addTags(['location-' . $menuLocationId]);
}
$this->processCacheSettings($request, $response);
$response->setContent($this->menuRenderer->get()->render($menu, $menuOptions));
return $response;
} | [
"public",
"function",
"renderMenu",
"(",
"Request",
"$",
"request",
",",
"string",
"$",
"menuName",
")",
":",
"Response",
"{",
"$",
"menu",
"=",
"$",
"this",
"->",
"menuProvider",
"->",
"get",
"(",
"$",
"menuName",
")",
";",
"$",
"menu",
"->",
"setChil... | Renders the menu with provided name. | [
"Renders",
"the",
"menu",
"with",
"provided",
"name",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Controller/MenuController.php#L43-L71 | train |
netgen/site-bundle | bundle/Controller/Controller.php | Controller.processCacheSettings | protected function processCacheSettings(Request $request, Response $response): void
{
$defaultSharedMaxAge = $this->getConfigResolver()->getParameter('view.shared_max_age', 'ngsite');
$cacheSettings = $request->attributes->get('cacheSettings');
if (!is_array($cacheSettings)) {
$cacheSettings = ['sharedMaxAge' => $defaultSharedMaxAge];
}
$public = true;
if (isset($cacheSettings['sharedMaxAge'])) {
$response->setSharedMaxAge($cacheSettings['sharedMaxAge']);
if (empty($cacheSettings['sharedMaxAge'])) {
$public = false;
}
} elseif (isset($cacheSettings['maxAge'])) {
$response->setMaxAge($cacheSettings['maxAge']);
if (empty($cacheSettings['maxAge'])) {
$public = false;
}
} else {
$response->setSharedMaxAge($defaultSharedMaxAge);
}
$public ? $response->setPublic() : $response->setPrivate();
} | php | protected function processCacheSettings(Request $request, Response $response): void
{
$defaultSharedMaxAge = $this->getConfigResolver()->getParameter('view.shared_max_age', 'ngsite');
$cacheSettings = $request->attributes->get('cacheSettings');
if (!is_array($cacheSettings)) {
$cacheSettings = ['sharedMaxAge' => $defaultSharedMaxAge];
}
$public = true;
if (isset($cacheSettings['sharedMaxAge'])) {
$response->setSharedMaxAge($cacheSettings['sharedMaxAge']);
if (empty($cacheSettings['sharedMaxAge'])) {
$public = false;
}
} elseif (isset($cacheSettings['maxAge'])) {
$response->setMaxAge($cacheSettings['maxAge']);
if (empty($cacheSettings['maxAge'])) {
$public = false;
}
} else {
$response->setSharedMaxAge($defaultSharedMaxAge);
}
$public ? $response->setPublic() : $response->setPrivate();
} | [
"protected",
"function",
"processCacheSettings",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
":",
"void",
"{",
"$",
"defaultSharedMaxAge",
"=",
"$",
"this",
"->",
"getConfigResolver",
"(",
")",
"->",
"getParameter",
"(",
"'view.shared_... | Configures the response with provided cache settings. | [
"Configures",
"the",
"response",
"with",
"provided",
"cache",
"settings",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Controller/Controller.php#L16-L42 | train |
netgen/site-bundle | bundle/EventListener/User/PasswordResetRequestEventListener.php | PasswordResetRequestEventListener.onPasswordResetRequest | public function onPasswordResetRequest(PasswordResetRequestEvent $event): void
{
$user = $event->getUser();
$email = $event->getEmail();
if (!$user instanceof User) {
$this->mailHelper
->sendMail(
$email,
'ngsite.user.forgot_password.not_registered.subject',
$this->configResolver->getParameter('template.user.mail.forgot_password_not_registered', 'ngsite')
);
return;
}
if (!$user->enabled) {
if ($this->ngUserSettingRepository->isUserActivated($user->id)) {
$this->mailHelper
->sendMail(
[$user->email => $this->getUserName($user)],
'ngsite.user.forgot_password.disabled.subject',
$this->configResolver->getParameter('template.user.mail.forgot_password_disabled', 'ngsite'),
[
'user' => $user,
]
);
return;
}
$this->mailHelper
->sendMail(
[$user->email => $this->getUserName($user)],
'ngsite.user.forgot_password.not_active.subject',
$this->configResolver->getParameter('template.user.mail.forgot_password_not_active', 'ngsite'),
[
'user' => $user,
]
);
return;
}
$accountKey = $this->ezUserAccountKeyRepository->create($user->id);
$this->mailHelper
->sendMail(
[$user->email => $this->getUserName($user)],
'ngsite.user.forgot_password.subject',
$this->configResolver->getParameter('template.user.mail.forgot_password', 'ngsite'),
[
'user' => $user,
'hash' => $accountKey->getHash(),
]
);
} | php | public function onPasswordResetRequest(PasswordResetRequestEvent $event): void
{
$user = $event->getUser();
$email = $event->getEmail();
if (!$user instanceof User) {
$this->mailHelper
->sendMail(
$email,
'ngsite.user.forgot_password.not_registered.subject',
$this->configResolver->getParameter('template.user.mail.forgot_password_not_registered', 'ngsite')
);
return;
}
if (!$user->enabled) {
if ($this->ngUserSettingRepository->isUserActivated($user->id)) {
$this->mailHelper
->sendMail(
[$user->email => $this->getUserName($user)],
'ngsite.user.forgot_password.disabled.subject',
$this->configResolver->getParameter('template.user.mail.forgot_password_disabled', 'ngsite'),
[
'user' => $user,
]
);
return;
}
$this->mailHelper
->sendMail(
[$user->email => $this->getUserName($user)],
'ngsite.user.forgot_password.not_active.subject',
$this->configResolver->getParameter('template.user.mail.forgot_password_not_active', 'ngsite'),
[
'user' => $user,
]
);
return;
}
$accountKey = $this->ezUserAccountKeyRepository->create($user->id);
$this->mailHelper
->sendMail(
[$user->email => $this->getUserName($user)],
'ngsite.user.forgot_password.subject',
$this->configResolver->getParameter('template.user.mail.forgot_password', 'ngsite'),
[
'user' => $user,
'hash' => $accountKey->getHash(),
]
);
} | [
"public",
"function",
"onPasswordResetRequest",
"(",
"PasswordResetRequestEvent",
"$",
"event",
")",
":",
"void",
"{",
"$",
"user",
"=",
"$",
"event",
"->",
"getUser",
"(",
")",
";",
"$",
"email",
"=",
"$",
"event",
"->",
"getEmail",
"(",
")",
";",
"if",... | Listens for the start of forgot password procedure.
Event contains information about the submitted email and the user, if found. | [
"Listens",
"for",
"the",
"start",
"of",
"forgot",
"password",
"procedure",
".",
"Event",
"contains",
"information",
"about",
"the",
"submitted",
"email",
"and",
"the",
"user",
"if",
"found",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/EventListener/User/PasswordResetRequestEventListener.php#L31-L87 | train |
netgen/site-bundle | bundle/Templating/Twig/Extension/SiteRuntime.php | SiteRuntime.getLanguageName | public function getLanguageName(string $languageCode): string
{
$posixLanguageCode = $this->localeConverter->convertToPOSIX($languageCode);
if ($posixLanguageCode === null) {
return '';
}
$posixLanguageCode = mb_substr($posixLanguageCode, 0, 2);
$languageName = Intl::getLanguageBundle()->getLanguageName($posixLanguageCode, null, $posixLanguageCode);
return ucwords($languageName);
} | php | public function getLanguageName(string $languageCode): string
{
$posixLanguageCode = $this->localeConverter->convertToPOSIX($languageCode);
if ($posixLanguageCode === null) {
return '';
}
$posixLanguageCode = mb_substr($posixLanguageCode, 0, 2);
$languageName = Intl::getLanguageBundle()->getLanguageName($posixLanguageCode, null, $posixLanguageCode);
return ucwords($languageName);
} | [
"public",
"function",
"getLanguageName",
"(",
"string",
"$",
"languageCode",
")",
":",
"string",
"{",
"$",
"posixLanguageCode",
"=",
"$",
"this",
"->",
"localeConverter",
"->",
"convertToPOSIX",
"(",
"$",
"languageCode",
")",
";",
"if",
"(",
"$",
"posixLanguag... | Returns the language name for specified language code. | [
"Returns",
"the",
"language",
"name",
"for",
"specified",
"language",
"code",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Templating/Twig/Extension/SiteRuntime.php#L52-L63 | train |
cedx/coveralls.php | lib/Job.php | Job.fromJson | static function fromJson(object $map): self {
return (new static(isset($map->source_files) && is_array($map->source_files) ? array_map([SourceFile::class, 'fromJson'], $map->source_files) : []))
->setCommitSha(isset($map->commit_sha) && is_string($map->commit_sha) ? $map->commit_sha : '')
->setGit(isset($map->git) && is_object($map->git) ? GitData::fromJson($map->git) : null)
->setParallel(isset($map->parallel) && is_bool($map->parallel) ? $map->parallel : false)
->setRepoToken(isset($map->repo_token) && is_string($map->repo_token) ? $map->repo_token : '')
->setRunAt(isset($map->run_at) && is_string($map->run_at) ? new \DateTime($map->run_at) : null)
->setServiceJobId(isset($map->service_job_id) && is_string($map->service_job_id) ? $map->service_job_id : '')
->setServiceName(isset($map->service_name) && is_string($map->service_name) ? $map->service_name : '')
->setServiceNumber(isset($map->service_number) && is_string($map->service_number) ? $map->service_number : '')
->setServicePullRequest(isset($map->service_pull_request) && is_string($map->service_pull_request) ? $map->service_pull_request : '');
} | php | static function fromJson(object $map): self {
return (new static(isset($map->source_files) && is_array($map->source_files) ? array_map([SourceFile::class, 'fromJson'], $map->source_files) : []))
->setCommitSha(isset($map->commit_sha) && is_string($map->commit_sha) ? $map->commit_sha : '')
->setGit(isset($map->git) && is_object($map->git) ? GitData::fromJson($map->git) : null)
->setParallel(isset($map->parallel) && is_bool($map->parallel) ? $map->parallel : false)
->setRepoToken(isset($map->repo_token) && is_string($map->repo_token) ? $map->repo_token : '')
->setRunAt(isset($map->run_at) && is_string($map->run_at) ? new \DateTime($map->run_at) : null)
->setServiceJobId(isset($map->service_job_id) && is_string($map->service_job_id) ? $map->service_job_id : '')
->setServiceName(isset($map->service_name) && is_string($map->service_name) ? $map->service_name : '')
->setServiceNumber(isset($map->service_number) && is_string($map->service_number) ? $map->service_number : '')
->setServicePullRequest(isset($map->service_pull_request) && is_string($map->service_pull_request) ? $map->service_pull_request : '');
} | [
"static",
"function",
"fromJson",
"(",
"object",
"$",
"map",
")",
":",
"self",
"{",
"return",
"(",
"new",
"static",
"(",
"isset",
"(",
"$",
"map",
"->",
"source_files",
")",
"&&",
"is_array",
"(",
"$",
"map",
"->",
"source_files",
")",
"?",
"array_map"... | Creates a new job from the specified JSON map.
@param object $map A JSON map representing a job.
@return static The instance corresponding to the specified JSON map. | [
"Creates",
"a",
"new",
"job",
"from",
"the",
"specified",
"JSON",
"map",
"."
] | c196de0f92e06d5143ba90ebab18c8e384316cc0 | https://github.com/cedx/coveralls.php/blob/c196de0f92e06d5143ba90ebab18c8e384316cc0/lib/Job.php#L50-L61 | train |
netgen/site-bundle | bundle/Command/SymlinkProjectCommand.php | SymlinkProjectCommand.symlinkProjectFiles | protected function symlinkProjectFiles(string $projectFilesPath, InputInterface $input, OutputInterface $output): void
{
/** @var \DirectoryIterator[] $directories */
$directories = [];
$path = $projectFilesPath . '/root_' . $this->environment . '/';
if ($this->fileSystem->exists($path) && is_dir($path)) {
$directories[] = new DirectoryIterator($path);
}
$path = $projectFilesPath . '/root/';
if ($this->fileSystem->exists($path) && is_dir($path)) {
$directories[] = new DirectoryIterator($path);
}
foreach ($directories as $directory) {
foreach ($directory as $item) {
if ($item->isDot() || $item->isLink()) {
continue;
}
if ($item->isDir() || $item->isFile()) {
if (in_array($item->getBasename(), self::$blacklistedItems, true)) {
continue;
}
$webFolderName = $input->getOption('web-folder');
$webFolderName = !empty($webFolderName) ? $webFolderName : 'web';
$destination = $this->getContainer()->getParameter('kernel.project_dir') . '/' . $webFolderName . '/' . $item->getBasename();
if (!$this->fileSystem->exists(dirname($destination))) {
$output->writeln('Skipped creating the symlink for <comment>' . basename($destination) . '</comment> in <comment>' . dirname($destination) . '/</comment>. Folder does not exist!');
continue;
}
if ($item->isDir()) {
$this->verifyAndSymlinkDirectory(
$item->getPathname(),
$destination,
$output
);
} else {
$this->verifyAndSymlinkFile(
$item->getPathname(),
$destination,
$output
);
}
}
}
}
} | php | protected function symlinkProjectFiles(string $projectFilesPath, InputInterface $input, OutputInterface $output): void
{
/** @var \DirectoryIterator[] $directories */
$directories = [];
$path = $projectFilesPath . '/root_' . $this->environment . '/';
if ($this->fileSystem->exists($path) && is_dir($path)) {
$directories[] = new DirectoryIterator($path);
}
$path = $projectFilesPath . '/root/';
if ($this->fileSystem->exists($path) && is_dir($path)) {
$directories[] = new DirectoryIterator($path);
}
foreach ($directories as $directory) {
foreach ($directory as $item) {
if ($item->isDot() || $item->isLink()) {
continue;
}
if ($item->isDir() || $item->isFile()) {
if (in_array($item->getBasename(), self::$blacklistedItems, true)) {
continue;
}
$webFolderName = $input->getOption('web-folder');
$webFolderName = !empty($webFolderName) ? $webFolderName : 'web';
$destination = $this->getContainer()->getParameter('kernel.project_dir') . '/' . $webFolderName . '/' . $item->getBasename();
if (!$this->fileSystem->exists(dirname($destination))) {
$output->writeln('Skipped creating the symlink for <comment>' . basename($destination) . '</comment> in <comment>' . dirname($destination) . '/</comment>. Folder does not exist!');
continue;
}
if ($item->isDir()) {
$this->verifyAndSymlinkDirectory(
$item->getPathname(),
$destination,
$output
);
} else {
$this->verifyAndSymlinkFile(
$item->getPathname(),
$destination,
$output
);
}
}
}
}
} | [
"protected",
"function",
"symlinkProjectFiles",
"(",
"string",
"$",
"projectFilesPath",
",",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
":",
"void",
"{",
"/** @var \\DirectoryIterator[] $directories */",
"$",
"directories",
"=",
"[",
"... | Symlinks project files from a bundle. | [
"Symlinks",
"project",
"files",
"from",
"a",
"bundle",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Command/SymlinkProjectCommand.php#L60-L113 | train |
IconoCoders/otp-simple-sdk | Source/SimpleIos.php | SimpleIos.runIos | public function runIos()
{
$this->debugMessage[] = 'IOS: START';
if ($this->merchantId == "" || $this->orderNumber == 'N/A') {
$this->errorMessage[] = 'IOS: MISSING DATA';
$this->debugMessage[] = 'IOS: END';
return false;
}
$iosArray = array(
'MERCHANT' => $this->merchantId,
'REFNOEXT' => $this->orderNumber,
'HASH' => $this->createHashString(array($this->merchantId, $this->orderNumber))
);
$this->logFunc("IOS", $iosArray, $this->orderNumber);
$iosCounter = 0;
while ($iosCounter < $this->maxRun) {
$result = $this->startRequest($this->iosOrderUrl, $iosArray, 'POST');
if ($result === false) {
$result = '<?xml version="1.0"?>
<Order>
<ORDER_DATE>' . @date("Y-m-d H:i:s", time()) . '</ORDER_DATE>
<REFNO>N/A</REFNO>
<REFNOEXT>N/A</REFNOEXT>
<ORDER_STATUS>EMPTY RESULT</ORDER_STATUS>
<PAYMETHOD>N/A</PAYMETHOD>
<HASH>N/A</HASH>
</Order>';
}
$resultArray = (array) simplexml_load_string($result);
foreach ($resultArray as $itemName => $itemValue) {
$this->status[$itemName] = $itemValue;
}
//Validation
$valid = false;
if (!isset($this->status['HASH'])) {
$this->debugMessage[] = 'IOS HASH: MISSING';
}
if ($this->createHashString($this->flatArray($this->status, array("HASH"))) == @$this->status['HASH']) {
$valid = true;
$this->debugMessage[] = 'IOS HASH: VALID';
}
if (!$valid) {
$iosCounter += $this->maxRun+10;
$this->debugMessage[] = 'IOS HASH: INVALID';
}
//state
switch ($this->status['ORDER_STATUS']) {
case 'NOT_FOUND':
$iosCounter++;
sleep(1);
break;
case 'CARD_NOTAUTHORIZED':
$iosCounter += 5;
sleep(1);
break;
default:
$iosCounter += $this->maxRun;
}
$this->debugMessage[] = 'IOS ORDER_STATUS: ' . $this->status['ORDER_STATUS'];
}
$this->debugMessage[] = 'IOS: END';
} | php | public function runIos()
{
$this->debugMessage[] = 'IOS: START';
if ($this->merchantId == "" || $this->orderNumber == 'N/A') {
$this->errorMessage[] = 'IOS: MISSING DATA';
$this->debugMessage[] = 'IOS: END';
return false;
}
$iosArray = array(
'MERCHANT' => $this->merchantId,
'REFNOEXT' => $this->orderNumber,
'HASH' => $this->createHashString(array($this->merchantId, $this->orderNumber))
);
$this->logFunc("IOS", $iosArray, $this->orderNumber);
$iosCounter = 0;
while ($iosCounter < $this->maxRun) {
$result = $this->startRequest($this->iosOrderUrl, $iosArray, 'POST');
if ($result === false) {
$result = '<?xml version="1.0"?>
<Order>
<ORDER_DATE>' . @date("Y-m-d H:i:s", time()) . '</ORDER_DATE>
<REFNO>N/A</REFNO>
<REFNOEXT>N/A</REFNOEXT>
<ORDER_STATUS>EMPTY RESULT</ORDER_STATUS>
<PAYMETHOD>N/A</PAYMETHOD>
<HASH>N/A</HASH>
</Order>';
}
$resultArray = (array) simplexml_load_string($result);
foreach ($resultArray as $itemName => $itemValue) {
$this->status[$itemName] = $itemValue;
}
//Validation
$valid = false;
if (!isset($this->status['HASH'])) {
$this->debugMessage[] = 'IOS HASH: MISSING';
}
if ($this->createHashString($this->flatArray($this->status, array("HASH"))) == @$this->status['HASH']) {
$valid = true;
$this->debugMessage[] = 'IOS HASH: VALID';
}
if (!$valid) {
$iosCounter += $this->maxRun+10;
$this->debugMessage[] = 'IOS HASH: INVALID';
}
//state
switch ($this->status['ORDER_STATUS']) {
case 'NOT_FOUND':
$iosCounter++;
sleep(1);
break;
case 'CARD_NOTAUTHORIZED':
$iosCounter += 5;
sleep(1);
break;
default:
$iosCounter += $this->maxRun;
}
$this->debugMessage[] = 'IOS ORDER_STATUS: ' . $this->status['ORDER_STATUS'];
}
$this->debugMessage[] = 'IOS: END';
} | [
"public",
"function",
"runIos",
"(",
")",
"{",
"$",
"this",
"->",
"debugMessage",
"[",
"]",
"=",
"'IOS: START'",
";",
"if",
"(",
"$",
"this",
"->",
"merchantId",
"==",
"\"\"",
"||",
"$",
"this",
"->",
"orderNumber",
"==",
"'N/A'",
")",
"{",
"$",
"thi... | Starts IOS communication
@return void | [
"Starts",
"IOS",
"communication"
] | d2808bf52e8d34be69414b444a00f1a9c8564930 | https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleIos.php#L87-L151 | train |
alaxos/cakephp3-libs | src/View/Helper/AlaxosFormHelper.php | AlaxosFormHelper.antispam | public function antispam($form_dom_id)
{
$salt = isset($this->_View->viewVars['_alaxos_spam_filter_salt']) ? $this->_View->viewVars['_alaxos_spam_filter_salt'] : null;
$token = SecurityTool::get_today_token($salt);
/*
* Unlock hidden field added by JS to prevent blackholing of form
*/
$fieldname = SecurityTool::get_today_fieldname($salt);
$this->unlockField($fieldname);
return $this->AlaxosHtml->script(Router::url(['prefix' => false, 'plugin' => 'Alaxos', 'controller' => 'Javascripts', 'action' => 'antispam', '_ext' => 'js', '?' => ['fid' => $form_dom_id, 'token' => $token]], true), ['block' => true]);
} | php | public function antispam($form_dom_id)
{
$salt = isset($this->_View->viewVars['_alaxos_spam_filter_salt']) ? $this->_View->viewVars['_alaxos_spam_filter_salt'] : null;
$token = SecurityTool::get_today_token($salt);
/*
* Unlock hidden field added by JS to prevent blackholing of form
*/
$fieldname = SecurityTool::get_today_fieldname($salt);
$this->unlockField($fieldname);
return $this->AlaxosHtml->script(Router::url(['prefix' => false, 'plugin' => 'Alaxos', 'controller' => 'Javascripts', 'action' => 'antispam', '_ext' => 'js', '?' => ['fid' => $form_dom_id, 'token' => $token]], true), ['block' => true]);
} | [
"public",
"function",
"antispam",
"(",
"$",
"form_dom_id",
")",
"{",
"$",
"salt",
"=",
"isset",
"(",
"$",
"this",
"->",
"_View",
"->",
"viewVars",
"[",
"'_alaxos_spam_filter_salt'",
"]",
")",
"?",
"$",
"this",
"->",
"_View",
"->",
"viewVars",
"[",
"'_ala... | Add some JS code that add a hidden field
If the hidden field is not present in the POST, SpamFilterComponent considers the request as spam. | [
"Add",
"some",
"JS",
"code",
"that",
"add",
"a",
"hidden",
"field",
"If",
"the",
"hidden",
"field",
"is",
"not",
"present",
"in",
"the",
"POST",
"SpamFilterComponent",
"considers",
"the",
"request",
"as",
"spam",
"."
] | 685e9f17a3fbe3550c59a03a65c4d75df763e804 | https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/View/Helper/AlaxosFormHelper.php#L406-L418 | train |
netgen/site-bundle | bundle/Core/MVC/Symfony/Matcher/ConfigResolverBased.php | ConfigResolverBased.doMatch | public function doMatch($value): bool
{
$config = $this->values[0];
$namespace = $this->values[1] ?? null;
if ($this->configResolver->hasParameter($config, $namespace)) {
$configValue = $this->configResolver->getParameter($config, $namespace);
$configValue = !is_array($configValue) ? [$configValue] : $configValue;
return in_array($value, $configValue, true);
}
return false;
} | php | public function doMatch($value): bool
{
$config = $this->values[0];
$namespace = $this->values[1] ?? null;
if ($this->configResolver->hasParameter($config, $namespace)) {
$configValue = $this->configResolver->getParameter($config, $namespace);
$configValue = !is_array($configValue) ? [$configValue] : $configValue;
return in_array($value, $configValue, true);
}
return false;
} | [
"public",
"function",
"doMatch",
"(",
"$",
"value",
")",
":",
"bool",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"values",
"[",
"0",
"]",
";",
"$",
"namespace",
"=",
"$",
"this",
"->",
"values",
"[",
"1",
"]",
"??",
"null",
";",
"if",
"(",
"$"... | Performs the match against the provided value.
This works by comparing the value against the parameter from config resolver.
First element in the value array should be the name of the parameter and the
second should be the namespace.
@param mixed $value
@return bool | [
"Performs",
"the",
"match",
"against",
"the",
"provided",
"value",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Core/MVC/Symfony/Matcher/ConfigResolverBased.php#L33-L46 | train |
smartboxgroup/integration-framework-bundle | Core/Producers/AbstractConfigurableProducer.php | AbstractConfigurableProducer.executeStep | public function executeStep($stepAction, &$stepActionParams, &$options, array &$context)
{
return $this->getConfHelper()->executeStep($stepAction, $stepActionParams, $options, $context);
} | php | public function executeStep($stepAction, &$stepActionParams, &$options, array &$context)
{
return $this->getConfHelper()->executeStep($stepAction, $stepActionParams, $options, $context);
} | [
"public",
"function",
"executeStep",
"(",
"$",
"stepAction",
",",
"&",
"$",
"stepActionParams",
",",
"&",
"$",
"options",
",",
"array",
"&",
"$",
"context",
")",
"{",
"return",
"$",
"this",
"->",
"getConfHelper",
"(",
")",
"->",
"executeStep",
"(",
"$",
... | Returns true if the step was executed, false if the step was not recognized.
@param $stepAction
@param $stepActionParams
@param $options
@param array $context
@return bool | [
"Returns",
"true",
"if",
"the",
"step",
"was",
"executed",
"false",
"if",
"the",
"step",
"was",
"not",
"recognized",
"."
] | 5f0bf8ff86337a51f6d208bd38df39017643b905 | https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Core/Producers/AbstractConfigurableProducer.php#L91-L94 | train |
netgen/ngsymfonytools | classes/ngsymfonytoolsrenderoperator.php | NgSymfonyToolsRenderOperator.renderUri | public static function renderUri( $uri, $options = array() )
{
$serviceContainer = ezpKernel::instance()->getServiceContainer();
$fragmentHandler = $serviceContainer->get( 'fragment.handler' );
$strategy = isset( $options['strategy'] ) ? $options['strategy'] : 'inline';
unset( $options['strategy'] );
try
{
return $fragmentHandler->render( $uri, $strategy, $options );
}
catch ( InvalidArgumentException $e )
{
throw new InvalidArgumentException( "The URI {$uri->controller} couldn't be rendered", 0, $e );
}
} | php | public static function renderUri( $uri, $options = array() )
{
$serviceContainer = ezpKernel::instance()->getServiceContainer();
$fragmentHandler = $serviceContainer->get( 'fragment.handler' );
$strategy = isset( $options['strategy'] ) ? $options['strategy'] : 'inline';
unset( $options['strategy'] );
try
{
return $fragmentHandler->render( $uri, $strategy, $options );
}
catch ( InvalidArgumentException $e )
{
throw new InvalidArgumentException( "The URI {$uri->controller} couldn't be rendered", 0, $e );
}
} | [
"public",
"static",
"function",
"renderUri",
"(",
"$",
"uri",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"serviceContainer",
"=",
"ezpKernel",
"::",
"instance",
"(",
")",
"->",
"getServiceContainer",
"(",
")",
";",
"$",
"fragmentHandler",
... | Renders the given URI with Symfony stack
@param string|\Symfony\Component\HttpKernel\Controller\ControllerReference $uri
@param array $options
@return string | [
"Renders",
"the",
"given",
"URI",
"with",
"Symfony",
"stack"
] | 58abf97996ddd1d4f969d8c64ce6998b9d1a5c27 | https://github.com/netgen/ngsymfonytools/blob/58abf97996ddd1d4f969d8c64ce6998b9d1a5c27/classes/ngsymfonytoolsrenderoperator.php#L122-L138 | train |
netgen/ngsymfonytools | classes/ngsymfonytoolsisgrantedoperator.php | NgSymfonyToolsIsGrantedOperator.isGranted | public static function isGranted( $role, $object = null, $field = null )
{
$serviceContainer = ezpKernel::instance()->getServiceContainer();
if ( $field !== null && class_exists( 'Symfony\Component\Security\Acl\Voter\FieldVote' ) )
{
$object = new FieldVote( $object, $field );
}
try
{
return $serviceContainer->get( 'security.authorization_checker' )->isGranted( $role, $object );
}
catch ( AuthenticationCredentialsNotFoundException $e )
{
return false;
}
} | php | public static function isGranted( $role, $object = null, $field = null )
{
$serviceContainer = ezpKernel::instance()->getServiceContainer();
if ( $field !== null && class_exists( 'Symfony\Component\Security\Acl\Voter\FieldVote' ) )
{
$object = new FieldVote( $object, $field );
}
try
{
return $serviceContainer->get( 'security.authorization_checker' )->isGranted( $role, $object );
}
catch ( AuthenticationCredentialsNotFoundException $e )
{
return false;
}
} | [
"public",
"static",
"function",
"isGranted",
"(",
"$",
"role",
",",
"$",
"object",
"=",
"null",
",",
"$",
"field",
"=",
"null",
")",
"{",
"$",
"serviceContainer",
"=",
"ezpKernel",
"::",
"instance",
"(",
")",
"->",
"getServiceContainer",
"(",
")",
";",
... | Returns if the current user has access to provided role.
@param mixed $role
@param mixed $object
@param mixed $field
@return bool | [
"Returns",
"if",
"the",
"current",
"user",
"has",
"access",
"to",
"provided",
"role",
"."
] | 58abf97996ddd1d4f969d8c64ce6998b9d1a5c27 | https://github.com/netgen/ngsymfonytools/blob/58abf97996ddd1d4f969d8c64ce6998b9d1a5c27/classes/ngsymfonytoolsisgrantedoperator.php#L82-L99 | train |
nilportugues/php-api-transformer | src/Mapping/MappingFactory.php | MappingFactory.getClassProperties | protected static function getClassProperties(string $className) : array
{
if (empty(static::$classProperties[$className])) {
$ref = new ReflectionClass($className);
$properties = [];
foreach ($ref->getProperties() as $prop) {
$f = $prop->getName();
$properties[$f] = $prop;
}
if ($parentClass = $ref->getParentClass()) {
$parentPropsArr = static::getClassProperties($parentClass->getName());
if (\count($parentPropsArr) > 0) {
$properties = \array_merge($parentPropsArr, $properties);
}
}
static::$classProperties[$className] = \array_keys($properties);
}
return static::$classProperties[$className];
} | php | protected static function getClassProperties(string $className) : array
{
if (empty(static::$classProperties[$className])) {
$ref = new ReflectionClass($className);
$properties = [];
foreach ($ref->getProperties() as $prop) {
$f = $prop->getName();
$properties[$f] = $prop;
}
if ($parentClass = $ref->getParentClass()) {
$parentPropsArr = static::getClassProperties($parentClass->getName());
if (\count($parentPropsArr) > 0) {
$properties = \array_merge($parentPropsArr, $properties);
}
}
static::$classProperties[$className] = \array_keys($properties);
}
return static::$classProperties[$className];
} | [
"protected",
"static",
"function",
"getClassProperties",
"(",
"string",
"$",
"className",
")",
":",
"array",
"{",
"if",
"(",
"empty",
"(",
"static",
"::",
"$",
"classProperties",
"[",
"$",
"className",
"]",
")",
")",
"{",
"$",
"ref",
"=",
"new",
"Reflect... | Recursive function to get an associative array of class properties by
property name, including inherited ones from extended classes.
@param string $className Class name
@return array
@link http://php.net/manual/es/reflectionclass.getproperties.php#88405 | [
"Recursive",
"function",
"to",
"get",
"an",
"associative",
"array",
"of",
"class",
"properties",
"by",
"property",
"name",
"including",
"inherited",
"ones",
"from",
"extended",
"classes",
"."
] | a9f20fbe1580d98e3d462a0ebe13fb7595cbd683 | https://github.com/nilportugues/php-api-transformer/blob/a9f20fbe1580d98e3d462a0ebe13fb7595cbd683/src/Mapping/MappingFactory.php#L187-L207 | train |
Atnic/laravel-generator | app/Console/Commands/ControllerMakeCommand.php | ControllerMakeCommand.getViewStub | protected function getViewStub($method = null, $name = null)
{
if (in_array($name, [ $this->qualifyClass('ModelController'), $this->qualifyClass('Model/ChildController') ])) {
if ($this->option('parent')) {
return __DIR__.'/stubs/view.nested.model.'.$method.'.stub';
} elseif ($this->option('model') || $this->option('resource')) {
return __DIR__.'/stubs/view.model.'.$method.'.stub';
}
}
if ($this->option('parent')) {
return __DIR__.'/stubs/view.nested.'.$method.'.stub';
} elseif ($this->option('model') || $this->option('resource')) {
return __DIR__.'/stubs/view.'.$method.'.stub';
}
return __DIR__.'/stubs/view.stub';
} | php | protected function getViewStub($method = null, $name = null)
{
if (in_array($name, [ $this->qualifyClass('ModelController'), $this->qualifyClass('Model/ChildController') ])) {
if ($this->option('parent')) {
return __DIR__.'/stubs/view.nested.model.'.$method.'.stub';
} elseif ($this->option('model') || $this->option('resource')) {
return __DIR__.'/stubs/view.model.'.$method.'.stub';
}
}
if ($this->option('parent')) {
return __DIR__.'/stubs/view.nested.'.$method.'.stub';
} elseif ($this->option('model') || $this->option('resource')) {
return __DIR__.'/stubs/view.'.$method.'.stub';
}
return __DIR__.'/stubs/view.stub';
} | [
"protected",
"function",
"getViewStub",
"(",
"$",
"method",
"=",
"null",
",",
"$",
"name",
"=",
"null",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"name",
",",
"[",
"$",
"this",
"->",
"qualifyClass",
"(",
"'ModelController'",
")",
",",
"$",
"this",
"... | Get the view stub file for the generator.
@param string|null $method
@param string|null $name
@return string | [
"Get",
"the",
"view",
"stub",
"file",
"for",
"the",
"generator",
"."
] | 7bf53837a61af566b389255784dbbf1789020018 | https://github.com/Atnic/laravel-generator/blob/7bf53837a61af566b389255784dbbf1789020018/app/Console/Commands/ControllerMakeCommand.php#L49-L66 | train |
Atnic/laravel-generator | app/Console/Commands/ControllerMakeCommand.php | ControllerMakeCommand.buildView | protected function buildView($name, $method = null)
{
$replace = [];
if ($this->option('parent')) {
$replace = $this->buildParentReplacements();
}
if ($this->option('model')) {
$replace = $this->buildModelReplacements($replace);
}
if ($this->option('parent')) {
$replace['parent_dummy_view'] = $this->getParentViewName($name);
$replace['parent_dummy_route'] = $this->getParentRouteName($name);
}
$replace['dummy_view'] = $this->getViewName($name);
$replace['dummy_route'] = $this->getRouteName($name);
return str_replace(array_keys($replace), array_values($replace), $this->files->get($this->getViewStub($method, $name)));
} | php | protected function buildView($name, $method = null)
{
$replace = [];
if ($this->option('parent')) {
$replace = $this->buildParentReplacements();
}
if ($this->option('model')) {
$replace = $this->buildModelReplacements($replace);
}
if ($this->option('parent')) {
$replace['parent_dummy_view'] = $this->getParentViewName($name);
$replace['parent_dummy_route'] = $this->getParentRouteName($name);
}
$replace['dummy_view'] = $this->getViewName($name);
$replace['dummy_route'] = $this->getRouteName($name);
return str_replace(array_keys($replace), array_values($replace), $this->files->get($this->getViewStub($method, $name)));
} | [
"protected",
"function",
"buildView",
"(",
"$",
"name",
",",
"$",
"method",
"=",
"null",
")",
"{",
"$",
"replace",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"option",
"(",
"'parent'",
")",
")",
"{",
"$",
"replace",
"=",
"$",
"this",
"->",... | Build the view with the given name.
@param string $name
@param string|null $method
@return string
@throws \Illuminate\Contracts\Filesystem\FileNotFoundException | [
"Build",
"the",
"view",
"with",
"the",
"given",
"name",
"."
] | 7bf53837a61af566b389255784dbbf1789020018 | https://github.com/Atnic/laravel-generator/blob/7bf53837a61af566b389255784dbbf1789020018/app/Console/Commands/ControllerMakeCommand.php#L178-L198 | train |
Atnic/laravel-generator | app/Console/Commands/ControllerMakeCommand.php | ControllerMakeCommand.generateView | protected function generateView()
{
if ($this->option('parent') || $this->option('model') || $this->option('resource')) {
if ($this->option('parent')) {
$name = $this->qualifyClass('Model/ChildController');
} else {
$name = $this->qualifyClass('ModelController');
}
$path = $this->getViewPath($name);
if (!$this->files->exists(str_replace_last('.blade.php', '/index.blade.php', $path))) {
foreach ([ 'index', 'create', 'show', 'edit' ] as $key => $method) {
$this->makeDirectory(str_replace_last('.blade.php', '/' . $method . '.blade.php', $path));
$this->files->put(str_replace_last('.blade.php', '/' . $method . '.blade.php', $path), $this->buildView($name, $method));
}
}
}
$name = $this->qualifyClass($this->getNameInput());
$path = $this->getViewPath($name);
if ($this->option('parent') || $this->option('model') || $this->option('resource')) {
foreach ([ 'index', 'create', 'show', 'edit' ] as $key => $method) {
$this->makeDirectory(str_replace_last('.blade.php', '/' . $method . '.blade.php', $path));
$this->files->put(str_replace_last('.blade.php', '/' . $method . '.blade.php', $path), $this->buildView($name, $method));
}
} else {
$this->makeDirectory($path);
$this->files->put($path, $this->buildView($name));
}
$this->info('View also generated successfully.');
} | php | protected function generateView()
{
if ($this->option('parent') || $this->option('model') || $this->option('resource')) {
if ($this->option('parent')) {
$name = $this->qualifyClass('Model/ChildController');
} else {
$name = $this->qualifyClass('ModelController');
}
$path = $this->getViewPath($name);
if (!$this->files->exists(str_replace_last('.blade.php', '/index.blade.php', $path))) {
foreach ([ 'index', 'create', 'show', 'edit' ] as $key => $method) {
$this->makeDirectory(str_replace_last('.blade.php', '/' . $method . '.blade.php', $path));
$this->files->put(str_replace_last('.blade.php', '/' . $method . '.blade.php', $path), $this->buildView($name, $method));
}
}
}
$name = $this->qualifyClass($this->getNameInput());
$path = $this->getViewPath($name);
if ($this->option('parent') || $this->option('model') || $this->option('resource')) {
foreach ([ 'index', 'create', 'show', 'edit' ] as $key => $method) {
$this->makeDirectory(str_replace_last('.blade.php', '/' . $method . '.blade.php', $path));
$this->files->put(str_replace_last('.blade.php', '/' . $method . '.blade.php', $path), $this->buildView($name, $method));
}
} else {
$this->makeDirectory($path);
$this->files->put($path, $this->buildView($name));
}
$this->info('View also generated successfully.');
} | [
"protected",
"function",
"generateView",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"option",
"(",
"'parent'",
")",
"||",
"$",
"this",
"->",
"option",
"(",
"'model'",
")",
"||",
"$",
"this",
"->",
"option",
"(",
"'resource'",
")",
")",
"{",
"if",
... | Generate View Files
@return void
@throws \Illuminate\Contracts\Filesystem\FileNotFoundException | [
"Generate",
"View",
"Files"
] | 7bf53837a61af566b389255784dbbf1789020018 | https://github.com/Atnic/laravel-generator/blob/7bf53837a61af566b389255784dbbf1789020018/app/Console/Commands/ControllerMakeCommand.php#L305-L337 | train |
Atnic/laravel-generator | app/Console/Commands/ControllerMakeCommand.php | ControllerMakeCommand.appendRouteFile | protected function appendRouteFile()
{
$name = $this->qualifyClass($this->getNameInput());
$nameWithoutNamespace = str_replace($this->getDefaultNamespace(trim($this->rootNamespace(), '\\')).'\\', '', $name);
$file = $this->option('api') ? base_path('routes/api.php') : base_path('routes/web.php');
$routeName = $this->getRouteName($name);
$routePath = $this->getRoutePath($name);
$routeDefinition = 'Route::get(\''.$routePath.'\', \''.$nameWithoutNamespace.'\')->name(\''.$routeName.'\');'.PHP_EOL;
if ($this->option('parent') || $this->option('model') || $this->option('resource')) {
$asExploded = explode('/', $routePath);
if (count($asExploded) > 1) {
array_pop($asExploded);
$as = implode('.', $asExploded);
if ($this->option('api'))
$routeDefinition = 'Route::apiResource(\''.$routePath.'\', \''.$nameWithoutNamespace.'\', [ \'as\' => \''.$as.'\' ]);'.PHP_EOL;
else $routeDefinition = 'Route::resource(\''.$routePath.'\', \''.$nameWithoutNamespace.'\');'.PHP_EOL;
} else {
if ($this->option('api'))
$routeDefinition = 'Route::apiResource(\''.$routePath.'\', \''.$nameWithoutNamespace.'\', [ \'as\' => \'api\' ]);'.PHP_EOL;
else $routeDefinition = 'Route::resource(\''.$routePath.'\', \''.$nameWithoutNamespace.'\');'.PHP_EOL;
}
}
file_put_contents($file, $routeDefinition, FILE_APPEND);
$this->warn($file.' modified.');
} | php | protected function appendRouteFile()
{
$name = $this->qualifyClass($this->getNameInput());
$nameWithoutNamespace = str_replace($this->getDefaultNamespace(trim($this->rootNamespace(), '\\')).'\\', '', $name);
$file = $this->option('api') ? base_path('routes/api.php') : base_path('routes/web.php');
$routeName = $this->getRouteName($name);
$routePath = $this->getRoutePath($name);
$routeDefinition = 'Route::get(\''.$routePath.'\', \''.$nameWithoutNamespace.'\')->name(\''.$routeName.'\');'.PHP_EOL;
if ($this->option('parent') || $this->option('model') || $this->option('resource')) {
$asExploded = explode('/', $routePath);
if (count($asExploded) > 1) {
array_pop($asExploded);
$as = implode('.', $asExploded);
if ($this->option('api'))
$routeDefinition = 'Route::apiResource(\''.$routePath.'\', \''.$nameWithoutNamespace.'\', [ \'as\' => \''.$as.'\' ]);'.PHP_EOL;
else $routeDefinition = 'Route::resource(\''.$routePath.'\', \''.$nameWithoutNamespace.'\');'.PHP_EOL;
} else {
if ($this->option('api'))
$routeDefinition = 'Route::apiResource(\''.$routePath.'\', \''.$nameWithoutNamespace.'\', [ \'as\' => \'api\' ]);'.PHP_EOL;
else $routeDefinition = 'Route::resource(\''.$routePath.'\', \''.$nameWithoutNamespace.'\');'.PHP_EOL;
}
}
file_put_contents($file, $routeDefinition, FILE_APPEND);
$this->warn($file.' modified.');
} | [
"protected",
"function",
"appendRouteFile",
"(",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"qualifyClass",
"(",
"$",
"this",
"->",
"getNameInput",
"(",
")",
")",
";",
"$",
"nameWithoutNamespace",
"=",
"str_replace",
"(",
"$",
"this",
"->",
"getDefault... | Append Route Files
@return void | [
"Append",
"Route",
"Files"
] | 7bf53837a61af566b389255784dbbf1789020018 | https://github.com/Atnic/laravel-generator/blob/7bf53837a61af566b389255784dbbf1789020018/app/Console/Commands/ControllerMakeCommand.php#L343-L372 | train |
Atnic/laravel-generator | app/Console/Commands/ControllerMakeCommand.php | ControllerMakeCommand.getParentViewName | protected function getParentViewName($name)
{
$name = Str::replaceFirst($this->getDefaultNamespace(trim($this->rootNamespace(), '\\')).'\\', '', $name);
$name = Str::replaceLast('Controller', '', $name);
$names = explode('\\', $name);
foreach ($names as $key => $value) {
$names[$key] = snake_case($value);
}
if (count($names) >= 2) {
array_pop($names);
$parent = str_plural(array_pop($names));
array_push($names, $parent);
}
$name = implode('.', $names);
return str_replace('\\', '.', $name);
} | php | protected function getParentViewName($name)
{
$name = Str::replaceFirst($this->getDefaultNamespace(trim($this->rootNamespace(), '\\')).'\\', '', $name);
$name = Str::replaceLast('Controller', '', $name);
$names = explode('\\', $name);
foreach ($names as $key => $value) {
$names[$key] = snake_case($value);
}
if (count($names) >= 2) {
array_pop($names);
$parent = str_plural(array_pop($names));
array_push($names, $parent);
}
$name = implode('.', $names);
return str_replace('\\', '.', $name);
} | [
"protected",
"function",
"getParentViewName",
"(",
"$",
"name",
")",
"{",
"$",
"name",
"=",
"Str",
"::",
"replaceFirst",
"(",
"$",
"this",
"->",
"getDefaultNamespace",
"(",
"trim",
"(",
"$",
"this",
"->",
"rootNamespace",
"(",
")",
",",
"'\\\\'",
")",
")... | Get the view name.
@param string $name
@return string | [
"Get",
"the",
"view",
"name",
"."
] | 7bf53837a61af566b389255784dbbf1789020018 | https://github.com/Atnic/laravel-generator/blob/7bf53837a61af566b389255784dbbf1789020018/app/Console/Commands/ControllerMakeCommand.php#L407-L423 | train |
alaxos/cakephp3-libs | src/Model/Behavior/AncestorBehavior.php | AncestorBehavior.getAncestorTable | public function getAncestorTable()
{
$ancestor_table = TableRegistry::get('Alaxos.Ancestors');
$table_name = $this->getConfig('ancestor_table_name');
$ancestor_table->setTable($table_name);
return $ancestor_table;
} | php | public function getAncestorTable()
{
$ancestor_table = TableRegistry::get('Alaxos.Ancestors');
$table_name = $this->getConfig('ancestor_table_name');
$ancestor_table->setTable($table_name);
return $ancestor_table;
} | [
"public",
"function",
"getAncestorTable",
"(",
")",
"{",
"$",
"ancestor_table",
"=",
"TableRegistry",
"::",
"get",
"(",
"'Alaxos.Ancestors'",
")",
";",
"$",
"table_name",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'ancestor_table_name'",
")",
";",
"$",
"ancest... | Get the Table for the linked ancestors table
@return @return \Cake\ORM\Table | [
"Get",
"the",
"Table",
"for",
"the",
"linked",
"ancestors",
"table"
] | 685e9f17a3fbe3550c59a03a65c4d75df763e804 | https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Model/Behavior/AncestorBehavior.php#L273-L281 | train |
alaxos/cakephp3-libs | src/Model/Behavior/AncestorBehavior.php | AncestorBehavior.getMultilevelChildren | public function getMultilevelChildren($id, array $options = [])
{
$options['for'] = $id;
$options['direct'] = false;
$options['for'] = $id;
$options['direct'] = false;
$query = $this->_table->find();
$iterator = $this->findChildren($query, $options);
$primaryKey = $this->_table->getSchema()->primaryKey();
$primaryKey = count($primaryKey) == 1 ? $primaryKey[0] : $primaryKey;
$parent_id_fieldname = $this->getConfig('model_parent_id_fieldname');
$nodes_by_pk = [];
$root_nodes = [];
foreach($iterator as $node)
{
$nodes_by_pk[$node->{$primaryKey}] = $node;
if($node->{$parent_id_fieldname} == $id)
{
$root_nodes[] = $node;
}
if(isset($nodes_by_pk[$node->{$parent_id_fieldname}]))
{
if(!isset($nodes_by_pk[$node->{$parent_id_fieldname}]->children))
{
$nodes_by_pk[$node->{$parent_id_fieldname}]->children = [];
}
$nodes_by_pk[$node->{$parent_id_fieldname}]->children[] = $node;
}
}
unset($node);
return new \Cake\Collection\Collection($root_nodes);
} | php | public function getMultilevelChildren($id, array $options = [])
{
$options['for'] = $id;
$options['direct'] = false;
$options['for'] = $id;
$options['direct'] = false;
$query = $this->_table->find();
$iterator = $this->findChildren($query, $options);
$primaryKey = $this->_table->getSchema()->primaryKey();
$primaryKey = count($primaryKey) == 1 ? $primaryKey[0] : $primaryKey;
$parent_id_fieldname = $this->getConfig('model_parent_id_fieldname');
$nodes_by_pk = [];
$root_nodes = [];
foreach($iterator as $node)
{
$nodes_by_pk[$node->{$primaryKey}] = $node;
if($node->{$parent_id_fieldname} == $id)
{
$root_nodes[] = $node;
}
if(isset($nodes_by_pk[$node->{$parent_id_fieldname}]))
{
if(!isset($nodes_by_pk[$node->{$parent_id_fieldname}]->children))
{
$nodes_by_pk[$node->{$parent_id_fieldname}]->children = [];
}
$nodes_by_pk[$node->{$parent_id_fieldname}]->children[] = $node;
}
}
unset($node);
return new \Cake\Collection\Collection($root_nodes);
} | [
"public",
"function",
"getMultilevelChildren",
"(",
"$",
"id",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"[",
"'for'",
"]",
"=",
"$",
"id",
";",
"$",
"options",
"[",
"'direct'",
"]",
"=",
"false",
";",
"$",
"options",
"... | Return a multi-dimension array of child nodes
@param int $id
@param array $options
@return \Cake\Collection\Collection | [
"Return",
"a",
"multi",
"-",
"dimension",
"array",
"of",
"child",
"nodes"
] | 685e9f17a3fbe3550c59a03a65c4d75df763e804 | https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Model/Behavior/AncestorBehavior.php#L627-L668 | train |
alaxos/cakephp3-libs | src/Model/Behavior/AncestorBehavior.php | AncestorBehavior.moveNode | public function moveNode($id, $parent_id, $position = null)
{
$primaryKey = $this->_table->getSchema()->primaryKey();
$primaryKey = count($primaryKey) == 1 ? $primaryKey[0] : $primaryKey;
$parent_id_fieldname = $this->getConfig('model_parent_id_fieldname');
$sort_fieldname = $this->getConfig('model_sort_fieldname');
$connection = $this->_table->getConnection();
$connection->begin();
$result = true;
/*
* Get moved node
*/
$node = $this->_table->get($id);
/*
* Get current nodes positions of (new) siblings
*/
$current_children = $this->_table->query()->where([$parent_id_fieldname => $parent_id])->order([$sort_fieldname => 'asc']);
$new_sort_children = [];
foreach($current_children as $current_position => $current_child)
{
if($current_child->{$primaryKey} != $id)
{
$new_sort_children[] = $current_child;
}
}
/*
* Default position is after all siblings
*/
$position = isset($position) ? $position : $current_children->count();
$position = $position >= 0 ? $position : 0;
$position = $position <= count($new_sort_children) ? $position : count($new_sort_children);
/*
* Insert moved node at position
*/
array_splice($new_sort_children, $position, 0, array($node));
/*
* If node has a new parent -> save it
*/
if($node->{$parent_id_fieldname} != $parent_id)
{
$query = $this->_table->query()->update()->set([$parent_id_fieldname => $parent_id])->where([$primaryKey => $id]);
if(!$query->execute())
{
$result = false;
}
}
/*
* Update positions
*/
foreach($new_sort_children as $index => $new_sort_child)
{
$query = $this->_table->query()->update()->set([$sort_fieldname => ($index * 10)])->where([$primaryKey => $new_sort_child->{$primaryKey}]);
if(!$query->execute())
{
$result = false;
}
}
/***********/
if($result)
{
$connection->commit();
}
else
{
$connection->rollback();
}
return $result;
} | php | public function moveNode($id, $parent_id, $position = null)
{
$primaryKey = $this->_table->getSchema()->primaryKey();
$primaryKey = count($primaryKey) == 1 ? $primaryKey[0] : $primaryKey;
$parent_id_fieldname = $this->getConfig('model_parent_id_fieldname');
$sort_fieldname = $this->getConfig('model_sort_fieldname');
$connection = $this->_table->getConnection();
$connection->begin();
$result = true;
/*
* Get moved node
*/
$node = $this->_table->get($id);
/*
* Get current nodes positions of (new) siblings
*/
$current_children = $this->_table->query()->where([$parent_id_fieldname => $parent_id])->order([$sort_fieldname => 'asc']);
$new_sort_children = [];
foreach($current_children as $current_position => $current_child)
{
if($current_child->{$primaryKey} != $id)
{
$new_sort_children[] = $current_child;
}
}
/*
* Default position is after all siblings
*/
$position = isset($position) ? $position : $current_children->count();
$position = $position >= 0 ? $position : 0;
$position = $position <= count($new_sort_children) ? $position : count($new_sort_children);
/*
* Insert moved node at position
*/
array_splice($new_sort_children, $position, 0, array($node));
/*
* If node has a new parent -> save it
*/
if($node->{$parent_id_fieldname} != $parent_id)
{
$query = $this->_table->query()->update()->set([$parent_id_fieldname => $parent_id])->where([$primaryKey => $id]);
if(!$query->execute())
{
$result = false;
}
}
/*
* Update positions
*/
foreach($new_sort_children as $index => $new_sort_child)
{
$query = $this->_table->query()->update()->set([$sort_fieldname => ($index * 10)])->where([$primaryKey => $new_sort_child->{$primaryKey}]);
if(!$query->execute())
{
$result = false;
}
}
/***********/
if($result)
{
$connection->commit();
}
else
{
$connection->rollback();
}
return $result;
} | [
"public",
"function",
"moveNode",
"(",
"$",
"id",
",",
"$",
"parent_id",
",",
"$",
"position",
"=",
"null",
")",
"{",
"$",
"primaryKey",
"=",
"$",
"this",
"->",
"_table",
"->",
"getSchema",
"(",
")",
"->",
"primaryKey",
"(",
")",
";",
"$",
"primaryKe... | Move a node under the same parent node or under a new node.
New position of the node can be specified
@param int $id ID of the node to move
@param int $parent_id ID of the (new) parent node
@param int $position New position of the node. Position is zero based.
@return boolean | [
"Move",
"a",
"node",
"under",
"the",
"same",
"parent",
"node",
"or",
"under",
"a",
"new",
"node",
".",
"New",
"position",
"of",
"the",
"node",
"can",
"be",
"specified"
] | 685e9f17a3fbe3550c59a03a65c4d75df763e804 | https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Model/Behavior/AncestorBehavior.php#L698-L779 | train |
smartboxgroup/integration-framework-bundle | Core/Handlers/MessageHandler.php | MessageHandler.dispatchEvent | protected function dispatchEvent(Exchange $exchange, $eventName)
{
$event = new HandlerEvent($eventName);
$event->setTimestampToCurrent();
$event->setExchange($exchange);
$this->eventDispatcher->dispatch($eventName, $event);
} | php | protected function dispatchEvent(Exchange $exchange, $eventName)
{
$event = new HandlerEvent($eventName);
$event->setTimestampToCurrent();
$event->setExchange($exchange);
$this->eventDispatcher->dispatch($eventName, $event);
} | [
"protected",
"function",
"dispatchEvent",
"(",
"Exchange",
"$",
"exchange",
",",
"$",
"eventName",
")",
"{",
"$",
"event",
"=",
"new",
"HandlerEvent",
"(",
"$",
"eventName",
")",
";",
"$",
"event",
"->",
"setTimestampToCurrent",
"(",
")",
";",
"$",
"event"... | Dispatch handler event depending on an event name
@param Exchange $exchange
@param $eventName | [
"Dispatch",
"handler",
"event",
"depending",
"on",
"an",
"event",
"name"
] | 5f0bf8ff86337a51f6d208bd38df39017643b905 | https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Core/Handlers/MessageHandler.php#L309-L315 | train |
smartboxgroup/integration-framework-bundle | Core/Handlers/MessageHandler.php | MessageHandler.addCallbackHeadersToEnvelope | private function addCallbackHeadersToEnvelope(CallbackExchangeEnvelope $envelope, ProcessingException $exception, ProcessorInterface $processor)
{
$originalException = $exception->getOriginalException();
$errorDescription = $originalException ? $originalException->getMessage() : $exception->getMessage();
$envelope->setHeader(CallbackExchangeEnvelope::HEADER_CREATED_AT, round(microtime(true) * 1000));
$envelope->setHeader(CallbackExchangeEnvelope::HEADER_ERROR_MESSAGE, $errorDescription);
$envelope->setHeader(CallbackExchangeEnvelope::HEADER_ERROR_PROCESSOR_ID, $processor->getId());
$envelope->setHeader(CallbackExchangeEnvelope::HEADER_ERROR_PROCESSOR_DESCRIPTION, $processor->getDescription());
$envelope->setHeader(CallbackExchangeEnvelope::HEADER_STATUS_CODE, $originalException->getCode());
} | php | private function addCallbackHeadersToEnvelope(CallbackExchangeEnvelope $envelope, ProcessingException $exception, ProcessorInterface $processor)
{
$originalException = $exception->getOriginalException();
$errorDescription = $originalException ? $originalException->getMessage() : $exception->getMessage();
$envelope->setHeader(CallbackExchangeEnvelope::HEADER_CREATED_AT, round(microtime(true) * 1000));
$envelope->setHeader(CallbackExchangeEnvelope::HEADER_ERROR_MESSAGE, $errorDescription);
$envelope->setHeader(CallbackExchangeEnvelope::HEADER_ERROR_PROCESSOR_ID, $processor->getId());
$envelope->setHeader(CallbackExchangeEnvelope::HEADER_ERROR_PROCESSOR_DESCRIPTION, $processor->getDescription());
$envelope->setHeader(CallbackExchangeEnvelope::HEADER_STATUS_CODE, $originalException->getCode());
} | [
"private",
"function",
"addCallbackHeadersToEnvelope",
"(",
"CallbackExchangeEnvelope",
"$",
"envelope",
",",
"ProcessingException",
"$",
"exception",
",",
"ProcessorInterface",
"$",
"processor",
")",
"{",
"$",
"originalException",
"=",
"$",
"exception",
"->",
"getOrigi... | This method adds headers to the Envelope that we put the Callback exchange into, this is so that the
consumer of the has information to do deal with it.
- add the last error message and the time the error happened
- add information about the processor that was being used when the event occurred
@param CallbackExchangeEnvelope $envelope
@param ProcessingException $exception
@param ProcessorInterface $processor | [
"This",
"method",
"adds",
"headers",
"to",
"the",
"Envelope",
"that",
"we",
"put",
"the",
"Callback",
"exchange",
"into",
"this",
"is",
"so",
"that",
"the",
"consumer",
"of",
"the",
"has",
"information",
"to",
"do",
"deal",
"with",
"it",
"."
] | 5f0bf8ff86337a51f6d208bd38df39017643b905 | https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Core/Handlers/MessageHandler.php#L506-L516 | train |
smartboxgroup/integration-framework-bundle | Core/Handlers/MessageHandler.php | MessageHandler.handle | public function handle(MessageInterface $message, EndpointInterface $endpointFrom)
{
$retries = 0;
// If this is an exchange envelope, we extract the old exchange and prepare the new one
if ($message && $message instanceof ExchangeEnvelope) {
$oldExchange = $message->getBody();
$exchange = new Exchange($oldExchange->getIn(), $oldExchange->getItinerary(), $oldExchange->getHeaders());
if ($message instanceof RetryExchangeEnvelope) {
$retries = $message->getRetries();
$delaySinceLastRetry = round(microtime(true) * 1000) - $message->getHeader(RetryExchangeEnvelope::HEADER_LAST_RETRY_AT);
$retryDelay = $message->getHeader(RetryExchangeEnvelope::HEADER_RETRY_DELAY) * 1000;
$endpointURI = $message instanceof ThrottledExchangeEnvelope ? $this->throttleURI : $this->retryURI;
if ($delaySinceLastRetry < $retryDelay) {
$this->deferExchangeMessage($message, $endpointURI);
return;
}
}
}
// Otherwise create the exchange
else {
$exchange = $this->createExchangeForMessageFromURI($message, $endpointFrom->getURI());
}
$this->onHandleStart($exchange);
$result = $this->processExchange($exchange, $retries);
$this->onHandleSuccess($exchange);
return $result;
} | php | public function handle(MessageInterface $message, EndpointInterface $endpointFrom)
{
$retries = 0;
// If this is an exchange envelope, we extract the old exchange and prepare the new one
if ($message && $message instanceof ExchangeEnvelope) {
$oldExchange = $message->getBody();
$exchange = new Exchange($oldExchange->getIn(), $oldExchange->getItinerary(), $oldExchange->getHeaders());
if ($message instanceof RetryExchangeEnvelope) {
$retries = $message->getRetries();
$delaySinceLastRetry = round(microtime(true) * 1000) - $message->getHeader(RetryExchangeEnvelope::HEADER_LAST_RETRY_AT);
$retryDelay = $message->getHeader(RetryExchangeEnvelope::HEADER_RETRY_DELAY) * 1000;
$endpointURI = $message instanceof ThrottledExchangeEnvelope ? $this->throttleURI : $this->retryURI;
if ($delaySinceLastRetry < $retryDelay) {
$this->deferExchangeMessage($message, $endpointURI);
return;
}
}
}
// Otherwise create the exchange
else {
$exchange = $this->createExchangeForMessageFromURI($message, $endpointFrom->getURI());
}
$this->onHandleStart($exchange);
$result = $this->processExchange($exchange, $retries);
$this->onHandleSuccess($exchange);
return $result;
} | [
"public",
"function",
"handle",
"(",
"MessageInterface",
"$",
"message",
",",
"EndpointInterface",
"$",
"endpointFrom",
")",
"{",
"$",
"retries",
"=",
"0",
";",
"// If this is an exchange envelope, we extract the old exchange and prepare the new one",
"if",
"(",
"$",
"mes... | Handle a message.
If the message is a retryable message and the message is not ready to be processed yet, we will re-defer the message.
Otherwise process the message by putting it as part of an exchange, and processing the exchange.
{@inheritdoc} | [
"Handle",
"a",
"message",
"."
] | 5f0bf8ff86337a51f6d208bd38df39017643b905 | https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Core/Handlers/MessageHandler.php#L526-L557 | train |
smartboxgroup/integration-framework-bundle | Core/Handlers/MessageHandler.php | MessageHandler.deferExchangeMessage | public function deferExchangeMessage(ExchangeEnvelope $deferredExchange, $endpointURI = null)
{
$exchange = new Exchange($deferredExchange);
if (!$endpointURI) {
$oldExchange = $deferredExchange->getBody();
$endpointURI = $oldExchange->getHeader(Exchange::HEADER_FROM);
}
$endpoint = $this->getEndpointFactory()->createEndpoint($endpointURI, EndpointFactory::MODE_PRODUCE);
$endpoint->produce($exchange);
} | php | public function deferExchangeMessage(ExchangeEnvelope $deferredExchange, $endpointURI = null)
{
$exchange = new Exchange($deferredExchange);
if (!$endpointURI) {
$oldExchange = $deferredExchange->getBody();
$endpointURI = $oldExchange->getHeader(Exchange::HEADER_FROM);
}
$endpoint = $this->getEndpointFactory()->createEndpoint($endpointURI, EndpointFactory::MODE_PRODUCE);
$endpoint->produce($exchange);
} | [
"public",
"function",
"deferExchangeMessage",
"(",
"ExchangeEnvelope",
"$",
"deferredExchange",
",",
"$",
"endpointURI",
"=",
"null",
")",
"{",
"$",
"exchange",
"=",
"new",
"Exchange",
"(",
"$",
"deferredExchange",
")",
";",
"if",
"(",
"!",
"$",
"endpointURI",... | Defer and ExchangeEnvelope to an endpoint
If no endpoint is defined then look inside the envelope for the exchange and use original endpoint.
@param ExchangeEnvelope $deferredExchange
@param null $endpointURI | [
"Defer",
"and",
"ExchangeEnvelope",
"to",
"an",
"endpoint",
"If",
"no",
"endpoint",
"is",
"defined",
"then",
"look",
"inside",
"the",
"envelope",
"for",
"the",
"exchange",
"and",
"use",
"original",
"endpoint",
"."
] | 5f0bf8ff86337a51f6d208bd38df39017643b905 | https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Core/Handlers/MessageHandler.php#L656-L668 | train |
netgen/site-bundle | bundle/Controller/FullViewController.php | FullViewController.viewNgCategory | public function viewNgCategory(Request $request, ContentView $view, array $params = [])
{
$content = $view->getSiteContent();
$location = $view->getSiteLocation();
if (!$location instanceof Location) {
$location = $content->mainLocation;
}
$response = $this->checkCategoryRedirect($location);
if ($response instanceof Response) {
return $response;
}
$criteria = [
new Criterion\Subtree($location->pathString),
new Criterion\Visibility(Criterion\Visibility::VISIBLE),
new Criterion\LogicalNot(new Criterion\LocationId($location->id)),
];
if (!$content->getField('fetch_subtree')->value->bool) {
$criteria[] = new Criterion\Location\Depth(Criterion\Operator::EQ, $location->depth + 1);
}
if (!$content->getField('children_class_filter_include')->isEmpty()) {
$contentTypeFilter = $content->getField('children_class_filter_include')->value;
$criteria[] = new Criterion\ContentTypeIdentifier(
array_map(
'trim',
explode(',', $contentTypeFilter->text)
)
);
}
$query = new LocationQuery();
$query->filter = new Criterion\LogicalAnd($criteria);
$query->sortClauses = $location->innerLocation->getSortClauses();
$pager = new Pagerfanta(
new FilterAdapter(
$query,
$this->getSite()->getFilterService()
)
);
$pager->setNormalizeOutOfRangePages(true);
/** @var \eZ\Publish\Core\FieldType\Integer\Value $pageLimitValue */
$pageLimitValue = $content->getField('page_limit')->value;
$defaultLimit = 12;
$childrenLimit = (int) ($params['childrenLimit'] ?? $defaultLimit);
$childrenLimit = $childrenLimit > 0 ? $childrenLimit : $defaultLimit;
$pager->setMaxPerPage($pageLimitValue->value > 0 ? (int) $pageLimitValue->value : $childrenLimit);
$currentPage = (int) $request->get('page', 1);
$pager->setCurrentPage($currentPage > 0 ? $currentPage : 1);
$view->addParameters([
'pager' => $pager,
]);
return $view;
} | php | public function viewNgCategory(Request $request, ContentView $view, array $params = [])
{
$content = $view->getSiteContent();
$location = $view->getSiteLocation();
if (!$location instanceof Location) {
$location = $content->mainLocation;
}
$response = $this->checkCategoryRedirect($location);
if ($response instanceof Response) {
return $response;
}
$criteria = [
new Criterion\Subtree($location->pathString),
new Criterion\Visibility(Criterion\Visibility::VISIBLE),
new Criterion\LogicalNot(new Criterion\LocationId($location->id)),
];
if (!$content->getField('fetch_subtree')->value->bool) {
$criteria[] = new Criterion\Location\Depth(Criterion\Operator::EQ, $location->depth + 1);
}
if (!$content->getField('children_class_filter_include')->isEmpty()) {
$contentTypeFilter = $content->getField('children_class_filter_include')->value;
$criteria[] = new Criterion\ContentTypeIdentifier(
array_map(
'trim',
explode(',', $contentTypeFilter->text)
)
);
}
$query = new LocationQuery();
$query->filter = new Criterion\LogicalAnd($criteria);
$query->sortClauses = $location->innerLocation->getSortClauses();
$pager = new Pagerfanta(
new FilterAdapter(
$query,
$this->getSite()->getFilterService()
)
);
$pager->setNormalizeOutOfRangePages(true);
/** @var \eZ\Publish\Core\FieldType\Integer\Value $pageLimitValue */
$pageLimitValue = $content->getField('page_limit')->value;
$defaultLimit = 12;
$childrenLimit = (int) ($params['childrenLimit'] ?? $defaultLimit);
$childrenLimit = $childrenLimit > 0 ? $childrenLimit : $defaultLimit;
$pager->setMaxPerPage($pageLimitValue->value > 0 ? (int) $pageLimitValue->value : $childrenLimit);
$currentPage = (int) $request->get('page', 1);
$pager->setCurrentPage($currentPage > 0 ? $currentPage : 1);
$view->addParameters([
'pager' => $pager,
]);
return $view;
} | [
"public",
"function",
"viewNgCategory",
"(",
"Request",
"$",
"request",
",",
"ContentView",
"$",
"view",
",",
"array",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"content",
"=",
"$",
"view",
"->",
"getSiteContent",
"(",
")",
";",
"$",
"location",
"="... | Action for viewing content with ng_category content type identifier.
@return \Symfony\Component\HttpFoundation\Response|\Netgen\Bundle\EzPlatformSiteApiBundle\View\ContentView | [
"Action",
"for",
"viewing",
"content",
"with",
"ng_category",
"content",
"type",
"identifier",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Controller/FullViewController.php#L37-L101 | train |
netgen/site-bundle | bundle/Controller/FullViewController.php | FullViewController.viewNgLandingPage | public function viewNgLandingPage(ContentView $view)
{
$location = $view->getSiteLocation();
if (!$location instanceof Location) {
$location = $view->getSiteContent()->mainLocation;
}
$response = $this->checkCategoryRedirect($location);
if ($response instanceof Response) {
return $response;
}
return $view;
} | php | public function viewNgLandingPage(ContentView $view)
{
$location = $view->getSiteLocation();
if (!$location instanceof Location) {
$location = $view->getSiteContent()->mainLocation;
}
$response = $this->checkCategoryRedirect($location);
if ($response instanceof Response) {
return $response;
}
return $view;
} | [
"public",
"function",
"viewNgLandingPage",
"(",
"ContentView",
"$",
"view",
")",
"{",
"$",
"location",
"=",
"$",
"view",
"->",
"getSiteLocation",
"(",
")",
";",
"if",
"(",
"!",
"$",
"location",
"instanceof",
"Location",
")",
"{",
"$",
"location",
"=",
"$... | Action for viewing content with ng_landing_page content type identifier.
@return \Symfony\Component\HttpFoundation\Response|\Netgen\Bundle\EzPlatformSiteApiBundle\View\ContentView | [
"Action",
"for",
"viewing",
"content",
"with",
"ng_landing_page",
"content",
"type",
"identifier",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Controller/FullViewController.php#L108-L121 | train |
netgen/site-bundle | bundle/Controller/FullViewController.php | FullViewController.checkCategoryRedirect | protected function checkCategoryRedirect(Location $location): ?RedirectResponse
{
$content = $location->content;
$internalRedirectContent = null;
if (!$content->getField('internal_redirect')->isEmpty()) {
$internalRedirectContent = $content->getFieldRelation('internal_redirect');
}
$externalRedirectValue = $content->getField('external_redirect')->value;
if ($internalRedirectContent instanceof Content) {
if ($internalRedirectContent->contentInfo->mainLocationId !== $location->id) {
return new RedirectResponse(
$this->router->generate($internalRedirectContent),
RedirectResponse::HTTP_MOVED_PERMANENTLY
);
}
} elseif ($externalRedirectValue instanceof UrlValue && !$content->getField('external_redirect')->isEmpty()) {
if (mb_stripos($externalRedirectValue->link, 'http') === 0) {
return new RedirectResponse($externalRedirectValue->link, RedirectResponse::HTTP_MOVED_PERMANENTLY);
}
return new RedirectResponse(
$this->router->generate($this->getRootLocation()) . trim($externalRedirectValue->link, '/'),
RedirectResponse::HTTP_MOVED_PERMANENTLY
);
}
return null;
} | php | protected function checkCategoryRedirect(Location $location): ?RedirectResponse
{
$content = $location->content;
$internalRedirectContent = null;
if (!$content->getField('internal_redirect')->isEmpty()) {
$internalRedirectContent = $content->getFieldRelation('internal_redirect');
}
$externalRedirectValue = $content->getField('external_redirect')->value;
if ($internalRedirectContent instanceof Content) {
if ($internalRedirectContent->contentInfo->mainLocationId !== $location->id) {
return new RedirectResponse(
$this->router->generate($internalRedirectContent),
RedirectResponse::HTTP_MOVED_PERMANENTLY
);
}
} elseif ($externalRedirectValue instanceof UrlValue && !$content->getField('external_redirect')->isEmpty()) {
if (mb_stripos($externalRedirectValue->link, 'http') === 0) {
return new RedirectResponse($externalRedirectValue->link, RedirectResponse::HTTP_MOVED_PERMANENTLY);
}
return new RedirectResponse(
$this->router->generate($this->getRootLocation()) . trim($externalRedirectValue->link, '/'),
RedirectResponse::HTTP_MOVED_PERMANENTLY
);
}
return null;
} | [
"protected",
"function",
"checkCategoryRedirect",
"(",
"Location",
"$",
"location",
")",
":",
"?",
"RedirectResponse",
"{",
"$",
"content",
"=",
"$",
"location",
"->",
"content",
";",
"$",
"internalRedirectContent",
"=",
"null",
";",
"if",
"(",
"!",
"$",
"co... | Checks if content at location defined by it's ID contains
valid category redirect value and returns a redirect response if it does. | [
"Checks",
"if",
"content",
"at",
"location",
"defined",
"by",
"it",
"s",
"ID",
"contains",
"valid",
"category",
"redirect",
"value",
"and",
"returns",
"a",
"redirect",
"response",
"if",
"it",
"does",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Controller/FullViewController.php#L127-L157 | train |
alaxos/cakephp3-libs | src/Controller/JavascriptsController.php | JavascriptsController.antispam | function antispam()
{
$this->layout = false;
$form_dom_id = $this->getRequest()->getQuery('fid');
$model_name = $this->getRequest()->getQuery('model_name');
$token = $this->getRequest()->getQuery('token');
$today_fieldname = $this->SpamFilter->get_today_fieldname();
$today_token = $this->SpamFilter->get_today_token();
$yesterday_token = $this->SpamFilter->get_yesterday_token();
if($token == $today_token || $token == $yesterday_token)
{
$this->set(compact('form_dom_id', 'model_name', 'today_fieldname'));
}
else
{
throw new NotFoundException();
}
} | php | function antispam()
{
$this->layout = false;
$form_dom_id = $this->getRequest()->getQuery('fid');
$model_name = $this->getRequest()->getQuery('model_name');
$token = $this->getRequest()->getQuery('token');
$today_fieldname = $this->SpamFilter->get_today_fieldname();
$today_token = $this->SpamFilter->get_today_token();
$yesterday_token = $this->SpamFilter->get_yesterday_token();
if($token == $today_token || $token == $yesterday_token)
{
$this->set(compact('form_dom_id', 'model_name', 'today_fieldname'));
}
else
{
throw new NotFoundException();
}
} | [
"function",
"antispam",
"(",
")",
"{",
"$",
"this",
"->",
"layout",
"=",
"false",
";",
"$",
"form_dom_id",
"=",
"$",
"this",
"->",
"getRequest",
"(",
")",
"->",
"getQuery",
"(",
"'fid'",
")",
";",
"$",
"model_name",
"=",
"$",
"this",
"->",
"getReques... | Return a JS that will complete an HTML form with a hidden field that changes every day | [
"Return",
"a",
"JS",
"that",
"will",
"complete",
"an",
"HTML",
"form",
"with",
"a",
"hidden",
"field",
"that",
"changes",
"every",
"day"
] | 685e9f17a3fbe3550c59a03a65c4d75df763e804 | https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Controller/JavascriptsController.php#L25-L45 | train |
smartboxgroup/integration-framework-bundle | Core/Processors/Processor.php | Processor.createProcessEvent | final protected function createProcessEvent(Exchange $exchange, SerializableArray $processingContext, $type)
{
$event = new ProcessEvent($type);
$event->setId(uniqid('', true));
$event->setTimestampToCurrent();
$event->setProcessor($this);
$event->setExchange($exchange);
$event->setProcessingContext($processingContext);
return $event;
} | php | final protected function createProcessEvent(Exchange $exchange, SerializableArray $processingContext, $type)
{
$event = new ProcessEvent($type);
$event->setId(uniqid('', true));
$event->setTimestampToCurrent();
$event->setProcessor($this);
$event->setExchange($exchange);
$event->setProcessingContext($processingContext);
return $event;
} | [
"final",
"protected",
"function",
"createProcessEvent",
"(",
"Exchange",
"$",
"exchange",
",",
"SerializableArray",
"$",
"processingContext",
",",
"$",
"type",
")",
"{",
"$",
"event",
"=",
"new",
"ProcessEvent",
"(",
"$",
"type",
")",
";",
"$",
"event",
"->"... | Method to create a process event.
@param Exchange $exchange
@param SerializableArray $processingContext
@param string $type Event type
@return ProcessEvent | [
"Method",
"to",
"create",
"a",
"process",
"event",
"."
] | 5f0bf8ff86337a51f6d208bd38df39017643b905 | https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Core/Processors/Processor.php#L98-L108 | train |
Atnic/laravel-generator | app/Console/Commands/ControllerApiMakeCommand.php | ControllerApiMakeCommand.getRoutePath | protected function getRoutePath($name)
{
$routeName = str_replace_first('api.', '', $this->getRouteName($name));
$routeNameExploded = explode('.', $routeName);
$routePath = str_replace('.', '/', $routeName);
if ($this->option('parent') && count($routeNameExploded) >= 2) {
$routePath = str_replace_last('/', '.', $routePath);
}
return $routePath;
} | php | protected function getRoutePath($name)
{
$routeName = str_replace_first('api.', '', $this->getRouteName($name));
$routeNameExploded = explode('.', $routeName);
$routePath = str_replace('.', '/', $routeName);
if ($this->option('parent') && count($routeNameExploded) >= 2) {
$routePath = str_replace_last('/', '.', $routePath);
}
return $routePath;
} | [
"protected",
"function",
"getRoutePath",
"(",
"$",
"name",
")",
"{",
"$",
"routeName",
"=",
"str_replace_first",
"(",
"'api.'",
",",
"''",
",",
"$",
"this",
"->",
"getRouteName",
"(",
"$",
"name",
")",
")",
";",
"$",
"routeNameExploded",
"=",
"explode",
... | Get the route path.
@param string $name
@return string | [
"Get",
"the",
"route",
"path",
"."
] | 7bf53837a61af566b389255784dbbf1789020018 | https://github.com/Atnic/laravel-generator/blob/7bf53837a61af566b389255784dbbf1789020018/app/Console/Commands/ControllerApiMakeCommand.php#L316-L325 | train |
netgen/site-bundle | bundle/DependencyInjection/Compiler/AsseticPass.php | AsseticPass.process | public function process(ContainerBuilder $container): void
{
if (!$container->has('assetic.twig_formula_loader.real')) {
return;
}
$container
->findDefinition('assetic.twig_formula_loader.real')
->replaceArgument(1, null);
} | php | public function process(ContainerBuilder $container): void
{
if (!$container->has('assetic.twig_formula_loader.real')) {
return;
}
$container
->findDefinition('assetic.twig_formula_loader.real')
->replaceArgument(1, null);
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
":",
"void",
"{",
"if",
"(",
"!",
"$",
"container",
"->",
"has",
"(",
"'assetic.twig_formula_loader.real'",
")",
")",
"{",
"return",
";",
"}",
"$",
"container",
"->",
"findDefin... | Removes the logging of template errors to console stdout in Assetic. | [
"Removes",
"the",
"logging",
"of",
"template",
"errors",
"to",
"console",
"stdout",
"in",
"Assetic",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/DependencyInjection/Compiler/AsseticPass.php#L15-L24 | train |
MacFJA/phpqa-extensions | src/ToolInstaller.php | ToolInstaller.install | public function install($class)
{
if (!in_array(ToolDefinition::class, class_implements($class), true)) {
throw new \InvalidArgumentException;
}
$this->runComposer(call_user_func([$class, 'getComposer']));
$this->updatePhpQaConfig(
call_user_func([$class, 'getCliName']),
$class,
call_user_func([$class, 'getReportName'])
);
} | php | public function install($class)
{
if (!in_array(ToolDefinition::class, class_implements($class), true)) {
throw new \InvalidArgumentException;
}
$this->runComposer(call_user_func([$class, 'getComposer']));
$this->updatePhpQaConfig(
call_user_func([$class, 'getCliName']),
$class,
call_user_func([$class, 'getReportName'])
);
} | [
"public",
"function",
"install",
"(",
"$",
"class",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"ToolDefinition",
"::",
"class",
",",
"class_implements",
"(",
"$",
"class",
")",
",",
"true",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
... | Install a tool.
Read all needed information from the Tools\Analyser class and run composer
@param string $class The Tools\Analyser class name | [
"Install",
"a",
"tool",
"."
] | f2193aa80fb8e0025a261975be0d4c525180fc88 | https://github.com/MacFJA/phpqa-extensions/blob/f2193aa80fb8e0025a261975be0d4c525180fc88/src/ToolInstaller.php#L22-L34 | train |
Atnic/laravel-generator | app/Console/Commands/ModelMakeCommand.php | ModelMakeCommand.createFilter | protected function createFilter()
{
$model = Str::studly(class_basename($this->argument('name')));
$this->call('make:filter', [
'name' => $model.'Filter',
]);
} | php | protected function createFilter()
{
$model = Str::studly(class_basename($this->argument('name')));
$this->call('make:filter', [
'name' => $model.'Filter',
]);
} | [
"protected",
"function",
"createFilter",
"(",
")",
"{",
"$",
"model",
"=",
"Str",
"::",
"studly",
"(",
"class_basename",
"(",
"$",
"this",
"->",
"argument",
"(",
"'name'",
")",
")",
")",
";",
"$",
"this",
"->",
"call",
"(",
"'make:filter'",
",",
"[",
... | Create a filter for the model.
@return void | [
"Create",
"a",
"filter",
"for",
"the",
"model",
"."
] | 7bf53837a61af566b389255784dbbf1789020018 | https://github.com/Atnic/laravel-generator/blob/7bf53837a61af566b389255784dbbf1789020018/app/Console/Commands/ModelMakeCommand.php#L34-L41 | train |
Atnic/laravel-generator | app/Console/Commands/ModelMakeCommand.php | ModelMakeCommand.generateTranslation | protected function generateTranslation()
{
$name = $this->qualifyClass($this->getNameInput());
$path = $this->getTranslationPath($name);
$this->makeDirectory($path);
$this->files->put($path, $this->buildTranslation($name));
$this->info('Translation also generated successfully.');
$this->warn($path);
} | php | protected function generateTranslation()
{
$name = $this->qualifyClass($this->getNameInput());
$path = $this->getTranslationPath($name);
$this->makeDirectory($path);
$this->files->put($path, $this->buildTranslation($name));
$this->info('Translation also generated successfully.');
$this->warn($path);
} | [
"protected",
"function",
"generateTranslation",
"(",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"qualifyClass",
"(",
"$",
"this",
"->",
"getNameInput",
"(",
")",
")",
";",
"$",
"path",
"=",
"$",
"this",
"->",
"getTranslationPath",
"(",
"$",
"name",
... | Generate Translation File
@return void
@throws \Illuminate\Contracts\Filesystem\FileNotFoundException | [
"Generate",
"Translation",
"File"
] | 7bf53837a61af566b389255784dbbf1789020018 | https://github.com/Atnic/laravel-generator/blob/7bf53837a61af566b389255784dbbf1789020018/app/Console/Commands/ModelMakeCommand.php#L89-L99 | train |
netgen/site-bundle | bundle/Routing/SiteContentUrlAliasRouter.php | SiteContentUrlAliasRouter.generate | public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH): string
{
if (!$name instanceof Content && !$name instanceof ContentInfo) {
throw new RouteNotFoundException('Could not match route');
}
if (empty($name->mainLocationId)) {
throw new LogicException('Cannot generate an UrlAlias route for content without main location.');
}
return $this->generator->generate(
$name->mainLocation->innerLocation,
$parameters,
$referenceType
);
} | php | public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH): string
{
if (!$name instanceof Content && !$name instanceof ContentInfo) {
throw new RouteNotFoundException('Could not match route');
}
if (empty($name->mainLocationId)) {
throw new LogicException('Cannot generate an UrlAlias route for content without main location.');
}
return $this->generator->generate(
$name->mainLocation->innerLocation,
$parameters,
$referenceType
);
} | [
"public",
"function",
"generate",
"(",
"$",
"name",
",",
"$",
"parameters",
"=",
"[",
"]",
",",
"$",
"referenceType",
"=",
"self",
"::",
"ABSOLUTE_PATH",
")",
":",
"string",
"{",
"if",
"(",
"!",
"$",
"name",
"instanceof",
"Content",
"&&",
"!",
"$",
"... | Generates a URL for Site API Content object or ContentInfo object, from the given parameters.
@param mixed $name
@param mixed $parameters
@param mixed $referenceType | [
"Generates",
"a",
"URL",
"for",
"Site",
"API",
"Content",
"object",
"or",
"ContentInfo",
"object",
"from",
"the",
"given",
"parameters",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Routing/SiteContentUrlAliasRouter.php#L52-L67 | train |
spiral/router | src/Route.php | Route.withContainer | public function withContainer(ContainerInterface $container): ContainerizedInterface
{
$route = clone $this;
$route->container = $container;
if ($route->target instanceof TargetInterface) {
$route->target = clone $route->target;
}
$route->pipeline = $route->makePipeline();
return $route;
} | php | public function withContainer(ContainerInterface $container): ContainerizedInterface
{
$route = clone $this;
$route->container = $container;
if ($route->target instanceof TargetInterface) {
$route->target = clone $route->target;
}
$route->pipeline = $route->makePipeline();
return $route;
} | [
"public",
"function",
"withContainer",
"(",
"ContainerInterface",
"$",
"container",
")",
":",
"ContainerizedInterface",
"{",
"$",
"route",
"=",
"clone",
"$",
"this",
";",
"$",
"route",
"->",
"container",
"=",
"$",
"container",
";",
"if",
"(",
"$",
"route",
... | Associated route with given container.
@param ContainerInterface $container
@return ContainerizedInterface|$this | [
"Associated",
"route",
"with",
"given",
"container",
"."
] | 35721d06231d5650402eb93ac7f3ade00cd1b640 | https://github.com/spiral/router/blob/35721d06231d5650402eb93ac7f3ade00cd1b640/src/Route.php#L76-L87 | train |
nilportugues/php-api-transformer | src/Transformer/Helpers/RecursiveFilterHelper.php | RecursiveFilterHelper.deletePropertiesNotInFilter | public static function deletePropertiesNotInFilter(array &$mappings, array &$array, string $typeKey)
{
if (\array_key_exists(Serializer::CLASS_IDENTIFIER_KEY, $array)) {
$newArray = [];
$type = $array[Serializer::CLASS_IDENTIFIER_KEY];
self::deleteMatchedClassNotInFilterProperties($mappings, $array, $typeKey, $type, $newArray);
if (!empty($newArray)) {
$array = $newArray;
}
}
} | php | public static function deletePropertiesNotInFilter(array &$mappings, array &$array, string $typeKey)
{
if (\array_key_exists(Serializer::CLASS_IDENTIFIER_KEY, $array)) {
$newArray = [];
$type = $array[Serializer::CLASS_IDENTIFIER_KEY];
self::deleteMatchedClassNotInFilterProperties($mappings, $array, $typeKey, $type, $newArray);
if (!empty($newArray)) {
$array = $newArray;
}
}
} | [
"public",
"static",
"function",
"deletePropertiesNotInFilter",
"(",
"array",
"&",
"$",
"mappings",
",",
"array",
"&",
"$",
"array",
",",
"string",
"$",
"typeKey",
")",
"{",
"if",
"(",
"\\",
"array_key_exists",
"(",
"Serializer",
"::",
"CLASS_IDENTIFIER_KEY",
"... | Delete all keys except the ones considered identifier keys or defined in the filter.
@param \NilPortugues\Api\Mapping\Mapping[] $mappings
@param array $array
@param string $typeKey | [
"Delete",
"all",
"keys",
"except",
"the",
"ones",
"considered",
"identifier",
"keys",
"or",
"defined",
"in",
"the",
"filter",
"."
] | a9f20fbe1580d98e3d462a0ebe13fb7595cbd683 | https://github.com/nilportugues/php-api-transformer/blob/a9f20fbe1580d98e3d462a0ebe13fb7595cbd683/src/Transformer/Helpers/RecursiveFilterHelper.php#L25-L37 | train |
smartboxgroup/integration-framework-bundle | Components/DB/NoSQL/Drivers/MongoDB/MongoDBDateHandler.php | MongoDBDateHandler.convertFromMongoFormatToDateTime | public function convertFromMongoFormatToDateTime(VisitorInterface $visitor, $date, array $type, Context $context)
{
/**
* this $dateTime object is incorrect in case of using microseconds
* because after conversion of \MongoDB\BSON\UTCDateTime to \DateTime
* method $dateTime->format('U.u') returns invalid string xxxxxxxxx.zzzzzzzzz
* part after "." contains 9 digits but it should contain up to 6 digits
* so we have to reduce this part to 6 digits.
*
* @var \DateTime
*/
if (!is_string($date) && !$date instanceof UTCDatetime) {
throw new \InvalidArgumentException('The provided date must be a valid string or an instance of UTCDateTime');
}
if (is_string($date)) {
$dateTime = date_create($date);
if (false === $dateTime) {
throw new \InvalidArgumentException(sprintf('The provided date "%s" is not a valid date/time string', $date));
}
return $dateTime;
}
return self::convertMongoFormatToDateTime($date);
} | php | public function convertFromMongoFormatToDateTime(VisitorInterface $visitor, $date, array $type, Context $context)
{
/**
* this $dateTime object is incorrect in case of using microseconds
* because after conversion of \MongoDB\BSON\UTCDateTime to \DateTime
* method $dateTime->format('U.u') returns invalid string xxxxxxxxx.zzzzzzzzz
* part after "." contains 9 digits but it should contain up to 6 digits
* so we have to reduce this part to 6 digits.
*
* @var \DateTime
*/
if (!is_string($date) && !$date instanceof UTCDatetime) {
throw new \InvalidArgumentException('The provided date must be a valid string or an instance of UTCDateTime');
}
if (is_string($date)) {
$dateTime = date_create($date);
if (false === $dateTime) {
throw new \InvalidArgumentException(sprintf('The provided date "%s" is not a valid date/time string', $date));
}
return $dateTime;
}
return self::convertMongoFormatToDateTime($date);
} | [
"public",
"function",
"convertFromMongoFormatToDateTime",
"(",
"VisitorInterface",
"$",
"visitor",
",",
"$",
"date",
",",
"array",
"$",
"type",
",",
"Context",
"$",
"context",
")",
"{",
"/**\n * this $dateTime object is incorrect in case of using microseconds\n ... | Method converts \MongoDB\BSON\UTCDateTime to \DateTime.
@param VisitorInterface $visitor
@param UTCDatetime $date
@param array $type
@param Context $context
@return \DateTime | [
"Method",
"converts",
"\\",
"MongoDB",
"\\",
"BSON",
"\\",
"UTCDateTime",
"to",
"\\",
"DateTime",
"."
] | 5f0bf8ff86337a51f6d208bd38df39017643b905 | https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Components/DB/NoSQL/Drivers/MongoDB/MongoDBDateHandler.php#L58-L83 | train |
smartboxgroup/integration-framework-bundle | Components/DB/NoSQL/Drivers/MongoDB/MongoDBDateHandler.php | MongoDBDateHandler.convertMongoFormatToDateTime | public static function convertMongoFormatToDateTime(UTCDatetime $date)
{
/**
* this $dateTime object is incorrect in case of using microseconds
* because after conversion of \MongoDB\BSON\UTCDateTime to \DateTime
* method $dateTime->format('U.u') returns invalid string xxxxxxxxx.zzzzzzzzz
* part after "." contains 9 digits but it should contain up to 6 digits
* so we have to reduce this part to 6 digits.
*
* @var \DateTime
*/
$dateTime = $date->toDateTime();
$seconds = $dateTime->format('U');
$microseconds = substr($dateTime->format('u'), 0, 5); // we allow max 6 digits
$fixedDateTime = DateTimeHelper::createDateTimeFromTimestampWithMilliseconds(sprintf('%s.%s', $seconds, $microseconds));
return $fixedDateTime;
} | php | public static function convertMongoFormatToDateTime(UTCDatetime $date)
{
/**
* this $dateTime object is incorrect in case of using microseconds
* because after conversion of \MongoDB\BSON\UTCDateTime to \DateTime
* method $dateTime->format('U.u') returns invalid string xxxxxxxxx.zzzzzzzzz
* part after "." contains 9 digits but it should contain up to 6 digits
* so we have to reduce this part to 6 digits.
*
* @var \DateTime
*/
$dateTime = $date->toDateTime();
$seconds = $dateTime->format('U');
$microseconds = substr($dateTime->format('u'), 0, 5); // we allow max 6 digits
$fixedDateTime = DateTimeHelper::createDateTimeFromTimestampWithMilliseconds(sprintf('%s.%s', $seconds, $microseconds));
return $fixedDateTime;
} | [
"public",
"static",
"function",
"convertMongoFormatToDateTime",
"(",
"UTCDatetime",
"$",
"date",
")",
"{",
"/**\n * this $dateTime object is incorrect in case of using microseconds\n * because after conversion of \\MongoDB\\BSON\\UTCDateTime to \\DateTime\n * method $date... | Method converts \MongoDB\BSON\UTCDateTime to \DateTime preserving milliseconds.
@param UTCDatetime $date
@return \DateTime | [
"Method",
"converts",
"\\",
"MongoDB",
"\\",
"BSON",
"\\",
"UTCDateTime",
"to",
"\\",
"DateTime",
"preserving",
"milliseconds",
"."
] | 5f0bf8ff86337a51f6d208bd38df39017643b905 | https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Components/DB/NoSQL/Drivers/MongoDB/MongoDBDateHandler.php#L92-L110 | train |
cedx/coveralls.php | lib/GitRemote.php | GitRemote.fromJson | static function fromJson(object $map): self {
return new static(
isset($map->name) && is_string($map->name) ? $map->name : '',
isset($map->url) && is_string($map->url) ? $map->url : null
);
} | php | static function fromJson(object $map): self {
return new static(
isset($map->name) && is_string($map->name) ? $map->name : '',
isset($map->url) && is_string($map->url) ? $map->url : null
);
} | [
"static",
"function",
"fromJson",
"(",
"object",
"$",
"map",
")",
":",
"self",
"{",
"return",
"new",
"static",
"(",
"isset",
"(",
"$",
"map",
"->",
"name",
")",
"&&",
"is_string",
"(",
"$",
"map",
"->",
"name",
")",
"?",
"$",
"map",
"->",
"name",
... | Creates a new remote repository from the specified JSON map.
@param object $map A JSON map representing a remote repository.
@return static The instance corresponding to the specified JSON map. | [
"Creates",
"a",
"new",
"remote",
"repository",
"from",
"the",
"specified",
"JSON",
"map",
"."
] | c196de0f92e06d5143ba90ebab18c8e384316cc0 | https://github.com/cedx/coveralls.php/blob/c196de0f92e06d5143ba90ebab18c8e384316cc0/lib/GitRemote.php#L32-L37 | train |
IconoCoders/otp-simple-sdk | Source/SimpleBackRef.php | SimpleBackRef.createRequestUri | protected function createRequestUri()
{
if ($this->protocol == '') {
$this->protocol = "http";
}
$this->request = $this->protocol . '://' . $this->serverData['HTTP_HOST'] . $this->serverData['REQUEST_URI'];
$this->debugMessage[] = 'REQUEST: ' . $this->request;
} | php | protected function createRequestUri()
{
if ($this->protocol == '') {
$this->protocol = "http";
}
$this->request = $this->protocol . '://' . $this->serverData['HTTP_HOST'] . $this->serverData['REQUEST_URI'];
$this->debugMessage[] = 'REQUEST: ' . $this->request;
} | [
"protected",
"function",
"createRequestUri",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"protocol",
"==",
"''",
")",
"{",
"$",
"this",
"->",
"protocol",
"=",
"\"http\"",
";",
"}",
"$",
"this",
"->",
"request",
"=",
"$",
"this",
"->",
"protocol",
".... | Creates request URI from HTTP SERVER VARS.
Handles http and https
@return void | [
"Creates",
"request",
"URI",
"from",
"HTTP",
"SERVER",
"VARS",
".",
"Handles",
"http",
"and",
"https"
] | d2808bf52e8d34be69414b444a00f1a9c8564930 | https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleBackRef.php#L111-L118 | train |
IconoCoders/otp-simple-sdk | Source/SimpleBackRef.php | SimpleBackRef.checkCtrl | protected function checkCtrl()
{
$requestURL = substr($this->request, 0, -38); //the last 38 characters are the CTRL param
$hashInput = strlen($requestURL) . $requestURL;
$this->debugMessage[] = 'REQUEST URL: ' . $requestURL;
$this->debugMessage[] = 'GET ctrl: ' . @$this->getData['ctrl'];
$this->debugMessage[] = 'Calculated ctrl: ' . $this->hmac($this->secretKey, $hashInput);
if (isset($this->getData['ctrl']) && $this->getData['ctrl'] == $this->hmac($this->secretKey, $hashInput)) {
return true;
}
$this->errorMessage[] = 'HASH: Calculated hash is not valid!';
$this->errorMessage[] = 'BACKREF ERROR: ' . @$this->getData['err'];
return false;
} | php | protected function checkCtrl()
{
$requestURL = substr($this->request, 0, -38); //the last 38 characters are the CTRL param
$hashInput = strlen($requestURL) . $requestURL;
$this->debugMessage[] = 'REQUEST URL: ' . $requestURL;
$this->debugMessage[] = 'GET ctrl: ' . @$this->getData['ctrl'];
$this->debugMessage[] = 'Calculated ctrl: ' . $this->hmac($this->secretKey, $hashInput);
if (isset($this->getData['ctrl']) && $this->getData['ctrl'] == $this->hmac($this->secretKey, $hashInput)) {
return true;
}
$this->errorMessage[] = 'HASH: Calculated hash is not valid!';
$this->errorMessage[] = 'BACKREF ERROR: ' . @$this->getData['err'];
return false;
} | [
"protected",
"function",
"checkCtrl",
"(",
")",
"{",
"$",
"requestURL",
"=",
"substr",
"(",
"$",
"this",
"->",
"request",
",",
"0",
",",
"-",
"38",
")",
";",
"//the last 38 characters are the CTRL param",
"$",
"hashInput",
"=",
"strlen",
"(",
"$",
"requestUR... | Validates CTRL variable
@return boolean | [
"Validates",
"CTRL",
"variable"
] | d2808bf52e8d34be69414b444a00f1a9c8564930 | https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleBackRef.php#L126-L139 | train |
IconoCoders/otp-simple-sdk | Source/SimpleBackRef.php | SimpleBackRef.checkResponse | public function checkResponse()
{
if (!isset($this->order_ref)) {
$this->errorMessage[] = 'CHECK RESPONSE: Missing order_ref variable!';
return false;
}
$this->logFunc("BackRef", $this->getData, $this->order_ref);
if (!$this->checkCtrl()) {
$this->errorMessage[] = 'CHECK RESPONSE: INVALID CTRL!';
return false;
}
$ios = new SimpleIos($this->iosConfig, $this->getData['order_currency'], $this->order_ref);
foreach ($ios->errorMessage as $msg) {
$this->errorMessage[] = $msg;
}
foreach ($ios->debugMessage as $msg) {
$this->debugMessage[] = $msg;
}
if (is_object($ios)) {
$this->checkIOSStatus($ios);
}
$this->logFunc("BackRef_BackStatus", $this->backStatusArray, $this->order_ref);
if (!$this->checkRtVariable($ios)) {
return false;
}
if (!$this->backStatusArray['RESULT']) {
return false;
}
return true;
} | php | public function checkResponse()
{
if (!isset($this->order_ref)) {
$this->errorMessage[] = 'CHECK RESPONSE: Missing order_ref variable!';
return false;
}
$this->logFunc("BackRef", $this->getData, $this->order_ref);
if (!$this->checkCtrl()) {
$this->errorMessage[] = 'CHECK RESPONSE: INVALID CTRL!';
return false;
}
$ios = new SimpleIos($this->iosConfig, $this->getData['order_currency'], $this->order_ref);
foreach ($ios->errorMessage as $msg) {
$this->errorMessage[] = $msg;
}
foreach ($ios->debugMessage as $msg) {
$this->debugMessage[] = $msg;
}
if (is_object($ios)) {
$this->checkIOSStatus($ios);
}
$this->logFunc("BackRef_BackStatus", $this->backStatusArray, $this->order_ref);
if (!$this->checkRtVariable($ios)) {
return false;
}
if (!$this->backStatusArray['RESULT']) {
return false;
}
return true;
} | [
"public",
"function",
"checkResponse",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"order_ref",
")",
")",
"{",
"$",
"this",
"->",
"errorMessage",
"[",
"]",
"=",
"'CHECK RESPONSE: Missing order_ref variable!'",
";",
"return",
"false",
";",... | Check card authorization response
1. check ctrl
2. check RC & RT
3. check IOS status
@return boolean | [
"Check",
"card",
"authorization",
"response"
] | d2808bf52e8d34be69414b444a00f1a9c8564930 | https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleBackRef.php#L151-L184 | train |
IconoCoders/otp-simple-sdk | Source/SimpleBackRef.php | SimpleBackRef.checkIOSStatus | protected function checkIOSStatus($ios)
{
$this->backStatusArray['ORDER_STATUS'] = (isset($ios->status['ORDER_STATUS'])) ? $ios->status['ORDER_STATUS'] : 'IOS_ERROR';
$this->backStatusArray['PAYMETHOD'] = (isset($ios->status['PAYMETHOD'])) ? $ios->status['PAYMETHOD'] : 'N/A';
if (in_array(trim($ios->status['ORDER_STATUS']), $this->successfulStatus)) {
$this->backStatusArray['RESULT'] = true;
} elseif (in_array(trim($ios->status['ORDER_STATUS']), $this->unsuccessfulStatus)) {
$this->backStatusArray['RESULT'] = false;
$this->errorMessage[] = 'IOS STATUS: UNSUCCESSFUL!';
}
} | php | protected function checkIOSStatus($ios)
{
$this->backStatusArray['ORDER_STATUS'] = (isset($ios->status['ORDER_STATUS'])) ? $ios->status['ORDER_STATUS'] : 'IOS_ERROR';
$this->backStatusArray['PAYMETHOD'] = (isset($ios->status['PAYMETHOD'])) ? $ios->status['PAYMETHOD'] : 'N/A';
if (in_array(trim($ios->status['ORDER_STATUS']), $this->successfulStatus)) {
$this->backStatusArray['RESULT'] = true;
} elseif (in_array(trim($ios->status['ORDER_STATUS']), $this->unsuccessfulStatus)) {
$this->backStatusArray['RESULT'] = false;
$this->errorMessage[] = 'IOS STATUS: UNSUCCESSFUL!';
}
} | [
"protected",
"function",
"checkIOSStatus",
"(",
"$",
"ios",
")",
"{",
"$",
"this",
"->",
"backStatusArray",
"[",
"'ORDER_STATUS'",
"]",
"=",
"(",
"isset",
"(",
"$",
"ios",
"->",
"status",
"[",
"'ORDER_STATUS'",
"]",
")",
")",
"?",
"$",
"ios",
"->",
"st... | Check IOS result
@param obj $ios Result of IOS comunication
@return boolean | [
"Check",
"IOS",
"result"
] | d2808bf52e8d34be69414b444a00f1a9c8564930 | https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleBackRef.php#L194-L204 | train |
IconoCoders/otp-simple-sdk | Source/SimpleBackRef.php | SimpleBackRef.checkRtVariable | protected function checkRtVariable($ios)
{
$successCode = array("000", "001");
if (isset($this->getData['RT'])) {
$returnCode = substr($this->getData['RT'], 0, 3);
//000 and 001 are successful
if (in_array($returnCode, $successCode)) {
$this->backStatusArray['RESULT'] = true;
$this->debugMessage[] = 'Return code: ' . $returnCode;
return true;
//all other unsuccessful
} elseif ($this->getData['RT'] != "" && !in_array($returnCode, $successCode)) {
$this->backStatusArray['RESULT'] = false;
$this->errorMessage[] = 'Return code: ' . $returnCode;
return false;
//in case of WIRE we have no bank return code and return text value, so RT has to be empty
} elseif ($this->getData['RT'] == "") {
//check IOS ORDER_STATUS
if (in_array(trim($ios->status['ORDER_STATUS']), $this->successfulStatus)) {
$this->backStatusArray['RESULT'] = true;
return true;
}
$this->backStatusArray['RESULT'] = false;
$this->errorMessage[] = 'Empty RT and status is: ' . $ios->status['ORDER_STATUS'];
return false;
}
$this->backStatusArray['RESULT'] = false;
$this->errorMessage[] = 'RT content: failure!';
return false;
} elseif (!isset($this->getData['RT'])) {
$this->backStatusArray['RESULT'] = false;
$this->errorMessage[] = 'Missing variable: (RT)!';
return false;
}
$this->backStatusArray['RESULT'] = false;
$this->errorMessage[] = 'checkRtVariable: general error!';
return false;
} | php | protected function checkRtVariable($ios)
{
$successCode = array("000", "001");
if (isset($this->getData['RT'])) {
$returnCode = substr($this->getData['RT'], 0, 3);
//000 and 001 are successful
if (in_array($returnCode, $successCode)) {
$this->backStatusArray['RESULT'] = true;
$this->debugMessage[] = 'Return code: ' . $returnCode;
return true;
//all other unsuccessful
} elseif ($this->getData['RT'] != "" && !in_array($returnCode, $successCode)) {
$this->backStatusArray['RESULT'] = false;
$this->errorMessage[] = 'Return code: ' . $returnCode;
return false;
//in case of WIRE we have no bank return code and return text value, so RT has to be empty
} elseif ($this->getData['RT'] == "") {
//check IOS ORDER_STATUS
if (in_array(trim($ios->status['ORDER_STATUS']), $this->successfulStatus)) {
$this->backStatusArray['RESULT'] = true;
return true;
}
$this->backStatusArray['RESULT'] = false;
$this->errorMessage[] = 'Empty RT and status is: ' . $ios->status['ORDER_STATUS'];
return false;
}
$this->backStatusArray['RESULT'] = false;
$this->errorMessage[] = 'RT content: failure!';
return false;
} elseif (!isset($this->getData['RT'])) {
$this->backStatusArray['RESULT'] = false;
$this->errorMessage[] = 'Missing variable: (RT)!';
return false;
}
$this->backStatusArray['RESULT'] = false;
$this->errorMessage[] = 'checkRtVariable: general error!';
return false;
} | [
"protected",
"function",
"checkRtVariable",
"(",
"$",
"ios",
")",
"{",
"$",
"successCode",
"=",
"array",
"(",
"\"000\"",
",",
"\"001\"",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"getData",
"[",
"'RT'",
"]",
")",
")",
"{",
"$",
"returnCod... | Check RT variable
@param obj $ios Result of IOS comunication
@return boolean | [
"Check",
"RT",
"variable"
] | d2808bf52e8d34be69414b444a00f1a9c8564930 | https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleBackRef.php#L214-L255 | train |
alaxos/cakephp3-libs | src/Lib/XmlTool.php | XmlTool.getAttribute | public static function getAttribute($node, $attribute_name, $default_value = null)
{
$value = $node->getAttribute($attribute_name);
if (! isset($value) || strlen($value) == 0)
{
$value = $default_value;
}
return $value;
} | php | public static function getAttribute($node, $attribute_name, $default_value = null)
{
$value = $node->getAttribute($attribute_name);
if (! isset($value) || strlen($value) == 0)
{
$value = $default_value;
}
return $value;
} | [
"public",
"static",
"function",
"getAttribute",
"(",
"$",
"node",
",",
"$",
"attribute_name",
",",
"$",
"default_value",
"=",
"null",
")",
"{",
"$",
"value",
"=",
"$",
"node",
"->",
"getAttribute",
"(",
"$",
"attribute_name",
")",
";",
"if",
"(",
"!",
... | Get an attribute value, or the default value if the attribute is null or empty
@param DOMNode $node The node to search the attribute on
@param string $attribute_name The name of the attribute to get the value from
@param string $default_value A default value if the attribute doesn't exist or is empty | [
"Get",
"an",
"attribute",
"value",
"or",
"the",
"default",
"value",
"if",
"the",
"attribute",
"is",
"null",
"or",
"empty"
] | 685e9f17a3fbe3550c59a03a65c4d75df763e804 | https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Lib/XmlTool.php#L190-L200 | train |
alaxos/cakephp3-libs | src/Lib/XmlTool.php | XmlTool.deleteElementsByXpath | public static function deleteElementsByXpath($node, $xpath_query, $namespaces = array())
{
if(is_a($node, 'DOMDocument'))
{
$xpath = new DOMXPath($node);
}
elseif(is_a($node, 'DOMNode'))
{
$xpath = new DOMXPath($node->ownerDocument);
}
else
{
return false;
}
foreach($namespaces as $prefix => $namespaceURI)
{
$xpath->registerNamespace($prefix, $namespaceURI);
}
$node_list = $xpath->query($xpath_query, $node);
if($node_list->length > 0)
{
foreach($node_list as $node_to_delete)
{
if(isset($node_to_delete->parentNode))
{
$node_to_delete->parentNode->removeChild($node_to_delete);
}
}
}
} | php | public static function deleteElementsByXpath($node, $xpath_query, $namespaces = array())
{
if(is_a($node, 'DOMDocument'))
{
$xpath = new DOMXPath($node);
}
elseif(is_a($node, 'DOMNode'))
{
$xpath = new DOMXPath($node->ownerDocument);
}
else
{
return false;
}
foreach($namespaces as $prefix => $namespaceURI)
{
$xpath->registerNamespace($prefix, $namespaceURI);
}
$node_list = $xpath->query($xpath_query, $node);
if($node_list->length > 0)
{
foreach($node_list as $node_to_delete)
{
if(isset($node_to_delete->parentNode))
{
$node_to_delete->parentNode->removeChild($node_to_delete);
}
}
}
} | [
"public",
"static",
"function",
"deleteElementsByXpath",
"(",
"$",
"node",
",",
"$",
"xpath_query",
",",
"$",
"namespaces",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"is_a",
"(",
"$",
"node",
",",
"'DOMDocument'",
")",
")",
"{",
"$",
"xpath",
"=",
... | Delete all the nodes from a DOMDocument that are found with the given xpath query
@param DOMNode $node
@param string $xpath_query
@param array $namespaces
@return boolean | [
"Delete",
"all",
"the",
"nodes",
"from",
"a",
"DOMDocument",
"that",
"are",
"found",
"with",
"the",
"given",
"xpath",
"query"
] | 685e9f17a3fbe3550c59a03a65c4d75df763e804 | https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Lib/XmlTool.php#L210-L242 | train |
alaxos/cakephp3-libs | src/Lib/XmlTool.php | XmlTool.setNodeText | public static function setNodeText($dom_document, $node, $text)
{
/*
* Clear existing child nodes
*/
foreach($node->childNodes as $child_node)
{
$node->removeChild($child_node);
}
/*
* Add a new child TextNode
*/
return $node->appendChild($dom_document->createTextNode($text));
} | php | public static function setNodeText($dom_document, $node, $text)
{
/*
* Clear existing child nodes
*/
foreach($node->childNodes as $child_node)
{
$node->removeChild($child_node);
}
/*
* Add a new child TextNode
*/
return $node->appendChild($dom_document->createTextNode($text));
} | [
"public",
"static",
"function",
"setNodeText",
"(",
"$",
"dom_document",
",",
"$",
"node",
",",
"$",
"text",
")",
"{",
"/*\n * Clear existing child nodes\n */",
"foreach",
"(",
"$",
"node",
"->",
"childNodes",
"as",
"$",
"child_node",
")",
"{",
"$"... | Replace the content of a node by a TextNode containing the given text
Note:
compared to using $node->nodeValue, this method automatically encodes the text
to support characters such as ampersand
@param DOMDocument $dom_document
@param DOMNode $node
@param string $text
@return DOMNode the newly created TextNode | [
"Replace",
"the",
"content",
"of",
"a",
"node",
"by",
"a",
"TextNode",
"containing",
"the",
"given",
"text"
] | 685e9f17a3fbe3550c59a03a65c4d75df763e804 | https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Lib/XmlTool.php#L305-L319 | train |
alaxos/cakephp3-libs | src/Controller/Component/FilterComponent.php | FilterComponent.prepareSearchEntity | public function prepareSearchEntity(array $options = array())
{
$alias = $options['alias'];
/**
* @var Entity $search_entity
*/
$search_entity = $this->controller->{$alias}->newEntity();
$search_entity->setAccess('*', true);
$this->controller->{$alias}->patchEntity($search_entity, $this->controller->request->getData());
$this->controller->set(compact('search_entity'));
} | php | public function prepareSearchEntity(array $options = array())
{
$alias = $options['alias'];
/**
* @var Entity $search_entity
*/
$search_entity = $this->controller->{$alias}->newEntity();
$search_entity->setAccess('*', true);
$this->controller->{$alias}->patchEntity($search_entity, $this->controller->request->getData());
$this->controller->set(compact('search_entity'));
} | [
"public",
"function",
"prepareSearchEntity",
"(",
"array",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"alias",
"=",
"$",
"options",
"[",
"'alias'",
"]",
";",
"/**\n * @var Entity $search_entity\n */",
"$",
"search_entity",
"=",
"$",
"... | Prepare Entity used to display search filters in the view
@param array $options
@return void | [
"Prepare",
"Entity",
"used",
"to",
"display",
"search",
"filters",
"in",
"the",
"view"
] | 685e9f17a3fbe3550c59a03a65c4d75df763e804 | https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Controller/Component/FilterComponent.php#L370-L382 | train |
alaxos/cakephp3-libs | src/Lib/DebugTool.php | DebugTool.init_microtime | public static function init_microtime($alert_threshold = null, $force_show_file = false)
{
if(DebugTool::$enabled)
{
DebugTool :: $start_microtime = microtime(true);
DebugTool :: $last_microtime = DebugTool :: $start_microtime;
DebugTool :: $alert_threshold = $alert_threshold;
DebugTool :: $force_show_file = $force_show_file;
}
} | php | public static function init_microtime($alert_threshold = null, $force_show_file = false)
{
if(DebugTool::$enabled)
{
DebugTool :: $start_microtime = microtime(true);
DebugTool :: $last_microtime = DebugTool :: $start_microtime;
DebugTool :: $alert_threshold = $alert_threshold;
DebugTool :: $force_show_file = $force_show_file;
}
} | [
"public",
"static",
"function",
"init_microtime",
"(",
"$",
"alert_threshold",
"=",
"null",
",",
"$",
"force_show_file",
"=",
"false",
")",
"{",
"if",
"(",
"DebugTool",
"::",
"$",
"enabled",
")",
"{",
"DebugTool",
"::",
"$",
"start_microtime",
"=",
"microtim... | Init the start time to calculate steps time
@param float $alert_threshold Threshold in second above which the step time must be shown in red | [
"Init",
"the",
"start",
"time",
"to",
"calculate",
"steps",
"time"
] | 685e9f17a3fbe3550c59a03a65c4d75df763e804 | https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Lib/DebugTool.php#L118-L127 | train |
spiral/router | src/Traits/PipelineTrait.php | PipelineTrait.withMiddleware | public function withMiddleware(...$middleware): RouteInterface
{
$route = clone $this;
// array fallback
if (count($middleware) == 1 && is_array($middleware[0])) {
$middleware = $middleware[0];
}
foreach ($middleware as $item) {
if (!is_string($item) && !$item instanceof MiddlewareInterface) {
if (is_object($item)) {
$name = get_class($item);
} else {
$name = gettype($item);
}
throw new RouteException("Invalid middleware `{$name}`.");
}
$route->middleware[] = $item;
}
if (!empty($route->pipeline)) {
$route->pipeline = $route->makePipeline();
}
return $route;
} | php | public function withMiddleware(...$middleware): RouteInterface
{
$route = clone $this;
// array fallback
if (count($middleware) == 1 && is_array($middleware[0])) {
$middleware = $middleware[0];
}
foreach ($middleware as $item) {
if (!is_string($item) && !$item instanceof MiddlewareInterface) {
if (is_object($item)) {
$name = get_class($item);
} else {
$name = gettype($item);
}
throw new RouteException("Invalid middleware `{$name}`.");
}
$route->middleware[] = $item;
}
if (!empty($route->pipeline)) {
$route->pipeline = $route->makePipeline();
}
return $route;
} | [
"public",
"function",
"withMiddleware",
"(",
"...",
"$",
"middleware",
")",
":",
"RouteInterface",
"{",
"$",
"route",
"=",
"clone",
"$",
"this",
";",
"// array fallback",
"if",
"(",
"count",
"(",
"$",
"middleware",
")",
"==",
"1",
"&&",
"is_array",
"(",
... | Associated middleware with route. New instance of route will be returned.
Example:
$route->withMiddleware(new CacheMiddleware(100));
$route->withMiddleware(ProxyMiddleware::class);
$route->withMiddleware(ProxyMiddleware::class, OtherMiddleware::class);
$route->withMiddleware([ProxyMiddleware::class, OtherMiddleware::class]);
@param MiddlewareInterface|string|array ...$middleware
@return RouteInterface|$this
@throws RouteException | [
"Associated",
"middleware",
"with",
"route",
".",
"New",
"instance",
"of",
"route",
"will",
"be",
"returned",
"."
] | 35721d06231d5650402eb93ac7f3ade00cd1b640 | https://github.com/spiral/router/blob/35721d06231d5650402eb93ac7f3ade00cd1b640/src/Traits/PipelineTrait.php#L42-L70 | train |
spiral/router | src/Traits/PipelineTrait.php | PipelineTrait.makePipeline | protected function makePipeline(): Pipeline
{
try {
$this->pipeline = $this->container->get(Pipeline::class);
foreach ($this->middleware as $middleware) {
if ($middleware instanceof MiddlewareInterface) {
$this->pipeline->pushMiddleware($middleware);
} else {
// dynamically resolved
$this->pipeline->pushMiddleware($this->container->get($middleware));
}
}
} catch (ContainerExceptionInterface $e) {
throw new RouteException($e->getMessage(), $e->getCode(), $e);
}
return $this->pipeline;
} | php | protected function makePipeline(): Pipeline
{
try {
$this->pipeline = $this->container->get(Pipeline::class);
foreach ($this->middleware as $middleware) {
if ($middleware instanceof MiddlewareInterface) {
$this->pipeline->pushMiddleware($middleware);
} else {
// dynamically resolved
$this->pipeline->pushMiddleware($this->container->get($middleware));
}
}
} catch (ContainerExceptionInterface $e) {
throw new RouteException($e->getMessage(), $e->getCode(), $e);
}
return $this->pipeline;
} | [
"protected",
"function",
"makePipeline",
"(",
")",
":",
"Pipeline",
"{",
"try",
"{",
"$",
"this",
"->",
"pipeline",
"=",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"Pipeline",
"::",
"class",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"middlewa... | Get associated route pipeline.
@return Pipeline
@throws RouteException | [
"Get",
"associated",
"route",
"pipeline",
"."
] | 35721d06231d5650402eb93ac7f3ade00cd1b640 | https://github.com/spiral/router/blob/35721d06231d5650402eb93ac7f3ade00cd1b640/src/Traits/PipelineTrait.php#L79-L97 | train |
IconoCoders/otp-simple-sdk | Source/SimpleTransaction.php | SimpleTransaction.createHiddenField | public function createHiddenField($name = '', $value = '')
{
if ($name == '') {
$this->errorMessage[] = 'HTML HIDDEN: field name is empty';
return false;
}
$inputId = $name;
if (substr($name, -2, 2) == "[]") {
$inputId = substr($name, 0, -2);
}
return "\n<input type='hidden' name='" . $name . "' id='" . $inputId . "' value='" . $value . "' />";
} | php | public function createHiddenField($name = '', $value = '')
{
if ($name == '') {
$this->errorMessage[] = 'HTML HIDDEN: field name is empty';
return false;
}
$inputId = $name;
if (substr($name, -2, 2) == "[]") {
$inputId = substr($name, 0, -2);
}
return "\n<input type='hidden' name='" . $name . "' id='" . $inputId . "' value='" . $value . "' />";
} | [
"public",
"function",
"createHiddenField",
"(",
"$",
"name",
"=",
"''",
",",
"$",
"value",
"=",
"''",
")",
"{",
"if",
"(",
"$",
"name",
"==",
"''",
")",
"{",
"$",
"this",
"->",
"errorMessage",
"[",
"]",
"=",
"'HTML HIDDEN: field name is empty'",
";",
"... | Creates hidden HTML field
@param string $name Name of the field. ID parameter will be generated without "[]"
@param string $value Value of the field
@return string HTML form element | [
"Creates",
"hidden",
"HTML",
"field"
] | d2808bf52e8d34be69414b444a00f1a9c8564930 | https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleTransaction.php#L166-L177 | train |
IconoCoders/otp-simple-sdk | Source/SimpleTransaction.php | SimpleTransaction.createPostArray | public function createPostArray($hashFieldName = "ORDER_HASH")
{
if (!$this->prepareFields($hashFieldName)) {
$this->errorMessage[] = 'POST ARRAY: Missing hash field name';
return false;
}
return $this->formData;
} | php | public function createPostArray($hashFieldName = "ORDER_HASH")
{
if (!$this->prepareFields($hashFieldName)) {
$this->errorMessage[] = 'POST ARRAY: Missing hash field name';
return false;
}
return $this->formData;
} | [
"public",
"function",
"createPostArray",
"(",
"$",
"hashFieldName",
"=",
"\"ORDER_HASH\"",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"prepareFields",
"(",
"$",
"hashFieldName",
")",
")",
"{",
"$",
"this",
"->",
"errorMessage",
"[",
"]",
"=",
"'POST ARRA... | Generates raw data array with HMAC HASH code for custom processing
@param string $hashFieldName Index-name of the generated HASH field in the associative array
@return array Data content of form | [
"Generates",
"raw",
"data",
"array",
"with",
"HMAC",
"HASH",
"code",
"for",
"custom",
"processing"
] | d2808bf52e8d34be69414b444a00f1a9c8564930 | https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleTransaction.php#L187-L194 | train |
IconoCoders/otp-simple-sdk | Source/SimpleTransaction.php | SimpleTransaction.setDefaults | protected function setDefaults($sets = array())
{
foreach ($sets as $set) {
foreach ($set as $field => $fieldParams) {
if ($fieldParams['type'] == 'single' && isset($fieldParams['default'])) {
$this->fieldData[$field] = $fieldParams['default'];
}
}
}
} | php | protected function setDefaults($sets = array())
{
foreach ($sets as $set) {
foreach ($set as $field => $fieldParams) {
if ($fieldParams['type'] == 'single' && isset($fieldParams['default'])) {
$this->fieldData[$field] = $fieldParams['default'];
}
}
}
} | [
"protected",
"function",
"setDefaults",
"(",
"$",
"sets",
"=",
"array",
"(",
")",
")",
"{",
"foreach",
"(",
"$",
"sets",
"as",
"$",
"set",
")",
"{",
"foreach",
"(",
"$",
"set",
"as",
"$",
"field",
"=>",
"$",
"fieldParams",
")",
"{",
"if",
"(",
"$... | Sets default value for a field
@param array $sets Array of fields and its parameters
@return void | [
"Sets",
"default",
"value",
"for",
"a",
"field"
] | d2808bf52e8d34be69414b444a00f1a9c8564930 | https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleTransaction.php#L204-L213 | train |
IconoCoders/otp-simple-sdk | Source/SimpleTransaction.php | SimpleTransaction.checkRequired | protected function checkRequired()
{
$missing = array();
foreach ($this->validFields as $field => $params) {
if (isset($params['required']) && $params['required']) {
if ($params['type'] == "single") {
if (!isset($this->formData[$field])) {
$missing[] = $field;
$this->errorMessage[] = 'Missing field: ' . $field;
}
} elseif ($params['type'] == "product") {
foreach ($this->products as $prod) {
$paramName = $params['paramName'];
if (!isset($prod[$paramName])) {
$missing[] = $field;
$this->errorMessage[] = 'Missing field: ' . $field;
}
}
}
}
}
$this->missing = $missing;
return true;
} | php | protected function checkRequired()
{
$missing = array();
foreach ($this->validFields as $field => $params) {
if (isset($params['required']) && $params['required']) {
if ($params['type'] == "single") {
if (!isset($this->formData[$field])) {
$missing[] = $field;
$this->errorMessage[] = 'Missing field: ' . $field;
}
} elseif ($params['type'] == "product") {
foreach ($this->products as $prod) {
$paramName = $params['paramName'];
if (!isset($prod[$paramName])) {
$missing[] = $field;
$this->errorMessage[] = 'Missing field: ' . $field;
}
}
}
}
}
$this->missing = $missing;
return true;
} | [
"protected",
"function",
"checkRequired",
"(",
")",
"{",
"$",
"missing",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"validFields",
"as",
"$",
"field",
"=>",
"$",
"params",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"params",
"[",
... | Checks if all required fields are set.
Returns true or the array of missing fields list
@return boolean | [
"Checks",
"if",
"all",
"required",
"fields",
"are",
"set",
".",
"Returns",
"true",
"or",
"the",
"array",
"of",
"missing",
"fields",
"list"
] | d2808bf52e8d34be69414b444a00f1a9c8564930 | https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleTransaction.php#L222-L245 | train |
IconoCoders/otp-simple-sdk | Source/SimpleTransaction.php | SimpleTransaction.getField | public function getField($fieldName = '')
{
if (isset($this->fieldData[$fieldName])) {
return $this->fieldData[$fieldName];
}
$this->debugMessage[] = 'GET FIELD: Missing field name in getField: ' . $fieldName;
return false;
} | php | public function getField($fieldName = '')
{
if (isset($this->fieldData[$fieldName])) {
return $this->fieldData[$fieldName];
}
$this->debugMessage[] = 'GET FIELD: Missing field name in getField: ' . $fieldName;
return false;
} | [
"public",
"function",
"getField",
"(",
"$",
"fieldName",
"=",
"''",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"fieldData",
"[",
"$",
"fieldName",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"fieldData",
"[",
"$",
"fieldName",
"]",
... | Getter method for fields
@param string $fieldName Name of the field
@return array Data of field | [
"Getter",
"method",
"for",
"fields"
] | d2808bf52e8d34be69414b444a00f1a9c8564930 | https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleTransaction.php#L255-L262 | train |
IconoCoders/otp-simple-sdk | Source/SimpleTransaction.php | SimpleTransaction.setField | public function setField($fieldName = '', $fieldValue = '')
{
if (in_array($fieldName, array_keys($this->validFields))) {
$this->fieldData[$fieldName] = $this->cleanString($fieldValue);
if ($fieldName == 'LU_ENABLE_TOKEN') {
if ($fieldValue) {
$this->fieldData['LU_TOKEN_TYPE'] = 'PAY_BY_CLICK';
}
}
return true;
}
$this->debugMessage[] = 'SET FIELD: Invalid field in setField: ' . $fieldName;
return false;
} | php | public function setField($fieldName = '', $fieldValue = '')
{
if (in_array($fieldName, array_keys($this->validFields))) {
$this->fieldData[$fieldName] = $this->cleanString($fieldValue);
if ($fieldName == 'LU_ENABLE_TOKEN') {
if ($fieldValue) {
$this->fieldData['LU_TOKEN_TYPE'] = 'PAY_BY_CLICK';
}
}
return true;
}
$this->debugMessage[] = 'SET FIELD: Invalid field in setField: ' . $fieldName;
return false;
} | [
"public",
"function",
"setField",
"(",
"$",
"fieldName",
"=",
"''",
",",
"$",
"fieldValue",
"=",
"''",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"fieldName",
",",
"array_keys",
"(",
"$",
"this",
"->",
"validFields",
")",
")",
")",
"{",
"$",
"this",
... | Setter method for fields
@param string $fieldName Name of the field to be set
@param imxed $fieldValue Value of the field to be set
@return boolean | [
"Setter",
"method",
"for",
"fields"
] | d2808bf52e8d34be69414b444a00f1a9c8564930 | https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleTransaction.php#L273-L286 | train |
IconoCoders/otp-simple-sdk | Source/SimpleTransaction.php | SimpleTransaction.prepareFields | protected function prepareFields($hashName = '')
{
if (!is_string($hashName)) {
$this->errorMessage[] = 'PREPARE: Hash name is not string!';
return false;
}
$this->setHashData();
$this->setFormData();
if ($this->hashData) {
$this->formData[$hashName] = $this->createHashString($this->hashData);
}
$this->checkRequired();
if (count($this->missing) == 0) {
return true;
}
$this->debugMessage[] = 'PREPARE: Missing required fields';
$this->errorMessage[] = 'PREPARE: Missing required fields';
return false;
} | php | protected function prepareFields($hashName = '')
{
if (!is_string($hashName)) {
$this->errorMessage[] = 'PREPARE: Hash name is not string!';
return false;
}
$this->setHashData();
$this->setFormData();
if ($this->hashData) {
$this->formData[$hashName] = $this->createHashString($this->hashData);
}
$this->checkRequired();
if (count($this->missing) == 0) {
return true;
}
$this->debugMessage[] = 'PREPARE: Missing required fields';
$this->errorMessage[] = 'PREPARE: Missing required fields';
return false;
} | [
"protected",
"function",
"prepareFields",
"(",
"$",
"hashName",
"=",
"''",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"hashName",
")",
")",
"{",
"$",
"this",
"->",
"errorMessage",
"[",
"]",
"=",
"'PREPARE: Hash name is not string!'",
";",
"return",
"... | Finalizes and prepares fields for sending
@param string $hashName Name of the field containing HMAC HASH code
@return boolean | [
"Finalizes",
"and",
"prepares",
"fields",
"for",
"sending"
] | d2808bf52e8d34be69414b444a00f1a9c8564930 | https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleTransaction.php#L321-L339 | train |
IconoCoders/otp-simple-sdk | Source/SimpleTransaction.php | SimpleTransaction.setHashData | protected function setHashData()
{
foreach ($this->hashFields as $field) {
$params = $this->validFields[$field];
if ($params['type'] == "single") {
if (isset($this->fieldData[$field])) {
$this->hashData[] = $this->fieldData[$field];
}
} elseif ($params['type'] == "product") {
foreach ($this->products as $product) {
if (isset($product[$params["paramName"]])) {
$this->hashData[] = $product[$params["paramName"]];
}
}
}
}
} | php | protected function setHashData()
{
foreach ($this->hashFields as $field) {
$params = $this->validFields[$field];
if ($params['type'] == "single") {
if (isset($this->fieldData[$field])) {
$this->hashData[] = $this->fieldData[$field];
}
} elseif ($params['type'] == "product") {
foreach ($this->products as $product) {
if (isset($product[$params["paramName"]])) {
$this->hashData[] = $product[$params["paramName"]];
}
}
}
}
} | [
"protected",
"function",
"setHashData",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"hashFields",
"as",
"$",
"field",
")",
"{",
"$",
"params",
"=",
"$",
"this",
"->",
"validFields",
"[",
"$",
"field",
"]",
";",
"if",
"(",
"$",
"params",
"[",
... | Set hash data by hashFields
@return void | [
"Set",
"hash",
"data",
"by",
"hashFields"
] | d2808bf52e8d34be69414b444a00f1a9c8564930 | https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleTransaction.php#L347-L363 | train |
IconoCoders/otp-simple-sdk | Source/SimpleTransaction.php | SimpleTransaction.setFormData | protected function setFormData()
{
foreach ($this->validFields as $field => $params) {
if (isset($params["rename"])) {
$field = $params["rename"];
}
if ($params['type'] == "single") {
if (isset($this->fieldData[$field])) {
$this->formData[$field] = $this->fieldData[$field];
}
} elseif ($params['type'] == "product") {
if (!isset($this->formData[$field])) {
$this->formData[$field] = array();
}
foreach ($this->products as $num => $product) {
if (isset($product[$params["paramName"]])) {
$this->formData[$field][$num] = $product[$params["paramName"]];
}
}
}
}
} | php | protected function setFormData()
{
foreach ($this->validFields as $field => $params) {
if (isset($params["rename"])) {
$field = $params["rename"];
}
if ($params['type'] == "single") {
if (isset($this->fieldData[$field])) {
$this->formData[$field] = $this->fieldData[$field];
}
} elseif ($params['type'] == "product") {
if (!isset($this->formData[$field])) {
$this->formData[$field] = array();
}
foreach ($this->products as $num => $product) {
if (isset($product[$params["paramName"]])) {
$this->formData[$field][$num] = $product[$params["paramName"]];
}
}
}
}
} | [
"protected",
"function",
"setFormData",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"validFields",
"as",
"$",
"field",
"=>",
"$",
"params",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"params",
"[",
"\"rename\"",
"]",
")",
")",
"{",
"$",
"field",
... | Set form data by validFields
@return void | [
"Set",
"form",
"data",
"by",
"validFields"
] | d2808bf52e8d34be69414b444a00f1a9c8564930 | https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleTransaction.php#L371-L392 | train |
IconoCoders/otp-simple-sdk | Source/SimpleTransaction.php | SimpleTransaction.processResponse | public function processResponse($resp = '')
{
preg_match_all("/<EPAYMENT>(.*?)<\/EPAYMENT>/", $resp, $matches);
$data = explode("|", $matches[1][0]);
if (is_array($data)) {
if (count($data) > 0) {
$counter = 1;
foreach ($data as $dataValue) {
$this->debugMessage[] = 'EPAYMENT_ELEMENT_' . $counter .': ' . $dataValue;
$counter++;
}
}
}
return $this->nameData($data);
} | php | public function processResponse($resp = '')
{
preg_match_all("/<EPAYMENT>(.*?)<\/EPAYMENT>/", $resp, $matches);
$data = explode("|", $matches[1][0]);
if (is_array($data)) {
if (count($data) > 0) {
$counter = 1;
foreach ($data as $dataValue) {
$this->debugMessage[] = 'EPAYMENT_ELEMENT_' . $counter .': ' . $dataValue;
$counter++;
}
}
}
return $this->nameData($data);
} | [
"public",
"function",
"processResponse",
"(",
"$",
"resp",
"=",
"''",
")",
"{",
"preg_match_all",
"(",
"\"/<EPAYMENT>(.*?)<\\/EPAYMENT>/\"",
",",
"$",
"resp",
",",
"$",
"matches",
")",
";",
"$",
"data",
"=",
"explode",
"(",
"\"|\"",
",",
"$",
"matches",
"[... | Finds and processes validation response from HTTP response
@param string $resp HTTP response
@return array Data | [
"Finds",
"and",
"processes",
"validation",
"response",
"from",
"HTTP",
"response"
] | d2808bf52e8d34be69414b444a00f1a9c8564930 | https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleTransaction.php#L402-L416 | train |
IconoCoders/otp-simple-sdk | Source/SimpleTransaction.php | SimpleTransaction.checkResponseHash | public function checkResponseHash($resp = array())
{
$hash = 'N/A';
if (isset($resp['ORDER_HASH'])) {
$hash = $resp['ORDER_HASH'];
}
elseif (isset($resp['hash'])) {
$hash = $resp['hash'];
}
array_pop($resp);
$calculated = $this->createHashString($resp);
$this->debugMessage[] = 'HASH ctrl: ' . $hash;
$this->debugMessage[] = 'HASH calculated: ' . $calculated;
if ($hash == $calculated) {
$this->debugMessage[] = 'HASH CHECK: ' . 'Successful';
return true;
}
$this->errorMessage[] = 'HASH ctrl: ' . $hash;
$this->errorMessage[] = 'HASH calculated: ' . $calculated;
$this->errorMessage[] = 'HASH CHECK: ' . 'Fail';
$this->debugMessage[] = 'HASH CHECK: ' . 'Fail';
return false;
} | php | public function checkResponseHash($resp = array())
{
$hash = 'N/A';
if (isset($resp['ORDER_HASH'])) {
$hash = $resp['ORDER_HASH'];
}
elseif (isset($resp['hash'])) {
$hash = $resp['hash'];
}
array_pop($resp);
$calculated = $this->createHashString($resp);
$this->debugMessage[] = 'HASH ctrl: ' . $hash;
$this->debugMessage[] = 'HASH calculated: ' . $calculated;
if ($hash == $calculated) {
$this->debugMessage[] = 'HASH CHECK: ' . 'Successful';
return true;
}
$this->errorMessage[] = 'HASH ctrl: ' . $hash;
$this->errorMessage[] = 'HASH calculated: ' . $calculated;
$this->errorMessage[] = 'HASH CHECK: ' . 'Fail';
$this->debugMessage[] = 'HASH CHECK: ' . 'Fail';
return false;
} | [
"public",
"function",
"checkResponseHash",
"(",
"$",
"resp",
"=",
"array",
"(",
")",
")",
"{",
"$",
"hash",
"=",
"'N/A'",
";",
"if",
"(",
"isset",
"(",
"$",
"resp",
"[",
"'ORDER_HASH'",
"]",
")",
")",
"{",
"$",
"hash",
"=",
"$",
"resp",
"[",
"'OR... | Validates HASH code of the response
@param array $resp Array with the response data
@return boolean | [
"Validates",
"HASH",
"code",
"of",
"the",
"response"
] | d2808bf52e8d34be69414b444a00f1a9c8564930 | https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleTransaction.php#L426-L449 | train |
netgen/site-bundle | bundle/DependencyInjection/Compiler/XmlTextFieldTypePass.php | XmlTextFieldTypePass.process | public function process(ContainerBuilder $container): void
{
if ($container->has('ezpublish.fieldType.ezxmltext.converter.embedToHtml5')) {
$container
->findDefinition('ezpublish.fieldType.ezxmltext.converter.embedToHtml5')
->setClass(EmbedToHtml5::class)
->addMethodCall('setSite', [new Reference('netgen.ezplatform_site.site')]);
}
} | php | public function process(ContainerBuilder $container): void
{
if ($container->has('ezpublish.fieldType.ezxmltext.converter.embedToHtml5')) {
$container
->findDefinition('ezpublish.fieldType.ezxmltext.converter.embedToHtml5')
->setClass(EmbedToHtml5::class)
->addMethodCall('setSite', [new Reference('netgen.ezplatform_site.site')]);
}
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
":",
"void",
"{",
"if",
"(",
"$",
"container",
"->",
"has",
"(",
"'ezpublish.fieldType.ezxmltext.converter.embedToHtml5'",
")",
")",
"{",
"$",
"container",
"->",
"findDefinition",
"("... | Overrides EmbedToHtml5 ezxmltext converter with own implementation. | [
"Overrides",
"EmbedToHtml5",
"ezxmltext",
"converter",
"with",
"own",
"implementation",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/DependencyInjection/Compiler/XmlTextFieldTypePass.php#L17-L25 | train |
netgen/site-bundle | bundle/Pagerfanta/View/SiteView.php | SiteView.calculateEndPageForStartPageUnderflow | protected function calculateEndPageForStartPageUnderflow(int $startPage, int $endPage, int $nbPages): int
{
return min($endPage + (1 - $startPage), $nbPages);
} | php | protected function calculateEndPageForStartPageUnderflow(int $startPage, int $endPage, int $nbPages): int
{
return min($endPage + (1 - $startPage), $nbPages);
} | [
"protected",
"function",
"calculateEndPageForStartPageUnderflow",
"(",
"int",
"$",
"startPage",
",",
"int",
"$",
"endPage",
",",
"int",
"$",
"nbPages",
")",
":",
"int",
"{",
"return",
"min",
"(",
"$",
"endPage",
"+",
"(",
"1",
"-",
"$",
"startPage",
")",
... | Calculates the end page when start page is underflowed. | [
"Calculates",
"the",
"end",
"page",
"when",
"start",
"page",
"is",
"underflowed",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Pagerfanta/View/SiteView.php#L139-L142 | train |
netgen/site-bundle | bundle/Pagerfanta/View/SiteView.php | SiteView.calculateStartPageForEndPageOverflow | protected function calculateStartPageForEndPageOverflow(int $startPage, int $endPage, int $nbPages): int
{
return max($startPage - ($endPage - $nbPages), 1);
} | php | protected function calculateStartPageForEndPageOverflow(int $startPage, int $endPage, int $nbPages): int
{
return max($startPage - ($endPage - $nbPages), 1);
} | [
"protected",
"function",
"calculateStartPageForEndPageOverflow",
"(",
"int",
"$",
"startPage",
",",
"int",
"$",
"endPage",
",",
"int",
"$",
"nbPages",
")",
":",
"int",
"{",
"return",
"max",
"(",
"$",
"startPage",
"-",
"(",
"$",
"endPage",
"-",
"$",
"nbPage... | Calculates the start page when end page is overflowed. | [
"Calculates",
"the",
"start",
"page",
"when",
"end",
"page",
"is",
"overflowed",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Pagerfanta/View/SiteView.php#L147-L150 | train |
netgen/site-bundle | bundle/Pagerfanta/View/SiteView.php | SiteView.getPages | protected function getPages(): array
{
$pages = [];
$pages['previous_page'] = $this->pagerfanta->hasPreviousPage() ?
$this->generateUrl($this->pagerfanta->getPreviousPage()) :
false;
$pages['first_page'] = $this->startPage > 1 ? $this->generateUrl(1) : false;
$pages['mobile_first_page'] = $this->pagerfanta->getCurrentPage() > 2 ? $this->generateUrl(1) : false;
$pages['second_page'] = $this->startPage === 3 ? $this->generateUrl(2) : false;
$pages['separator_before'] = $this->startPage > 3;
$middlePages = [];
for ($i = $this->startPage, $end = $this->endPage; $i <= $end; ++$i) {
$middlePages[$i] = $this->generateUrl($i);
}
$pages['middle_pages'] = $middlePages;
$pages['separator_after'] = $this->endPage < $this->pagerfanta->getNbPages() - 2;
$pages['second_to_last_page'] = $this->endPage === $this->pagerfanta->getNbPages() - 2 ?
$this->generateUrl($this->pagerfanta->getNbPages() - 1) :
false;
$pages['last_page'] = $this->pagerfanta->getNbPages() > $this->endPage ?
$this->generateUrl($this->pagerfanta->getNbPages()) :
false;
$pages['mobile_last_page'] = $this->pagerfanta->getCurrentPage() < $this->pagerfanta->getNbPages() - 1 ?
$this->generateUrl($this->pagerfanta->getNbPages()) :
false;
$pages['next_page'] = $this->pagerfanta->hasNextPage() ?
$this->generateUrl($this->pagerfanta->getNextPage()) :
false;
return $pages;
} | php | protected function getPages(): array
{
$pages = [];
$pages['previous_page'] = $this->pagerfanta->hasPreviousPage() ?
$this->generateUrl($this->pagerfanta->getPreviousPage()) :
false;
$pages['first_page'] = $this->startPage > 1 ? $this->generateUrl(1) : false;
$pages['mobile_first_page'] = $this->pagerfanta->getCurrentPage() > 2 ? $this->generateUrl(1) : false;
$pages['second_page'] = $this->startPage === 3 ? $this->generateUrl(2) : false;
$pages['separator_before'] = $this->startPage > 3;
$middlePages = [];
for ($i = $this->startPage, $end = $this->endPage; $i <= $end; ++$i) {
$middlePages[$i] = $this->generateUrl($i);
}
$pages['middle_pages'] = $middlePages;
$pages['separator_after'] = $this->endPage < $this->pagerfanta->getNbPages() - 2;
$pages['second_to_last_page'] = $this->endPage === $this->pagerfanta->getNbPages() - 2 ?
$this->generateUrl($this->pagerfanta->getNbPages() - 1) :
false;
$pages['last_page'] = $this->pagerfanta->getNbPages() > $this->endPage ?
$this->generateUrl($this->pagerfanta->getNbPages()) :
false;
$pages['mobile_last_page'] = $this->pagerfanta->getCurrentPage() < $this->pagerfanta->getNbPages() - 1 ?
$this->generateUrl($this->pagerfanta->getNbPages()) :
false;
$pages['next_page'] = $this->pagerfanta->hasNextPage() ?
$this->generateUrl($this->pagerfanta->getNextPage()) :
false;
return $pages;
} | [
"protected",
"function",
"getPages",
"(",
")",
":",
"array",
"{",
"$",
"pages",
"=",
"[",
"]",
";",
"$",
"pages",
"[",
"'previous_page'",
"]",
"=",
"$",
"this",
"->",
"pagerfanta",
"->",
"hasPreviousPage",
"(",
")",
"?",
"$",
"this",
"->",
"generateUrl... | Returns the list of all pages that need to be displayed. | [
"Returns",
"the",
"list",
"of",
"all",
"pages",
"that",
"need",
"to",
"be",
"displayed",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Pagerfanta/View/SiteView.php#L155-L196 | train |
netgen/site-bundle | bundle/Pagerfanta/View/SiteView.php | SiteView.generateUrl | protected function generateUrl(int $page): string
{
$routeGenerator = $this->routeGenerator;
// We use trim here because Pagerfanta (or Symfony?) adds an extra '?'
// at the end of page when there are no other query params
return trim($routeGenerator($page), '?');
} | php | protected function generateUrl(int $page): string
{
$routeGenerator = $this->routeGenerator;
// We use trim here because Pagerfanta (or Symfony?) adds an extra '?'
// at the end of page when there are no other query params
return trim($routeGenerator($page), '?');
} | [
"protected",
"function",
"generateUrl",
"(",
"int",
"$",
"page",
")",
":",
"string",
"{",
"$",
"routeGenerator",
"=",
"$",
"this",
"->",
"routeGenerator",
";",
"// We use trim here because Pagerfanta (or Symfony?) adds an extra '?'",
"// at the end of page when there are no o... | Generates the URL based on provided page. | [
"Generates",
"the",
"URL",
"based",
"on",
"provided",
"page",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Pagerfanta/View/SiteView.php#L201-L208 | train |
netgen/site-bundle | bundle/Controller/DownloadController.php | DownloadController.downloadFile | public function downloadFile(Request $request, $contentId, $fieldId, $isInline = false): BinaryStreamResponse
{
$content = $this->getSite()->getLoadService()->loadContent(
$contentId,
$request->query->get('version'),
$request->query->get('inLanguage')
);
if (!$content->hasFieldById($fieldId) || $content->getFieldById($fieldId)->isEmpty()) {
throw new NotFoundHttpException(
$this->translator->trans('download.file_not_found', [], 'ngsite')
);
}
$binaryFieldValue = $content->getFieldById($fieldId)->value;
if ($binaryFieldValue instanceof BinaryBaseValue) {
$ioService = $this->ioFileService;
$binaryFile = $this->ioFileService->loadBinaryFile($binaryFieldValue->id);
} elseif ($binaryFieldValue instanceof ImageValue) {
$ioService = $this->ioImageService;
$binaryFile = $this->ioImageService->loadBinaryFile($binaryFieldValue->id);
} else {
throw new NotFoundHttpException(
$this->translator->trans('download.file_not_found', [], 'ngsite')
);
}
$response = new BinaryStreamResponse($binaryFile, $ioService);
$response->setContentDisposition(
(bool) $isInline ? ResponseHeaderBag::DISPOSITION_INLINE :
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
str_replace(['/', '\\'], '', $binaryFieldValue->fileName),
'file'
);
if (!$request->headers->has('Range')) {
$downloadEvent = new DownloadEvent(
$contentId,
$fieldId,
$content->contentInfo->currentVersionNo,
$response
);
$this->dispatcher->dispatch(SiteEvents::CONTENT_DOWNLOAD, $downloadEvent);
}
return $response;
} | php | public function downloadFile(Request $request, $contentId, $fieldId, $isInline = false): BinaryStreamResponse
{
$content = $this->getSite()->getLoadService()->loadContent(
$contentId,
$request->query->get('version'),
$request->query->get('inLanguage')
);
if (!$content->hasFieldById($fieldId) || $content->getFieldById($fieldId)->isEmpty()) {
throw new NotFoundHttpException(
$this->translator->trans('download.file_not_found', [], 'ngsite')
);
}
$binaryFieldValue = $content->getFieldById($fieldId)->value;
if ($binaryFieldValue instanceof BinaryBaseValue) {
$ioService = $this->ioFileService;
$binaryFile = $this->ioFileService->loadBinaryFile($binaryFieldValue->id);
} elseif ($binaryFieldValue instanceof ImageValue) {
$ioService = $this->ioImageService;
$binaryFile = $this->ioImageService->loadBinaryFile($binaryFieldValue->id);
} else {
throw new NotFoundHttpException(
$this->translator->trans('download.file_not_found', [], 'ngsite')
);
}
$response = new BinaryStreamResponse($binaryFile, $ioService);
$response->setContentDisposition(
(bool) $isInline ? ResponseHeaderBag::DISPOSITION_INLINE :
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
str_replace(['/', '\\'], '', $binaryFieldValue->fileName),
'file'
);
if (!$request->headers->has('Range')) {
$downloadEvent = new DownloadEvent(
$contentId,
$fieldId,
$content->contentInfo->currentVersionNo,
$response
);
$this->dispatcher->dispatch(SiteEvents::CONTENT_DOWNLOAD, $downloadEvent);
}
return $response;
} | [
"public",
"function",
"downloadFile",
"(",
"Request",
"$",
"request",
",",
"$",
"contentId",
",",
"$",
"fieldId",
",",
"$",
"isInline",
"=",
"false",
")",
":",
"BinaryStreamResponse",
"{",
"$",
"content",
"=",
"$",
"this",
"->",
"getSite",
"(",
")",
"->"... | Downloads the binary file specified by content ID and field ID.
Assumes that the file is locally stored
Dispatch \Netgen\Bundle\SiteBundle\Event\SiteEvents::CONTENT_DOWNLOAD only once
@param \Symfony\Component\HttpFoundation\Request $request
@param mixed $contentId
@param mixed $fieldId
@param bool $isInline
@throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException If file or image does not exist
@return \eZ\Bundle\EzPublishIOBundle\BinaryStreamResponse | [
"Downloads",
"the",
"binary",
"file",
"specified",
"by",
"content",
"ID",
"and",
"field",
"ID",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Controller/DownloadController.php#L69-L117 | train |
smartboxgroup/integration-framework-bundle | Components/WebService/Soap/AbstractSoapConfigurableProducer.php | AbstractSoapConfigurableProducer.throwRecoverableSoapFaultException | protected function throwRecoverableSoapFaultException($message, $code = 0, $previousException = null)
{
/* @var \SoapClient $soapClient */
$exception = new RecoverableSoapException(
$message,
null,
null,
null,
null,
$code,
$previousException
);
$exception->setShowExternalSystemErrorMessage(true);
$exception->setExternalSystemName($this->getName());
throw $exception;
} | php | protected function throwRecoverableSoapFaultException($message, $code = 0, $previousException = null)
{
/* @var \SoapClient $soapClient */
$exception = new RecoverableSoapException(
$message,
null,
null,
null,
null,
$code,
$previousException
);
$exception->setShowExternalSystemErrorMessage(true);
$exception->setExternalSystemName($this->getName());
throw $exception;
} | [
"protected",
"function",
"throwRecoverableSoapFaultException",
"(",
"$",
"message",
",",
"$",
"code",
"=",
"0",
",",
"$",
"previousException",
"=",
"null",
")",
"{",
"/* @var \\SoapClient $soapClient */",
"$",
"exception",
"=",
"new",
"RecoverableSoapException",
"(",
... | Throw a RecoverableSoapFault when SoapClient construct failed.
@param \SoapClient $soapClient
@param int $code
@param null $previousException
@throws \Smartbox\Integration\FrameworkBundle\Components\WebService\Soap\Exceptions\RecoverableSoapException | [
"Throw",
"a",
"RecoverableSoapFault",
"when",
"SoapClient",
"construct",
"failed",
"."
] | 5f0bf8ff86337a51f6d208bd38df39017643b905 | https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Components/WebService/Soap/AbstractSoapConfigurableProducer.php#L230-L246 | train |
netgen/site-bundle | bundle/Controller/SearchController.php | SearchController.search | public function search(Request $request): Response
{
$configResolver = $this->getConfigResolver();
$queryType = $this->getQueryTypeRegistry()->getQueryType('NetgenSite:Search');
$searchText = trim($request->query->get('searchText', ''));
if (empty($searchText)) {
return $this->render(
$configResolver->getParameter('template.search', 'ngsite'),
[
'search_text' => '',
'pager' => null,
]
);
}
$pager = new Pagerfanta(
new FindAdapter(
$queryType->getQuery(['search_text' => $searchText]),
$this->getSite()->getFindService()
)
);
$pager->setNormalizeOutOfRangePages(true);
$pager->setMaxPerPage((int) $configResolver->getParameter('search.default_limit', 'ngsite'));
$currentPage = $request->query->getInt('page', 1);
$pager->setCurrentPage($currentPage > 0 ? $currentPage : 1);
return $this->render(
$configResolver->getParameter('template.search', 'ngsite'),
[
'search_text' => $searchText,
'pager' => $pager,
]
);
} | php | public function search(Request $request): Response
{
$configResolver = $this->getConfigResolver();
$queryType = $this->getQueryTypeRegistry()->getQueryType('NetgenSite:Search');
$searchText = trim($request->query->get('searchText', ''));
if (empty($searchText)) {
return $this->render(
$configResolver->getParameter('template.search', 'ngsite'),
[
'search_text' => '',
'pager' => null,
]
);
}
$pager = new Pagerfanta(
new FindAdapter(
$queryType->getQuery(['search_text' => $searchText]),
$this->getSite()->getFindService()
)
);
$pager->setNormalizeOutOfRangePages(true);
$pager->setMaxPerPage((int) $configResolver->getParameter('search.default_limit', 'ngsite'));
$currentPage = $request->query->getInt('page', 1);
$pager->setCurrentPage($currentPage > 0 ? $currentPage : 1);
return $this->render(
$configResolver->getParameter('template.search', 'ngsite'),
[
'search_text' => $searchText,
'pager' => $pager,
]
);
} | [
"public",
"function",
"search",
"(",
"Request",
"$",
"request",
")",
":",
"Response",
"{",
"$",
"configResolver",
"=",
"$",
"this",
"->",
"getConfigResolver",
"(",
")",
";",
"$",
"queryType",
"=",
"$",
"this",
"->",
"getQueryTypeRegistry",
"(",
")",
"->",
... | Action for displaying the results of full text search. | [
"Action",
"for",
"displaying",
"the",
"results",
"of",
"full",
"text",
"search",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Controller/SearchController.php#L17-L54 | train |
nilportugues/php-api-transformer | src/Transformer/Transformer.php | Transformer.recursiveSetKeysToUnderScore | protected function recursiveSetKeysToUnderScore(array &$array)
{
$newArray = [];
foreach ($array as $key => &$value) {
$underscoreKey = RecursiveFormatterHelper::camelCaseToUnderscore($key);
$newArray[$underscoreKey] = $value;
if (\is_array($value)) {
$this->recursiveSetKeysToUnderScore($newArray[$underscoreKey]);
}
}
$array = $newArray;
} | php | protected function recursiveSetKeysToUnderScore(array &$array)
{
$newArray = [];
foreach ($array as $key => &$value) {
$underscoreKey = RecursiveFormatterHelper::camelCaseToUnderscore($key);
$newArray[$underscoreKey] = $value;
if (\is_array($value)) {
$this->recursiveSetKeysToUnderScore($newArray[$underscoreKey]);
}
}
$array = $newArray;
} | [
"protected",
"function",
"recursiveSetKeysToUnderScore",
"(",
"array",
"&",
"$",
"array",
")",
"{",
"$",
"newArray",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"array",
"as",
"$",
"key",
"=>",
"&",
"$",
"value",
")",
"{",
"$",
"underscoreKey",
"=",
"Recu... | Changes all array keys to under_score format using recursion.
@param array $array | [
"Changes",
"all",
"array",
"keys",
"to",
"under_score",
"format",
"using",
"recursion",
"."
] | a9f20fbe1580d98e3d462a0ebe13fb7595cbd683 | https://github.com/nilportugues/php-api-transformer/blob/a9f20fbe1580d98e3d462a0ebe13fb7595cbd683/src/Transformer/Transformer.php#L125-L137 | train |
smartboxgroup/integration-framework-bundle | Core/Processors/Routing/ContentRouter.php | ContentRouter.doProcess | protected function doProcess(Exchange $exchange, SerializableArray $processingContext)
{
$evaluator = $this->getEvaluator();
foreach ($this->clauses as $clause) {
if ($evaluator->evaluateWithExchange($clause->getCondition(), $exchange)) {
$exchange->getItinerary()->prepend($clause->getItinerary());
$processingContext->set(self::CONDITION_MATCHED, $clause->getCondition());
return true;
}
}
if ($this->fallbackItinerary) {
$exchange->getItinerary()->prepend($this->fallbackItinerary);
$processingContext->set(self::CONDITION_MATCHED, 'fallback itinerary');
return true;
}
return false;
} | php | protected function doProcess(Exchange $exchange, SerializableArray $processingContext)
{
$evaluator = $this->getEvaluator();
foreach ($this->clauses as $clause) {
if ($evaluator->evaluateWithExchange($clause->getCondition(), $exchange)) {
$exchange->getItinerary()->prepend($clause->getItinerary());
$processingContext->set(self::CONDITION_MATCHED, $clause->getCondition());
return true;
}
}
if ($this->fallbackItinerary) {
$exchange->getItinerary()->prepend($this->fallbackItinerary);
$processingContext->set(self::CONDITION_MATCHED, 'fallback itinerary');
return true;
}
return false;
} | [
"protected",
"function",
"doProcess",
"(",
"Exchange",
"$",
"exchange",
",",
"SerializableArray",
"$",
"processingContext",
")",
"{",
"$",
"evaluator",
"=",
"$",
"this",
"->",
"getEvaluator",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"clauses",
"as",... | The content router will evaluate the list of when clauses for the given exchange until one of them returns true,
then the itinerary of the exchange will be updated with the one specified for the when clause.
In case that no when clause matches, if there is a fallbackItinerary defined, the exchange will be updated with it,
otherwise nothing will happen.
todo: Check what should be the behaviour when no when clause is matched and no fallbackItinerary is defined
@param Exchange $exchange
@return bool | [
"The",
"content",
"router",
"will",
"evaluate",
"the",
"list",
"of",
"when",
"clauses",
"for",
"the",
"given",
"exchange",
"until",
"one",
"of",
"them",
"returns",
"true",
"then",
"the",
"itinerary",
"of",
"the",
"exchange",
"will",
"be",
"updated",
"with",
... | 5f0bf8ff86337a51f6d208bd38df39017643b905 | https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Core/Processors/Routing/ContentRouter.php#L63-L84 | train |
Atnic/laravel-generator | app/Filters/BaseFilter.php | BaseFilter.getFilters | protected function getFilters()
{
$filters = array_diff(get_class_methods($this), [
'__construct', '__call', 'apply', 'getFilters', 'getSearchables', 'getSortables', 'buildSearch', 'buildSql'
]);
$filters = array_merge($filters, array_map(function ($searchable, $key) {
return is_array($searchable) ? $key : $searchable;
}, $this->searchables, array_keys($this->searchables)));
return array_only($this->request->query(), $filters);
} | php | protected function getFilters()
{
$filters = array_diff(get_class_methods($this), [
'__construct', '__call', 'apply', 'getFilters', 'getSearchables', 'getSortables', 'buildSearch', 'buildSql'
]);
$filters = array_merge($filters, array_map(function ($searchable, $key) {
return is_array($searchable) ? $key : $searchable;
}, $this->searchables, array_keys($this->searchables)));
return array_only($this->request->query(), $filters);
} | [
"protected",
"function",
"getFilters",
"(",
")",
"{",
"$",
"filters",
"=",
"array_diff",
"(",
"get_class_methods",
"(",
"$",
"this",
")",
",",
"[",
"'__construct'",
",",
"'__call'",
",",
"'apply'",
",",
"'getFilters'",
",",
"'getSearchables'",
",",
"'getSortab... | Fetch all relevant filters from the request.
@return array | [
"Fetch",
"all",
"relevant",
"filters",
"from",
"the",
"request",
"."
] | 7bf53837a61af566b389255784dbbf1789020018 | https://github.com/Atnic/laravel-generator/blob/7bf53837a61af566b389255784dbbf1789020018/app/Filters/BaseFilter.php#L63-L73 | train |
Atnic/laravel-generator | app/Filters/BaseFilter.php | BaseFilter.buildSearch | protected function buildSearch($query, $searchables, $value)
{
foreach ($searchables as $key => $searchable) {
if (is_array($searchable)) {
$query->orWhereHas($key, function (Builder $query) use($searchable, $value) {
$query->where(function (Builder $query) use($searchable, $value) {
$this->buildSearch($query, $searchable, $value);
});
});
} else {
if ($query->getConnection()->getDriverName() == 'pgsql')
$query->orWhere($query->qualifyColumn($searchable), 'ilike', '%'.str_replace(' ', '%', $value).'%');
else
$query->orWhere($query->qualifyColumn($searchable), 'like', '%'.str_replace(' ', '%', $value).'%');
}
}
} | php | protected function buildSearch($query, $searchables, $value)
{
foreach ($searchables as $key => $searchable) {
if (is_array($searchable)) {
$query->orWhereHas($key, function (Builder $query) use($searchable, $value) {
$query->where(function (Builder $query) use($searchable, $value) {
$this->buildSearch($query, $searchable, $value);
});
});
} else {
if ($query->getConnection()->getDriverName() == 'pgsql')
$query->orWhere($query->qualifyColumn($searchable), 'ilike', '%'.str_replace(' ', '%', $value).'%');
else
$query->orWhere($query->qualifyColumn($searchable), 'like', '%'.str_replace(' ', '%', $value).'%');
}
}
} | [
"protected",
"function",
"buildSearch",
"(",
"$",
"query",
",",
"$",
"searchables",
",",
"$",
"value",
")",
"{",
"foreach",
"(",
"$",
"searchables",
"as",
"$",
"key",
"=>",
"$",
"searchable",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"searchable",
")"... | Recursive Build Search
@param \Illuminate\Database\Eloquent\Builder $query
@param array|string $searchables
@param string $value | [
"Recursive",
"Build",
"Search"
] | 7bf53837a61af566b389255784dbbf1789020018 | https://github.com/Atnic/laravel-generator/blob/7bf53837a61af566b389255784dbbf1789020018/app/Filters/BaseFilter.php#L112-L128 | train |
Atnic/laravel-generator | app/Filters/BaseFilter.php | BaseFilter.per_page | public function per_page($value)
{
$validator = validator([ 'value' => $value ], [ 'value' => 'numeric|min:1|max:1000' ]);
return $this->builder->when(!$validator->fails(), function (Builder $query) use($value) {
$model = $query->getModel();
$model->setPerPage($value);
$query->setModel($model);
});
} | php | public function per_page($value)
{
$validator = validator([ 'value' => $value ], [ 'value' => 'numeric|min:1|max:1000' ]);
return $this->builder->when(!$validator->fails(), function (Builder $query) use($value) {
$model = $query->getModel();
$model->setPerPage($value);
$query->setModel($model);
});
} | [
"public",
"function",
"per_page",
"(",
"$",
"value",
")",
"{",
"$",
"validator",
"=",
"validator",
"(",
"[",
"'value'",
"=>",
"$",
"value",
"]",
",",
"[",
"'value'",
"=>",
"'numeric|min:1|max:1000'",
"]",
")",
";",
"return",
"$",
"this",
"->",
"builder",... | Total per page on pagination
@param int $value
@return \Illuminate\Database\Eloquent\Builder | [
"Total",
"per",
"page",
"on",
"pagination"
] | 7bf53837a61af566b389255784dbbf1789020018 | https://github.com/Atnic/laravel-generator/blob/7bf53837a61af566b389255784dbbf1789020018/app/Filters/BaseFilter.php#L212-L220 | train |
Atnic/laravel-generator | app/Filters/BaseFilter.php | BaseFilter.keys | public function keys($values)
{
$keys = explode(',', $values);
$model = $this->builder->getModel();
$validator = validator([ 'values' => $keys ], [ 'values.*' => 'exists:'.$model->getTable().','.$model->getKeyName() ]);
return $this->builder->when(!$validator->fails(), function (Builder $query) use($keys) {
$query->whereKey($keys);
});
} | php | public function keys($values)
{
$keys = explode(',', $values);
$model = $this->builder->getModel();
$validator = validator([ 'values' => $keys ], [ 'values.*' => 'exists:'.$model->getTable().','.$model->getKeyName() ]);
return $this->builder->when(!$validator->fails(), function (Builder $query) use($keys) {
$query->whereKey($keys);
});
} | [
"public",
"function",
"keys",
"(",
"$",
"values",
")",
"{",
"$",
"keys",
"=",
"explode",
"(",
"','",
",",
"$",
"values",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"builder",
"->",
"getModel",
"(",
")",
";",
"$",
"validator",
"=",
"validator",... | Get collection of resources by keys
@param string $values
@return \Illuminate\Database\Eloquent\Builder | [
"Get",
"collection",
"of",
"resources",
"by",
"keys"
] | 7bf53837a61af566b389255784dbbf1789020018 | https://github.com/Atnic/laravel-generator/blob/7bf53837a61af566b389255784dbbf1789020018/app/Filters/BaseFilter.php#L227-L235 | train |
Atnic/laravel-generator | app/Filters/BaseFilter.php | BaseFilter.has | public function has($values)
{
$hases = explode(',', $values);
$model = $this->builder->getModel();
$hases = collect($hases)->filter(function ($has) use($model) {
if (str_contains($has, '.')) return ($model->{explode('.', $has)[0]}() instanceof Relation);
return ($model->{$has}() instanceof Relation);
})->toArray();
$validator = validator([ 'values' => $hases ], [ 'values' => 'array|min:1' ]);
return $this->builder->when(!$validator->fails(), function (Builder $query) use($hases) {
foreach ($hases as $has) {
$query->has($has);
}
});
} | php | public function has($values)
{
$hases = explode(',', $values);
$model = $this->builder->getModel();
$hases = collect($hases)->filter(function ($has) use($model) {
if (str_contains($has, '.')) return ($model->{explode('.', $has)[0]}() instanceof Relation);
return ($model->{$has}() instanceof Relation);
})->toArray();
$validator = validator([ 'values' => $hases ], [ 'values' => 'array|min:1' ]);
return $this->builder->when(!$validator->fails(), function (Builder $query) use($hases) {
foreach ($hases as $has) {
$query->has($has);
}
});
} | [
"public",
"function",
"has",
"(",
"$",
"values",
")",
"{",
"$",
"hases",
"=",
"explode",
"(",
"','",
",",
"$",
"values",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"builder",
"->",
"getModel",
"(",
")",
";",
"$",
"hases",
"=",
"collect",
"("... | Get collection of resources by has relation
@param string $values
@return \Illuminate\Database\Eloquent\Builder | [
"Get",
"collection",
"of",
"resources",
"by",
"has",
"relation"
] | 7bf53837a61af566b389255784dbbf1789020018 | https://github.com/Atnic/laravel-generator/blob/7bf53837a61af566b389255784dbbf1789020018/app/Filters/BaseFilter.php#L314-L328 | train |
Atnic/laravel-generator | app/Filters/BaseFilter.php | BaseFilter.doesnt_have | public function doesnt_have($values)
{
$doesnt_haves = explode(',', $values);
$model = $this->builder->getModel();
$doesnt_haves = collect($doesnt_haves)->filter(function ($doesnt_have) use($model) {
if (str_contains($doesnt_have, '.')) return ($model->{explode('.', $doesnt_have)[0]}() instanceof Relation);
return ($model->{$doesnt_have}() instanceof Relation);
})->toArray();
$validator = validator([ 'values' => $doesnt_haves ], [ 'values' => 'array|min:1' ]);
return $this->builder->when(!$validator->fails(), function (Builder $query) use($doesnt_haves) {
foreach ($doesnt_haves as $doesnt_have) {
$query->doesntHave($doesnt_have);
}
});
} | php | public function doesnt_have($values)
{
$doesnt_haves = explode(',', $values);
$model = $this->builder->getModel();
$doesnt_haves = collect($doesnt_haves)->filter(function ($doesnt_have) use($model) {
if (str_contains($doesnt_have, '.')) return ($model->{explode('.', $doesnt_have)[0]}() instanceof Relation);
return ($model->{$doesnt_have}() instanceof Relation);
})->toArray();
$validator = validator([ 'values' => $doesnt_haves ], [ 'values' => 'array|min:1' ]);
return $this->builder->when(!$validator->fails(), function (Builder $query) use($doesnt_haves) {
foreach ($doesnt_haves as $doesnt_have) {
$query->doesntHave($doesnt_have);
}
});
} | [
"public",
"function",
"doesnt_have",
"(",
"$",
"values",
")",
"{",
"$",
"doesnt_haves",
"=",
"explode",
"(",
"','",
",",
"$",
"values",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"builder",
"->",
"getModel",
"(",
")",
";",
"$",
"doesnt_haves",
"... | Get collection of resources by doesnt_have relation
@param string $values
@return \Illuminate\Database\Eloquent\Builder | [
"Get",
"collection",
"of",
"resources",
"by",
"doesnt_have",
"relation"
] | 7bf53837a61af566b389255784dbbf1789020018 | https://github.com/Atnic/laravel-generator/blob/7bf53837a61af566b389255784dbbf1789020018/app/Filters/BaseFilter.php#L336-L350 | train |
Islandora-CLAW/chullo | src/FedoraApi.php | FedoraApi.getResource | public function getResource(
$uri = "",
$headers = []
) {
// Set headers
$options = ['http_errors' => false, 'headers' => $headers];
// Send the request.
return $this->client->request(
'GET',
$uri,
$options
);
} | php | public function getResource(
$uri = "",
$headers = []
) {
// Set headers
$options = ['http_errors' => false, 'headers' => $headers];
// Send the request.
return $this->client->request(
'GET',
$uri,
$options
);
} | [
"public",
"function",
"getResource",
"(",
"$",
"uri",
"=",
"\"\"",
",",
"$",
"headers",
"=",
"[",
"]",
")",
"{",
"// Set headers",
"$",
"options",
"=",
"[",
"'http_errors'",
"=>",
"false",
",",
"'headers'",
"=>",
"$",
"headers",
"]",
";",
"// Send the re... | Gets a Fedora resource.
@param string $uri Resource URI
@param array $headers HTTP Headers
@return ResponseInterface | [
"Gets",
"a",
"Fedora",
"resource",
"."
] | fc60e9c271c4f83290b3a98ad46825a7e418d51e | https://github.com/Islandora-CLAW/chullo/blob/fc60e9c271c4f83290b3a98ad46825a7e418d51e/src/FedoraApi.php#L70-L83 | train |
Islandora-CLAW/chullo | src/FedoraApi.php | FedoraApi.createResource | public function createResource(
$uri = "",
$content = null,
$headers = []
) {
$options = ['http_errors' => false];
// Set content.
$options['body'] = $content;
// Set headers.
$options['headers'] = $headers;
return $this->client->request(
'POST',
$uri,
$options
);
} | php | public function createResource(
$uri = "",
$content = null,
$headers = []
) {
$options = ['http_errors' => false];
// Set content.
$options['body'] = $content;
// Set headers.
$options['headers'] = $headers;
return $this->client->request(
'POST',
$uri,
$options
);
} | [
"public",
"function",
"createResource",
"(",
"$",
"uri",
"=",
"\"\"",
",",
"$",
"content",
"=",
"null",
",",
"$",
"headers",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"=",
"[",
"'http_errors'",
"=>",
"false",
"]",
";",
"// Set content.",
"$",
"options",... | Creates a new resource in Fedora.
@param string $uri Resource URI
@param string $content String or binary content
@param array $headers HTTP Headers
@return ResponseInterface | [
"Creates",
"a",
"new",
"resource",
"in",
"Fedora",
"."
] | fc60e9c271c4f83290b3a98ad46825a7e418d51e | https://github.com/Islandora-CLAW/chullo/blob/fc60e9c271c4f83290b3a98ad46825a7e418d51e/src/FedoraApi.php#L134-L152 | train |
Islandora-CLAW/chullo | src/FedoraApi.php | FedoraApi.modifyResource | public function modifyResource(
$uri,
$sparql = "",
$headers = []
) {
$options = ['http_errors' => false];
// Set content.
$options['body'] = $sparql;
// Set headers.
$options['headers'] = $headers;
$options['headers']['content-type'] = 'application/sparql-update';
return $this->client->request(
'PATCH',
$uri,
$options
);
} | php | public function modifyResource(
$uri,
$sparql = "",
$headers = []
) {
$options = ['http_errors' => false];
// Set content.
$options['body'] = $sparql;
// Set headers.
$options['headers'] = $headers;
$options['headers']['content-type'] = 'application/sparql-update';
return $this->client->request(
'PATCH',
$uri,
$options
);
} | [
"public",
"function",
"modifyResource",
"(",
"$",
"uri",
",",
"$",
"sparql",
"=",
"\"\"",
",",
"$",
"headers",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"=",
"[",
"'http_errors'",
"=>",
"false",
"]",
";",
"// Set content.",
"$",
"options",
"[",
"'body'"... | Modifies a resource using a SPARQL Update query.
@param string $uri Resource URI
@param string $sparql SPARQL Update query
@param array $headers HTTP Headers
@return ResponseInterface | [
"Modifies",
"a",
"resource",
"using",
"a",
"SPARQL",
"Update",
"query",
"."
] | fc60e9c271c4f83290b3a98ad46825a7e418d51e | https://github.com/Islandora-CLAW/chullo/blob/fc60e9c271c4f83290b3a98ad46825a7e418d51e/src/FedoraApi.php#L192-L211 | train |
Islandora-CLAW/chullo | src/FedoraApi.php | FedoraApi.deleteResource | public function deleteResource(
$uri = '',
$headers = []
) {
$options = ['http_errors' => false, 'headers' => $headers];
return $this->client->request(
'DELETE',
$uri,
$options
);
} | php | public function deleteResource(
$uri = '',
$headers = []
) {
$options = ['http_errors' => false, 'headers' => $headers];
return $this->client->request(
'DELETE',
$uri,
$options
);
} | [
"public",
"function",
"deleteResource",
"(",
"$",
"uri",
"=",
"''",
",",
"$",
"headers",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"=",
"[",
"'http_errors'",
"=>",
"false",
",",
"'headers'",
"=>",
"$",
"headers",
"]",
";",
"return",
"$",
"this",
"->",... | Issues a DELETE request to Fedora.
@param string $uri Resource URI
@param array $headers HTTP Headers
@return ResponseInterface | [
"Issues",
"a",
"DELETE",
"request",
"to",
"Fedora",
"."
] | fc60e9c271c4f83290b3a98ad46825a7e418d51e | https://github.com/Islandora-CLAW/chullo/blob/fc60e9c271c4f83290b3a98ad46825a7e418d51e/src/FedoraApi.php#L221-L232 | train |
Islandora-CLAW/chullo | src/FedoraApi.php | FedoraApi.saveGraph | public function saveGraph(
\EasyRdf_Graph $graph,
$uri = '',
$headers = []
) {
// Serialze the rdf.
$turtle = $graph->serialise('turtle');
// Checksum it.
$checksum_value = sha1($turtle);
// Set headers.
$headers['Content-Type'] = 'text/turtle';
$headers['digest'] = 'sha1=' . $checksum_value;
// Save it.
return $this->saveResource($uri, $turtle, $headers);
} | php | public function saveGraph(
\EasyRdf_Graph $graph,
$uri = '',
$headers = []
) {
// Serialze the rdf.
$turtle = $graph->serialise('turtle');
// Checksum it.
$checksum_value = sha1($turtle);
// Set headers.
$headers['Content-Type'] = 'text/turtle';
$headers['digest'] = 'sha1=' . $checksum_value;
// Save it.
return $this->saveResource($uri, $turtle, $headers);
} | [
"public",
"function",
"saveGraph",
"(",
"\\",
"EasyRdf_Graph",
"$",
"graph",
",",
"$",
"uri",
"=",
"''",
",",
"$",
"headers",
"=",
"[",
"]",
")",
"{",
"// Serialze the rdf.",
"$",
"turtle",
"=",
"$",
"graph",
"->",
"serialise",
"(",
"'turtle'",
")",
";... | Saves RDF in Fedora.
@param EasyRdf_Resource $graph Graph to save
@param string $uri Resource URI
@param array $headers HTTP Headers
@return ResponseInterface | [
"Saves",
"RDF",
"in",
"Fedora",
"."
] | fc60e9c271c4f83290b3a98ad46825a7e418d51e | https://github.com/Islandora-CLAW/chullo/blob/fc60e9c271c4f83290b3a98ad46825a7e418d51e/src/FedoraApi.php#L243-L260 | train |
Islandora-CLAW/chullo | src/FedoraApi.php | FedoraApi.createGraph | public function createGraph(
\EasyRdf_Graph $graph,
$uri = '',
$headers = []
) {
// Serialze the rdf.
$turtle = $graph->serialise('turtle');
// Checksum it.
$checksum_value = sha1($turtle);
// Set headers.
$headers['Content-Type'] = 'text/turtle';
$headers['digest'] = 'sha1=' . $checksum_value;
// Save it.
return $this->createResource($uri, $turtle, $headers);
} | php | public function createGraph(
\EasyRdf_Graph $graph,
$uri = '',
$headers = []
) {
// Serialze the rdf.
$turtle = $graph->serialise('turtle');
// Checksum it.
$checksum_value = sha1($turtle);
// Set headers.
$headers['Content-Type'] = 'text/turtle';
$headers['digest'] = 'sha1=' . $checksum_value;
// Save it.
return $this->createResource($uri, $turtle, $headers);
} | [
"public",
"function",
"createGraph",
"(",
"\\",
"EasyRdf_Graph",
"$",
"graph",
",",
"$",
"uri",
"=",
"''",
",",
"$",
"headers",
"=",
"[",
"]",
")",
"{",
"// Serialze the rdf.",
"$",
"turtle",
"=",
"$",
"graph",
"->",
"serialise",
"(",
"'turtle'",
")",
... | Creates RDF in Fedora.
@param EasyRdf_Resource $graph Graph to save
@param string $uri Resource URI
@param array $headers HTTP Headers
@return ResponseInterface | [
"Creates",
"RDF",
"in",
"Fedora",
"."
] | fc60e9c271c4f83290b3a98ad46825a7e418d51e | https://github.com/Islandora-CLAW/chullo/blob/fc60e9c271c4f83290b3a98ad46825a7e418d51e/src/FedoraApi.php#L271-L288 | train |
Islandora-CLAW/chullo | src/FedoraApi.php | FedoraApi.getGraph | public function getGraph(ResponseInterface $response)
{
// Extract rdf as response body and return Easy_RDF Graph object.
$rdf = $response->getBody()->getContents();
$graph = new \EasyRdf_Graph();
if (!empty($rdf)) {
$graph->parse($rdf, 'jsonld');
}
return $graph;
} | php | public function getGraph(ResponseInterface $response)
{
// Extract rdf as response body and return Easy_RDF Graph object.
$rdf = $response->getBody()->getContents();
$graph = new \EasyRdf_Graph();
if (!empty($rdf)) {
$graph->parse($rdf, 'jsonld');
}
return $graph;
} | [
"public",
"function",
"getGraph",
"(",
"ResponseInterface",
"$",
"response",
")",
"{",
"// Extract rdf as response body and return Easy_RDF Graph object.",
"$",
"rdf",
"=",
"$",
"response",
"->",
"getBody",
"(",
")",
"->",
"getContents",
"(",
")",
";",
"$",
"graph",... | Gets RDF in Fedora.
@param ResponseInterface $request Response received
@return \EasyRdf_Graph | [
"Gets",
"RDF",
"in",
"Fedora",
"."
] | fc60e9c271c4f83290b3a98ad46825a7e418d51e | https://github.com/Islandora-CLAW/chullo/blob/fc60e9c271c4f83290b3a98ad46825a7e418d51e/src/FedoraApi.php#L298-L307 | train |
netgen/site-bundle | bundle/Composer/ScriptHandler.php | ScriptHandler.installProjectSymlinks | public static function installProjectSymlinks(Event $event): void
{
$options = self::getOptions($event);
$consoleDir = static::getConsoleDir($event, 'install project symlinks');
static::executeCommand($event, $consoleDir, 'ngsite:symlink:project', $options['process-timeout']);
} | php | public static function installProjectSymlinks(Event $event): void
{
$options = self::getOptions($event);
$consoleDir = static::getConsoleDir($event, 'install project symlinks');
static::executeCommand($event, $consoleDir, 'ngsite:symlink:project', $options['process-timeout']);
} | [
"public",
"static",
"function",
"installProjectSymlinks",
"(",
"Event",
"$",
"event",
")",
":",
"void",
"{",
"$",
"options",
"=",
"self",
"::",
"getOptions",
"(",
"$",
"event",
")",
";",
"$",
"consoleDir",
"=",
"static",
"::",
"getConsoleDir",
"(",
"$",
... | Symlinks various project files and folders to their proper locations. | [
"Symlinks",
"various",
"project",
"files",
"and",
"folders",
"to",
"their",
"proper",
"locations",
"."
] | 4198c8412ffdb6692b80d35e05c8ba331365b746 | https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Composer/ScriptHandler.php#L15-L21 | train |
smartboxgroup/integration-framework-bundle | Tools/Evaluator/ApcuParserCache.php | ApcuParserCache.fetch | public function fetch($key)
{
if(extension_loaded('apcu') && function_exists('apcu_fetch')) {
$cached = apcu_fetch($key);
if (!$cached) {
return null;
}
return $cached;
}else{
return null;
}
} | php | public function fetch($key)
{
if(extension_loaded('apcu') && function_exists('apcu_fetch')) {
$cached = apcu_fetch($key);
if (!$cached) {
return null;
}
return $cached;
}else{
return null;
}
} | [
"public",
"function",
"fetch",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"extension_loaded",
"(",
"'apcu'",
")",
"&&",
"function_exists",
"(",
"'apcu_fetch'",
")",
")",
"{",
"$",
"cached",
"=",
"apcu_fetch",
"(",
"$",
"key",
")",
";",
"if",
"(",
"!",
"$"... | Fetches an expression from the cache.
@param string $key The cache key
@return ParsedExpression|null | [
"Fetches",
"an",
"expression",
"from",
"the",
"cache",
"."
] | 5f0bf8ff86337a51f6d208bd38df39017643b905 | https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Tools/Evaluator/ApcuParserCache.php#L31-L44 | train |
spiral/tokenizer | src/Tokenizer.php | Tokenizer.getTokens | public static function getTokens(string $filename): array
{
$tokens = token_get_all(file_get_contents($filename));
$line = 0;
foreach ($tokens as &$token) {
if (isset($token[self::LINE])) {
$line = $token[self::LINE];
}
if (!is_array($token)) {
$token = [$token, $token, $line];
}
unset($token);
}
return $tokens;
} | php | public static function getTokens(string $filename): array
{
$tokens = token_get_all(file_get_contents($filename));
$line = 0;
foreach ($tokens as &$token) {
if (isset($token[self::LINE])) {
$line = $token[self::LINE];
}
if (!is_array($token)) {
$token = [$token, $token, $line];
}
unset($token);
}
return $tokens;
} | [
"public",
"static",
"function",
"getTokens",
"(",
"string",
"$",
"filename",
")",
":",
"array",
"{",
"$",
"tokens",
"=",
"token_get_all",
"(",
"file_get_contents",
"(",
"$",
"filename",
")",
")",
";",
"$",
"line",
"=",
"0",
";",
"foreach",
"(",
"$",
"t... | Get all tokes for specific file.
@param string $filename
@return array | [
"Get",
"all",
"tokes",
"for",
"specific",
"file",
"."
] | aca11410e183d4c4a6c0f858ba87bf072c4eb925 | https://github.com/spiral/tokenizer/blob/aca11410e183d4c4a6c0f858ba87bf072c4eb925/src/Tokenizer.php#L92-L110 | train |
spiral/tokenizer | src/Reflection/ReflectionFile.php | ReflectionFile.importSchema | protected function importSchema(array $cache)
{
list($this->hasIncludes, $this->declarations, $this->functions, $this->namespaces) = $cache;
} | php | protected function importSchema(array $cache)
{
list($this->hasIncludes, $this->declarations, $this->functions, $this->namespaces) = $cache;
} | [
"protected",
"function",
"importSchema",
"(",
"array",
"$",
"cache",
")",
"{",
"list",
"(",
"$",
"this",
"->",
"hasIncludes",
",",
"$",
"this",
"->",
"declarations",
",",
"$",
"this",
"->",
"functions",
",",
"$",
"this",
"->",
"namespaces",
")",
"=",
"... | Import cached reflection schema.
@param array $cache | [
"Import",
"cached",
"reflection",
"schema",
"."
] | aca11410e183d4c4a6c0f858ba87bf072c4eb925 | https://github.com/spiral/tokenizer/blob/aca11410e183d4c4a6c0f858ba87bf072c4eb925/src/Reflection/ReflectionFile.php#L254-L257 | train |
spiral/tokenizer | src/Reflection/ReflectionFile.php | ReflectionFile.locateDeclarations | protected function locateDeclarations()
{
foreach ($this->getTokens() as $tokenID => $token) {
if (!in_array($token[self::TOKEN_TYPE], self::$processTokens)) {
continue;
}
switch ($token[self::TOKEN_TYPE]) {
case T_NAMESPACE:
$this->registerNamespace($tokenID);
break;
case T_USE:
$this->registerUse($tokenID);
break;
case T_FUNCTION:
$this->registerFunction($tokenID);
break;
case T_CLASS:
case T_TRAIT:
case T_INTERFACE:
if ($this->isClassNameConst($tokenID)) {
//PHP5.5 ClassName::class constant
continue 2;
}
$this->registerDeclaration($tokenID, $token[self::TOKEN_TYPE]);
break;
case T_INCLUDE:
case T_INCLUDE_ONCE:
case T_REQUIRE:
case T_REQUIRE_ONCE:
$this->hasIncludes = true;
}
}
//Dropping empty namespace
if (isset($this->namespaces[''])) {
$this->namespaces['\\'] = $this->namespaces[''];
unset($this->namespaces['']);
}
} | php | protected function locateDeclarations()
{
foreach ($this->getTokens() as $tokenID => $token) {
if (!in_array($token[self::TOKEN_TYPE], self::$processTokens)) {
continue;
}
switch ($token[self::TOKEN_TYPE]) {
case T_NAMESPACE:
$this->registerNamespace($tokenID);
break;
case T_USE:
$this->registerUse($tokenID);
break;
case T_FUNCTION:
$this->registerFunction($tokenID);
break;
case T_CLASS:
case T_TRAIT:
case T_INTERFACE:
if ($this->isClassNameConst($tokenID)) {
//PHP5.5 ClassName::class constant
continue 2;
}
$this->registerDeclaration($tokenID, $token[self::TOKEN_TYPE]);
break;
case T_INCLUDE:
case T_INCLUDE_ONCE:
case T_REQUIRE:
case T_REQUIRE_ONCE:
$this->hasIncludes = true;
}
}
//Dropping empty namespace
if (isset($this->namespaces[''])) {
$this->namespaces['\\'] = $this->namespaces[''];
unset($this->namespaces['']);
}
} | [
"protected",
"function",
"locateDeclarations",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getTokens",
"(",
")",
"as",
"$",
"tokenID",
"=>",
"$",
"token",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"token",
"[",
"self",
"::",
"TOKEN_TYPE",
... | Locate every class, interface, trait or function definition. | [
"Locate",
"every",
"class",
"interface",
"trait",
"or",
"function",
"definition",
"."
] | aca11410e183d4c4a6c0f858ba87bf072c4eb925 | https://github.com/spiral/tokenizer/blob/aca11410e183d4c4a6c0f858ba87bf072c4eb925/src/Reflection/ReflectionFile.php#L262-L306 | train |
spiral/tokenizer | src/Reflection/ReflectionFile.php | ReflectionFile.registerNamespace | private function registerNamespace(int $tokenID)
{
$namespace = '';
$localID = $tokenID + 1;
do {
$token = $this->tokens[$localID++];
if ($token[self::TOKEN_CODE] == '{') {
break;
}
$namespace .= $token[self::TOKEN_CODE];
} while (
isset($this->tokens[$localID])
&& $this->tokens[$localID][self::TOKEN_CODE] != '{'
&& $this->tokens[$localID][self::TOKEN_CODE] != ';'
);
//Whitespaces
$namespace = trim($namespace);
$uses = [];
if (isset($this->namespaces[$namespace])) {
$uses = $this->namespaces[$namespace];
}
if ($this->tokens[$localID][self::TOKEN_CODE] == ';') {
$endingID = count($this->tokens) - 1;
} else {
$endingID = $this->endingToken($tokenID);
}
$this->namespaces[$namespace] = [
self::O_TOKEN => $tokenID,
self::C_TOKEN => $endingID,
self::N_USES => $uses,
];
} | php | private function registerNamespace(int $tokenID)
{
$namespace = '';
$localID = $tokenID + 1;
do {
$token = $this->tokens[$localID++];
if ($token[self::TOKEN_CODE] == '{') {
break;
}
$namespace .= $token[self::TOKEN_CODE];
} while (
isset($this->tokens[$localID])
&& $this->tokens[$localID][self::TOKEN_CODE] != '{'
&& $this->tokens[$localID][self::TOKEN_CODE] != ';'
);
//Whitespaces
$namespace = trim($namespace);
$uses = [];
if (isset($this->namespaces[$namespace])) {
$uses = $this->namespaces[$namespace];
}
if ($this->tokens[$localID][self::TOKEN_CODE] == ';') {
$endingID = count($this->tokens) - 1;
} else {
$endingID = $this->endingToken($tokenID);
}
$this->namespaces[$namespace] = [
self::O_TOKEN => $tokenID,
self::C_TOKEN => $endingID,
self::N_USES => $uses,
];
} | [
"private",
"function",
"registerNamespace",
"(",
"int",
"$",
"tokenID",
")",
"{",
"$",
"namespace",
"=",
"''",
";",
"$",
"localID",
"=",
"$",
"tokenID",
"+",
"1",
";",
"do",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"tokens",
"[",
"$",
"localID",
... | Handle namespace declaration.
@param int $tokenID | [
"Handle",
"namespace",
"declaration",
"."
] | aca11410e183d4c4a6c0f858ba87bf072c4eb925 | https://github.com/spiral/tokenizer/blob/aca11410e183d4c4a6c0f858ba87bf072c4eb925/src/Reflection/ReflectionFile.php#L313-L350 | train |
spiral/tokenizer | src/Reflection/ReflectionFile.php | ReflectionFile.registerDeclaration | private function registerDeclaration(int $tokenID, int $tokenType)
{
$localID = $tokenID + 1;
while ($this->tokens[$localID][self::TOKEN_TYPE] != T_STRING) {
++$localID;
}
$name = $this->tokens[$localID][self::TOKEN_CODE];
if (!empty($namespace = $this->activeNamespace($tokenID))) {
$name = $namespace . self::NS_SEPARATOR . $name;
}
$this->declarations[token_name($tokenType)][$name] = [
self::O_TOKEN => $tokenID,
self::C_TOKEN => $this->endingToken($tokenID),
];
} | php | private function registerDeclaration(int $tokenID, int $tokenType)
{
$localID = $tokenID + 1;
while ($this->tokens[$localID][self::TOKEN_TYPE] != T_STRING) {
++$localID;
}
$name = $this->tokens[$localID][self::TOKEN_CODE];
if (!empty($namespace = $this->activeNamespace($tokenID))) {
$name = $namespace . self::NS_SEPARATOR . $name;
}
$this->declarations[token_name($tokenType)][$name] = [
self::O_TOKEN => $tokenID,
self::C_TOKEN => $this->endingToken($tokenID),
];
} | [
"private",
"function",
"registerDeclaration",
"(",
"int",
"$",
"tokenID",
",",
"int",
"$",
"tokenType",
")",
"{",
"$",
"localID",
"=",
"$",
"tokenID",
"+",
"1",
";",
"while",
"(",
"$",
"this",
"->",
"tokens",
"[",
"$",
"localID",
"]",
"[",
"self",
":... | Handle declaration of class, trait of interface. Declaration will be stored under it's token
type in declarations array.
@param int $tokenID
@param int $tokenType | [
"Handle",
"declaration",
"of",
"class",
"trait",
"of",
"interface",
".",
"Declaration",
"will",
"be",
"stored",
"under",
"it",
"s",
"token",
"type",
"in",
"declarations",
"array",
"."
] | aca11410e183d4c4a6c0f858ba87bf072c4eb925 | https://github.com/spiral/tokenizer/blob/aca11410e183d4c4a6c0f858ba87bf072c4eb925/src/Reflection/ReflectionFile.php#L424-L440 | train |
spiral/tokenizer | src/Reflection/ReflectionFile.php | ReflectionFile.registerInvocation | private function registerInvocation(
int $invocationID,
int $argumentsID,
int $endID,
array $arguments,
int $invocationLevel
) {
//Nested invocations
$this->locateInvocations($arguments, $invocationLevel + 1);
list($class, $operator, $name) = $this->fetchContext($invocationID, $argumentsID);
if (!empty($operator) && empty($class)) {
//Non detectable
return;
}
$this->invocations[] = new ReflectionInvocation(
$this->filename,
$this->lineNumber($invocationID),
$class,
$operator,
$name,
ReflectionArgument::locateArguments($arguments),
$this->getSource($invocationID, $endID),
$invocationLevel
);
} | php | private function registerInvocation(
int $invocationID,
int $argumentsID,
int $endID,
array $arguments,
int $invocationLevel
) {
//Nested invocations
$this->locateInvocations($arguments, $invocationLevel + 1);
list($class, $operator, $name) = $this->fetchContext($invocationID, $argumentsID);
if (!empty($operator) && empty($class)) {
//Non detectable
return;
}
$this->invocations[] = new ReflectionInvocation(
$this->filename,
$this->lineNumber($invocationID),
$class,
$operator,
$name,
ReflectionArgument::locateArguments($arguments),
$this->getSource($invocationID, $endID),
$invocationLevel
);
} | [
"private",
"function",
"registerInvocation",
"(",
"int",
"$",
"invocationID",
",",
"int",
"$",
"argumentsID",
",",
"int",
"$",
"endID",
",",
"array",
"$",
"arguments",
",",
"int",
"$",
"invocationLevel",
")",
"{",
"//Nested invocations",
"$",
"this",
"->",
"... | Registering invocation.
@param int $invocationID
@param int $argumentsID
@param int $endID
@param array $arguments
@param int $invocationLevel | [
"Registering",
"invocation",
"."
] | aca11410e183d4c4a6c0f858ba87bf072c4eb925 | https://github.com/spiral/tokenizer/blob/aca11410e183d4c4a6c0f858ba87bf072c4eb925/src/Reflection/ReflectionFile.php#L591-L618 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.