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
sequence | docstring
stringlengths 3
47.2k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 91
247
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
congraphcms/core | Repositories/AbstractRepository.php | AbstractRepository.removeTransactionMethod | public function removeTransactionMethod($method)
{
// if it's not an array, there are no transaction methods
if (!is_array($this->transactionMethods)) {
return $this;
}
// find method in transactionMethods
$index = array_search($method, $this->transactionMethods);
// remove the method if it exists in array
if ($index !== false) {
array_splice($this->transactionMethods, $index, 1);
}
// if transaction methods are empty set them to null
if (empty($this->transactionMethods)) {
$this->transactionMethods = null;
}
return $this;
} | php | public function removeTransactionMethod($method)
{
// if it's not an array, there are no transaction methods
if (!is_array($this->transactionMethods)) {
return $this;
}
// find method in transactionMethods
$index = array_search($method, $this->transactionMethods);
// remove the method if it exists in array
if ($index !== false) {
array_splice($this->transactionMethods, $index, 1);
}
// if transaction methods are empty set them to null
if (empty($this->transactionMethods)) {
$this->transactionMethods = null;
}
return $this;
} | [
"public",
"function",
"removeTransactionMethod",
"(",
"$",
"method",
")",
"{",
"// if it's not an array, there are no transaction methods",
"if",
"(",
"!",
"is_array",
"(",
"$",
"this",
"->",
"transactionMethods",
")",
")",
"{",
"return",
"$",
"this",
";",
"}",
"// find method in transactionMethods",
"$",
"index",
"=",
"array_search",
"(",
"$",
"method",
",",
"$",
"this",
"->",
"transactionMethods",
")",
";",
"// remove the method if it exists in array",
"if",
"(",
"$",
"index",
"!==",
"false",
")",
"{",
"array_splice",
"(",
"$",
"this",
"->",
"transactionMethods",
",",
"$",
"index",
",",
"1",
")",
";",
"}",
"// if transaction methods are empty set them to null",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"transactionMethods",
")",
")",
"{",
"$",
"this",
"->",
"transactionMethods",
"=",
"null",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Remove transaction method.
@param string $method - method name
@return $this | [
"Remove",
"transaction",
"method",
"."
] | d017d3951b446fb2ac93b8fcee120549bb125b17 | https://github.com/congraphcms/core/blob/d017d3951b446fb2ac93b8fcee120549bb125b17/Repositories/AbstractRepository.php#L157-L179 | train |
congraphcms/core | Repositories/AbstractRepository.php | AbstractRepository.proxy | protected function proxy($method, $args)
{
// logic before executing the method
//
$this->beforeProxy($method, $args);
// executing the domain method
$result = call_user_func_array(array($this, $method), $args);
// logic after executin the method
//
$this->afterProxy($method, $args, $result);
// return the result of domain method
return $result;
} | php | protected function proxy($method, $args)
{
// logic before executing the method
//
$this->beforeProxy($method, $args);
// executing the domain method
$result = call_user_func_array(array($this, $method), $args);
// logic after executin the method
//
$this->afterProxy($method, $args, $result);
// return the result of domain method
return $result;
} | [
"protected",
"function",
"proxy",
"(",
"$",
"method",
",",
"$",
"args",
")",
"{",
"// logic before executing the method",
"//",
"$",
"this",
"->",
"beforeProxy",
"(",
"$",
"method",
",",
"$",
"args",
")",
";",
"// executing the domain method",
"$",
"result",
"=",
"call_user_func_array",
"(",
"array",
"(",
"$",
"this",
",",
"$",
"method",
")",
",",
"$",
"args",
")",
";",
"// logic after executin the method",
"//",
"$",
"this",
"->",
"afterProxy",
"(",
"$",
"method",
",",
"$",
"args",
",",
"$",
"result",
")",
";",
"// return the result of domain method",
"return",
"$",
"result",
";",
"}"
] | Proxy function through which domain methods will be called
This method should be overridden in extending classes
@param $method string - domain method name
@param $arg array - array of arguments for domain method
@return mixed | [
"Proxy",
"function",
"through",
"which",
"domain",
"methods",
"will",
"be",
"called",
"This",
"method",
"should",
"be",
"overridden",
"in",
"extending",
"classes"
] | d017d3951b446fb2ac93b8fcee120549bb125b17 | https://github.com/congraphcms/core/blob/d017d3951b446fb2ac93b8fcee120549bb125b17/Repositories/AbstractRepository.php#L200-L217 | train |
congraphcms/core | Repositories/AbstractRepository.php | AbstractRepository.beforeProxy | protected function beforeProxy($method, $args)
{
// if method is defined as transaction method
if (is_array($this->transactionMethods) && in_array($method, $this->transactionMethods)) {
// begin transaction
$this->db->beginTransaction();
}
} | php | protected function beforeProxy($method, $args)
{
// if method is defined as transaction method
if (is_array($this->transactionMethods) && in_array($method, $this->transactionMethods)) {
// begin transaction
$this->db->beginTransaction();
}
} | [
"protected",
"function",
"beforeProxy",
"(",
"$",
"method",
",",
"$",
"args",
")",
"{",
"// if method is defined as transaction method",
"if",
"(",
"is_array",
"(",
"$",
"this",
"->",
"transactionMethods",
")",
"&&",
"in_array",
"(",
"$",
"method",
",",
"$",
"this",
"->",
"transactionMethods",
")",
")",
"{",
"// begin transaction",
"$",
"this",
"->",
"db",
"->",
"beginTransaction",
"(",
")",
";",
"}",
"}"
] | Logic before proxy call to domain method
@param $method string - domain method name
@param $arg array - array of arguments for domain method
@return void | [
"Logic",
"before",
"proxy",
"call",
"to",
"domain",
"method"
] | d017d3951b446fb2ac93b8fcee120549bb125b17 | https://github.com/congraphcms/core/blob/d017d3951b446fb2ac93b8fcee120549bb125b17/Repositories/AbstractRepository.php#L227-L234 | train |
congraphcms/core | Repositories/AbstractRepository.php | AbstractRepository.afterProxy | protected function afterProxy($method, $args, $result)
{
// if method is defined as transaction method
if (is_array($this->transactionMethods) && in_array($method, $this->transactionMethods)) {
// commit transaction
$this->db->commit();
}
} | php | protected function afterProxy($method, $args, $result)
{
// if method is defined as transaction method
if (is_array($this->transactionMethods) && in_array($method, $this->transactionMethods)) {
// commit transaction
$this->db->commit();
}
} | [
"protected",
"function",
"afterProxy",
"(",
"$",
"method",
",",
"$",
"args",
",",
"$",
"result",
")",
"{",
"// if method is defined as transaction method",
"if",
"(",
"is_array",
"(",
"$",
"this",
"->",
"transactionMethods",
")",
"&&",
"in_array",
"(",
"$",
"method",
",",
"$",
"this",
"->",
"transactionMethods",
")",
")",
"{",
"// commit transaction",
"$",
"this",
"->",
"db",
"->",
"commit",
"(",
")",
";",
"}",
"}"
] | Logic after proxy call to domain method
@param $method string - domain method name
@param $arg array - array of arguments for domain method
@return void | [
"Logic",
"after",
"proxy",
"call",
"to",
"domain",
"method"
] | d017d3951b446fb2ac93b8fcee120549bb125b17 | https://github.com/congraphcms/core/blob/d017d3951b446fb2ac93b8fcee120549bb125b17/Repositories/AbstractRepository.php#L244-L251 | train |
congraphcms/core | Repositories/AbstractRepository.php | AbstractRepository.update | public function update($id, $model)
{
// arguments for private method
$args = func_get_args();
// proxy call
$result = $this->proxy('_update', $args);
// if($this->shouldUseCache())
// {
// // Cache::put($this->type . ':' . $result->id, $result, $this->cacheDuration);
// Cache::forget($this->type);
// }
return $result;
} | php | public function update($id, $model)
{
// arguments for private method
$args = func_get_args();
// proxy call
$result = $this->proxy('_update', $args);
// if($this->shouldUseCache())
// {
// // Cache::put($this->type . ':' . $result->id, $result, $this->cacheDuration);
// Cache::forget($this->type);
// }
return $result;
} | [
"public",
"function",
"update",
"(",
"$",
"id",
",",
"$",
"model",
")",
"{",
"// arguments for private method",
"$",
"args",
"=",
"func_get_args",
"(",
")",
";",
"// proxy call",
"$",
"result",
"=",
"$",
"this",
"->",
"proxy",
"(",
"'_update'",
",",
"$",
"args",
")",
";",
"// if($this->shouldUseCache())",
"// {",
"// \t// Cache::put($this->type . ':' . $result->id, $result, $this->cacheDuration);",
"// \tCache::forget($this->type);",
"// }",
"return",
"$",
"result",
";",
"}"
] | DB UPDATE of object
@param $model string - data for object update
@return mixed | [
"DB",
"UPDATE",
"of",
"object"
] | d017d3951b446fb2ac93b8fcee120549bb125b17 | https://github.com/congraphcms/core/blob/d017d3951b446fb2ac93b8fcee120549bb125b17/Repositories/AbstractRepository.php#L284-L299 | train |
lasallecms/lasallecms-l5-usermanagement-pkg | src/Http/Controllers/Frontendauth/FrontendAuthController.php | FrontendAuthController.post2FALogin | public function post2FALogin(Request $request) {
$userId = $request->session()->get('user_id');
// Did the user take too much time to fill out the form?
if ($this->twoFactorAuthHelper->isTwoFactorAuthFormTimeout($userId)) {
return view('usermanagement::frontend.'.$this->frontend_template_name.'.login.login', [
'title' => 'Login',
])
->withErrors([
'Two Factor Authorization' => 'Your two factor authorization code expired. Please re-login.'
]);
}
// Is the code correct?
// If not, go back to the 2FA form with an error message
if (!$this->twoFactorAuthHelper->isInputtedTwoFactorAuthCodeCorrect($userId)) {
return view('usermanagement::frontend.'.$this->frontend_template_name.'.login.two_factor_auth', [
'title' => 'Login Enter 2FA Code',
])
->withErrors([
'Two Factor Authorization' => 'Your entered an incorrect two factor authorization code. Please try again.'
]);
}
// 2FA successful!
// Clear the user's 2FA code
$this->twoFactorAuthHelper->clearUserTwoFactorAuthFields($userId);
// Update the user's last_login fields
$this->twoFactorAuthHelper->updateUserRecordWithLastlogin($userId);
// Manually login user
Auth::loginUsingId($request->session()->get('user_id'));
// Clear the 'user_id' session variable
$this->twoFactorAuthHelper->clearUserIdSessionVar();
// Set the cookie, and onward and forward to the frontend!
// Ah ah ah! Instantiating a new response view and returning it is causing a message to display
// before the actual view is rendered. This message looks like cookie information, but it displays
// whether or not a cookie is created. So... I'm going to see if we need a cookie, and if not,
// return the view as usual.
if ((!$this->twoFactorAuthHelper->isCookieExists()) && (config('lasallecmsusermanagement.auth_2fa_cookie_enable'))) {
// Create the cookie...
$view = redirect()->intended($this->twoFactorAuthHelper->redirectPathUponSuccessfulFrontendLogin());
$response = new \Illuminate\Http\Response($view);
$response = $this->twoFactorAuthHelper->setCookie($response);
return $response;
}
// Oh, no cookie writing at all...
return redirect()->intended($this->twoFactorAuthHelper->redirectPathUponSuccessfulFrontendLogin());
} | php | public function post2FALogin(Request $request) {
$userId = $request->session()->get('user_id');
// Did the user take too much time to fill out the form?
if ($this->twoFactorAuthHelper->isTwoFactorAuthFormTimeout($userId)) {
return view('usermanagement::frontend.'.$this->frontend_template_name.'.login.login', [
'title' => 'Login',
])
->withErrors([
'Two Factor Authorization' => 'Your two factor authorization code expired. Please re-login.'
]);
}
// Is the code correct?
// If not, go back to the 2FA form with an error message
if (!$this->twoFactorAuthHelper->isInputtedTwoFactorAuthCodeCorrect($userId)) {
return view('usermanagement::frontend.'.$this->frontend_template_name.'.login.two_factor_auth', [
'title' => 'Login Enter 2FA Code',
])
->withErrors([
'Two Factor Authorization' => 'Your entered an incorrect two factor authorization code. Please try again.'
]);
}
// 2FA successful!
// Clear the user's 2FA code
$this->twoFactorAuthHelper->clearUserTwoFactorAuthFields($userId);
// Update the user's last_login fields
$this->twoFactorAuthHelper->updateUserRecordWithLastlogin($userId);
// Manually login user
Auth::loginUsingId($request->session()->get('user_id'));
// Clear the 'user_id' session variable
$this->twoFactorAuthHelper->clearUserIdSessionVar();
// Set the cookie, and onward and forward to the frontend!
// Ah ah ah! Instantiating a new response view and returning it is causing a message to display
// before the actual view is rendered. This message looks like cookie information, but it displays
// whether or not a cookie is created. So... I'm going to see if we need a cookie, and if not,
// return the view as usual.
if ((!$this->twoFactorAuthHelper->isCookieExists()) && (config('lasallecmsusermanagement.auth_2fa_cookie_enable'))) {
// Create the cookie...
$view = redirect()->intended($this->twoFactorAuthHelper->redirectPathUponSuccessfulFrontendLogin());
$response = new \Illuminate\Http\Response($view);
$response = $this->twoFactorAuthHelper->setCookie($response);
return $response;
}
// Oh, no cookie writing at all...
return redirect()->intended($this->twoFactorAuthHelper->redirectPathUponSuccessfulFrontendLogin());
} | [
"public",
"function",
"post2FALogin",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"userId",
"=",
"$",
"request",
"->",
"session",
"(",
")",
"->",
"get",
"(",
"'user_id'",
")",
";",
"// Did the user take too much time to fill out the form?",
"if",
"(",
"$",
"this",
"->",
"twoFactorAuthHelper",
"->",
"isTwoFactorAuthFormTimeout",
"(",
"$",
"userId",
")",
")",
"{",
"return",
"view",
"(",
"'usermanagement::frontend.'",
".",
"$",
"this",
"->",
"frontend_template_name",
".",
"'.login.login'",
",",
"[",
"'title'",
"=>",
"'Login'",
",",
"]",
")",
"->",
"withErrors",
"(",
"[",
"'Two Factor Authorization'",
"=>",
"'Your two factor authorization code expired. Please re-login.'",
"]",
")",
";",
"}",
"// Is the code correct?",
"// If not, go back to the 2FA form with an error message",
"if",
"(",
"!",
"$",
"this",
"->",
"twoFactorAuthHelper",
"->",
"isInputtedTwoFactorAuthCodeCorrect",
"(",
"$",
"userId",
")",
")",
"{",
"return",
"view",
"(",
"'usermanagement::frontend.'",
".",
"$",
"this",
"->",
"frontend_template_name",
".",
"'.login.two_factor_auth'",
",",
"[",
"'title'",
"=>",
"'Login Enter 2FA Code'",
",",
"]",
")",
"->",
"withErrors",
"(",
"[",
"'Two Factor Authorization'",
"=>",
"'Your entered an incorrect two factor authorization code. Please try again.'",
"]",
")",
";",
"}",
"// 2FA successful!",
"// Clear the user's 2FA code",
"$",
"this",
"->",
"twoFactorAuthHelper",
"->",
"clearUserTwoFactorAuthFields",
"(",
"$",
"userId",
")",
";",
"// Update the user's last_login fields",
"$",
"this",
"->",
"twoFactorAuthHelper",
"->",
"updateUserRecordWithLastlogin",
"(",
"$",
"userId",
")",
";",
"// Manually login user",
"Auth",
"::",
"loginUsingId",
"(",
"$",
"request",
"->",
"session",
"(",
")",
"->",
"get",
"(",
"'user_id'",
")",
")",
";",
"// Clear the 'user_id' session variable",
"$",
"this",
"->",
"twoFactorAuthHelper",
"->",
"clearUserIdSessionVar",
"(",
")",
";",
"// Set the cookie, and onward and forward to the frontend!",
"// Ah ah ah! Instantiating a new response view and returning it is causing a message to display",
"// before the actual view is rendered. This message looks like cookie information, but it displays",
"// whether or not a cookie is created. So... I'm going to see if we need a cookie, and if not,",
"// return the view as usual.",
"if",
"(",
"(",
"!",
"$",
"this",
"->",
"twoFactorAuthHelper",
"->",
"isCookieExists",
"(",
")",
")",
"&&",
"(",
"config",
"(",
"'lasallecmsusermanagement.auth_2fa_cookie_enable'",
")",
")",
")",
"{",
"// Create the cookie...",
"$",
"view",
"=",
"redirect",
"(",
")",
"->",
"intended",
"(",
"$",
"this",
"->",
"twoFactorAuthHelper",
"->",
"redirectPathUponSuccessfulFrontendLogin",
"(",
")",
")",
";",
"$",
"response",
"=",
"new",
"\\",
"Illuminate",
"\\",
"Http",
"\\",
"Response",
"(",
"$",
"view",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"twoFactorAuthHelper",
"->",
"setCookie",
"(",
"$",
"response",
")",
";",
"return",
"$",
"response",
";",
"}",
"// Oh, no cookie writing at all...",
"return",
"redirect",
"(",
")",
"->",
"intended",
"(",
"$",
"this",
"->",
"twoFactorAuthHelper",
"->",
"redirectPathUponSuccessfulFrontendLogin",
"(",
")",
")",
";",
"}"
] | Handle the front-end Two Factor Authorization login
@param \Illuminate\Http\Request $request
@return \Illuminate\Http\Response | [
"Handle",
"the",
"front",
"-",
"end",
"Two",
"Factor",
"Authorization",
"login"
] | b5203d596e18e2566e7fdcd3f13868bb44a94c1d | https://github.com/lasallecms/lasallecms-l5-usermanagement-pkg/blob/b5203d596e18e2566e7fdcd3f13868bb44a94c1d/src/Http/Controllers/Frontendauth/FrontendAuthController.php#L307-L365 | train |
xelax90/l2p-client | src/L2PClient/Client.php | Client.request | public function request($endpoint, $isPost = false, $params = array()){
$accessToken = $this->getAccessToken();
if($accessToken === null){
return null;
}
$params['accessToken'] = $accessToken->getAccessToken();
$url = $this->getConfig()->getApiUrl().$endpoint;
if(!$isPost){
$url .= '?'.http_build_query($params);
}
$ch = curl_init($url);
if($isPost){
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return array('output' => $output, 'code' => $httpcode);
} | php | public function request($endpoint, $isPost = false, $params = array()){
$accessToken = $this->getAccessToken();
if($accessToken === null){
return null;
}
$params['accessToken'] = $accessToken->getAccessToken();
$url = $this->getConfig()->getApiUrl().$endpoint;
if(!$isPost){
$url .= '?'.http_build_query($params);
}
$ch = curl_init($url);
if($isPost){
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return array('output' => $output, 'code' => $httpcode);
} | [
"public",
"function",
"request",
"(",
"$",
"endpoint",
",",
"$",
"isPost",
"=",
"false",
",",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"$",
"accessToken",
"=",
"$",
"this",
"->",
"getAccessToken",
"(",
")",
";",
"if",
"(",
"$",
"accessToken",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"$",
"params",
"[",
"'accessToken'",
"]",
"=",
"$",
"accessToken",
"->",
"getAccessToken",
"(",
")",
";",
"$",
"url",
"=",
"$",
"this",
"->",
"getConfig",
"(",
")",
"->",
"getApiUrl",
"(",
")",
".",
"$",
"endpoint",
";",
"if",
"(",
"!",
"$",
"isPost",
")",
"{",
"$",
"url",
".=",
"'?'",
".",
"http_build_query",
"(",
"$",
"params",
")",
";",
"}",
"$",
"ch",
"=",
"curl_init",
"(",
"$",
"url",
")",
";",
"if",
"(",
"$",
"isPost",
")",
"{",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_POST",
",",
"true",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_POSTFIELDS",
",",
"http_build_query",
"(",
"$",
"params",
")",
")",
";",
"}",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_RETURNTRANSFER",
",",
"1",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_TIMEOUT",
",",
"10",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_VERBOSE",
",",
"true",
")",
";",
"$",
"output",
"=",
"curl_exec",
"(",
"$",
"ch",
")",
";",
"$",
"httpcode",
"=",
"curl_getinfo",
"(",
"$",
"ch",
",",
"CURLINFO_HTTP_CODE",
")",
";",
"curl_close",
"(",
"$",
"ch",
")",
";",
"return",
"array",
"(",
"'output'",
"=>",
"$",
"output",
",",
"'code'",
"=>",
"$",
"httpcode",
")",
";",
"}"
] | Request an API endpoint with post or get method and given parameters. Returns null if no AccessToken is provided
@param string $endpoint
@param boolean $isPost
@param array $params
@return array|null | [
"Request",
"an",
"API",
"endpoint",
"with",
"post",
"or",
"get",
"method",
"and",
"given",
"parameters",
".",
"Returns",
"null",
"if",
"no",
"AccessToken",
"is",
"provided"
] | e4e53dfa1ee6e785acc4d3c632d3ebf70fe3d4fb | https://github.com/xelax90/l2p-client/blob/e4e53dfa1ee6e785acc4d3c632d3ebf70fe3d4fb/src/L2PClient/Client.php#L94-L118 | train |
OliverMonneke/pennePHP | src/Filesystem/Directory.php | Directory.evaluateDirectory | private function evaluateDirectory($directory = null)
{
$directory = $this->setDirectoryFallback($directory);
/** @noinspection PhpAssignmentInConditionInspection */
$this->run($directory);
} | php | private function evaluateDirectory($directory = null)
{
$directory = $this->setDirectoryFallback($directory);
/** @noinspection PhpAssignmentInConditionInspection */
$this->run($directory);
} | [
"private",
"function",
"evaluateDirectory",
"(",
"$",
"directory",
"=",
"null",
")",
"{",
"$",
"directory",
"=",
"$",
"this",
"->",
"setDirectoryFallback",
"(",
"$",
"directory",
")",
";",
"/** @noinspection PhpAssignmentInConditionInspection */",
"$",
"this",
"->",
"run",
"(",
"$",
"directory",
")",
";",
"}"
] | Walk through directory
@param string $directory Directory
@return void | [
"Walk",
"through",
"directory"
] | dd0de7944685a3f1947157e1254fc54b55ff9942 | https://github.com/OliverMonneke/pennePHP/blob/dd0de7944685a3f1947157e1254fc54b55ff9942/src/Filesystem/Directory.php#L82-L88 | train |
yvoyer/collection | lib/Star/Component/Collection/IdentityCollection.php | IdentityCollection.remove | public function remove($key)
{
if ($key instanceof UniqueId) {
$key = $key->id();
}
return $this->elements->remove($key);
} | php | public function remove($key)
{
if ($key instanceof UniqueId) {
$key = $key->id();
}
return $this->elements->remove($key);
} | [
"public",
"function",
"remove",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"$",
"key",
"instanceof",
"UniqueId",
")",
"{",
"$",
"key",
"=",
"$",
"key",
"->",
"id",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"elements",
"->",
"remove",
"(",
"$",
"key",
")",
";",
"}"
] | Removes the element at the specified index from the collection.
@param string|integer $key The kex/index of the element to remove.
@return mixed The removed element or NULL, if the collection did not contain the element. | [
"Removes",
"the",
"element",
"at",
"the",
"specified",
"index",
"from",
"the",
"collection",
"."
] | 08babb9996bece44e01aaa4d3b244bf48139c3ea | https://github.com/yvoyer/collection/blob/08babb9996bece44e01aaa4d3b244bf48139c3ea/lib/Star/Component/Collection/IdentityCollection.php#L116-L123 | train |
yvoyer/collection | lib/Star/Component/Collection/IdentityCollection.php | IdentityCollection.map | public function map(Closure $func)
{
return new static($this->type, $this->elements->map($func)->toArray());
} | php | public function map(Closure $func)
{
return new static($this->type, $this->elements->map($func)->toArray());
} | [
"public",
"function",
"map",
"(",
"Closure",
"$",
"func",
")",
"{",
"return",
"new",
"static",
"(",
"$",
"this",
"->",
"type",
",",
"$",
"this",
"->",
"elements",
"->",
"map",
"(",
"$",
"func",
")",
"->",
"toArray",
"(",
")",
")",
";",
"}"
] | Applies the given public function to each element in the collection and returns
a new collection with the elements returned by the public function.
@param Closure $func
@return Collection | [
"Applies",
"the",
"given",
"public",
"function",
"to",
"each",
"element",
"in",
"the",
"collection",
"and",
"returns",
"a",
"new",
"collection",
"with",
"the",
"elements",
"returned",
"by",
"the",
"public",
"function",
"."
] | 08babb9996bece44e01aaa4d3b244bf48139c3ea | https://github.com/yvoyer/collection/blob/08babb9996bece44e01aaa4d3b244bf48139c3ea/lib/Star/Component/Collection/IdentityCollection.php#L316-L319 | train |
comodojo/foundation | src/Comodojo/Foundation/Validation/DataValidation.php | DataValidation.validate | public static function validate($data, $type, callable $filter=null) {
$type = strtoupper($type);
if ( !array_key_exists($type, self::$supported_types) ) {
throw new UnexpectedValueException("Bad validation type");
}
return call_user_func(self::$supported_types[$type], $data, $filter);
} | php | public static function validate($data, $type, callable $filter=null) {
$type = strtoupper($type);
if ( !array_key_exists($type, self::$supported_types) ) {
throw new UnexpectedValueException("Bad validation type");
}
return call_user_func(self::$supported_types[$type], $data, $filter);
} | [
"public",
"static",
"function",
"validate",
"(",
"$",
"data",
",",
"$",
"type",
",",
"callable",
"$",
"filter",
"=",
"null",
")",
"{",
"$",
"type",
"=",
"strtoupper",
"(",
"$",
"type",
")",
";",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"type",
",",
"self",
"::",
"$",
"supported_types",
")",
")",
"{",
"throw",
"new",
"UnexpectedValueException",
"(",
"\"Bad validation type\"",
")",
";",
"}",
"return",
"call_user_func",
"(",
"self",
"::",
"$",
"supported_types",
"[",
"$",
"type",
"]",
",",
"$",
"data",
",",
"$",
"filter",
")",
";",
"}"
] | Generic validator.
@param mixed $data Data to validate
@param string $type Type (one of self::$supported_types)
@param callable $filter Custom filter
@return bool
@throws UnexpectedValueException | [
"Generic",
"validator",
"."
] | 21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a | https://github.com/comodojo/foundation/blob/21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a/src/Comodojo/Foundation/Validation/DataValidation.php#L69-L79 | train |
comodojo/foundation | src/Comodojo/Foundation/Validation/DataValidation.php | DataValidation.validateString | public static function validateString($data, callable $filter=null) {
if ( is_string($data) === false ) return false;
return self::applyFilter($data, $filter);
} | php | public static function validateString($data, callable $filter=null) {
if ( is_string($data) === false ) return false;
return self::applyFilter($data, $filter);
} | [
"public",
"static",
"function",
"validateString",
"(",
"$",
"data",
",",
"callable",
"$",
"filter",
"=",
"null",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"data",
")",
"===",
"false",
")",
"return",
"false",
";",
"return",
"self",
"::",
"applyFilter",
"(",
"$",
"data",
",",
"$",
"filter",
")",
";",
"}"
] | String validator.
@param mixed $data Data to validate
@param callable $filter Custom filter
@return bool | [
"String",
"validator",
"."
] | 21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a | https://github.com/comodojo/foundation/blob/21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a/src/Comodojo/Foundation/Validation/DataValidation.php#L88-L91 | train |
comodojo/foundation | src/Comodojo/Foundation/Validation/DataValidation.php | DataValidation.validateBoolean | public static function validateBoolean($data, callable $filter=null) {
if ( is_bool($data) === false ) return false;
return self::applyFilter($data, $filter);
} | php | public static function validateBoolean($data, callable $filter=null) {
if ( is_bool($data) === false ) return false;
return self::applyFilter($data, $filter);
} | [
"public",
"static",
"function",
"validateBoolean",
"(",
"$",
"data",
",",
"callable",
"$",
"filter",
"=",
"null",
")",
"{",
"if",
"(",
"is_bool",
"(",
"$",
"data",
")",
"===",
"false",
")",
"return",
"false",
";",
"return",
"self",
"::",
"applyFilter",
"(",
"$",
"data",
",",
"$",
"filter",
")",
";",
"}"
] | Bool validator.
@param mixed $data Data to validate
@param callable $filter Custom filter
@return bool | [
"Bool",
"validator",
"."
] | 21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a | https://github.com/comodojo/foundation/blob/21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a/src/Comodojo/Foundation/Validation/DataValidation.php#L100-L103 | train |
comodojo/foundation | src/Comodojo/Foundation/Validation/DataValidation.php | DataValidation.validateInteger | public static function validateInteger($data, callable $filter=null) {
if ( is_int($data) === false ) return false;
return self::applyFilter($data, $filter);
} | php | public static function validateInteger($data, callable $filter=null) {
if ( is_int($data) === false ) return false;
return self::applyFilter($data, $filter);
} | [
"public",
"static",
"function",
"validateInteger",
"(",
"$",
"data",
",",
"callable",
"$",
"filter",
"=",
"null",
")",
"{",
"if",
"(",
"is_int",
"(",
"$",
"data",
")",
"===",
"false",
")",
"return",
"false",
";",
"return",
"self",
"::",
"applyFilter",
"(",
"$",
"data",
",",
"$",
"filter",
")",
";",
"}"
] | Int validator.
@param mixed $data Data to validate
@param callable $filter Custom filter
@return bool | [
"Int",
"validator",
"."
] | 21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a | https://github.com/comodojo/foundation/blob/21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a/src/Comodojo/Foundation/Validation/DataValidation.php#L112-L115 | train |
comodojo/foundation | src/Comodojo/Foundation/Validation/DataValidation.php | DataValidation.validateNumeric | public static function validateNumeric($data, callable $filter=null) {
if ( is_numeric($data) === false ) return false;
return self::applyFilter($data, $filter);
} | php | public static function validateNumeric($data, callable $filter=null) {
if ( is_numeric($data) === false ) return false;
return self::applyFilter($data, $filter);
} | [
"public",
"static",
"function",
"validateNumeric",
"(",
"$",
"data",
",",
"callable",
"$",
"filter",
"=",
"null",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"data",
")",
"===",
"false",
")",
"return",
"false",
";",
"return",
"self",
"::",
"applyFilter",
"(",
"$",
"data",
",",
"$",
"filter",
")",
";",
"}"
] | Numeric validator.
@param mixed $data Data to validate
@param callable $filter Custom filter
@return bool | [
"Numeric",
"validator",
"."
] | 21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a | https://github.com/comodojo/foundation/blob/21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a/src/Comodojo/Foundation/Validation/DataValidation.php#L124-L127 | train |
comodojo/foundation | src/Comodojo/Foundation/Validation/DataValidation.php | DataValidation.validateFloat | public static function validateFloat($data, callable $filter=null) {
if ( is_float($data) === false ) return false;
return self::applyFilter($data, $filter);
} | php | public static function validateFloat($data, callable $filter=null) {
if ( is_float($data) === false ) return false;
return self::applyFilter($data, $filter);
} | [
"public",
"static",
"function",
"validateFloat",
"(",
"$",
"data",
",",
"callable",
"$",
"filter",
"=",
"null",
")",
"{",
"if",
"(",
"is_float",
"(",
"$",
"data",
")",
"===",
"false",
")",
"return",
"false",
";",
"return",
"self",
"::",
"applyFilter",
"(",
"$",
"data",
",",
"$",
"filter",
")",
";",
"}"
] | Float validator.
@param mixed $data Data to validate
@param callable $filter Custom filter
@return bool | [
"Float",
"validator",
"."
] | 21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a | https://github.com/comodojo/foundation/blob/21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a/src/Comodojo/Foundation/Validation/DataValidation.php#L136-L139 | train |
comodojo/foundation | src/Comodojo/Foundation/Validation/DataValidation.php | DataValidation.validateJson | public static function validateJson($data, callable $filter=null) {
$decoded = json_decode($data);
if ( is_null($decoded) ) return false;
return self::applyFilter($data, $filter);
} | php | public static function validateJson($data, callable $filter=null) {
$decoded = json_decode($data);
if ( is_null($decoded) ) return false;
return self::applyFilter($data, $filter);
} | [
"public",
"static",
"function",
"validateJson",
"(",
"$",
"data",
",",
"callable",
"$",
"filter",
"=",
"null",
")",
"{",
"$",
"decoded",
"=",
"json_decode",
"(",
"$",
"data",
")",
";",
"if",
"(",
"is_null",
"(",
"$",
"decoded",
")",
")",
"return",
"false",
";",
"return",
"self",
"::",
"applyFilter",
"(",
"$",
"data",
",",
"$",
"filter",
")",
";",
"}"
] | Json validator.
@param mixed $data Data to validate
@param callable $filter Custom filter
@return bool | [
"Json",
"validator",
"."
] | 21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a | https://github.com/comodojo/foundation/blob/21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a/src/Comodojo/Foundation/Validation/DataValidation.php#L148-L152 | train |
comodojo/foundation | src/Comodojo/Foundation/Validation/DataValidation.php | DataValidation.validateSerialized | public static function validateSerialized($data, callable $filter=null) {
$decoded = @unserialize($data);
if ( $decoded === false && $data != @serialize(false) ) return false;
return self::applyFilter($data, $filter);
} | php | public static function validateSerialized($data, callable $filter=null) {
$decoded = @unserialize($data);
if ( $decoded === false && $data != @serialize(false) ) return false;
return self::applyFilter($data, $filter);
} | [
"public",
"static",
"function",
"validateSerialized",
"(",
"$",
"data",
",",
"callable",
"$",
"filter",
"=",
"null",
")",
"{",
"$",
"decoded",
"=",
"@",
"unserialize",
"(",
"$",
"data",
")",
";",
"if",
"(",
"$",
"decoded",
"===",
"false",
"&&",
"$",
"data",
"!=",
"@",
"serialize",
"(",
"false",
")",
")",
"return",
"false",
";",
"return",
"self",
"::",
"applyFilter",
"(",
"$",
"data",
",",
"$",
"filter",
")",
";",
"}"
] | Serialized values validator.
@param mixed $data Data to validate
@param callable $filter Custom filter
@return bool | [
"Serialized",
"values",
"validator",
"."
] | 21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a | https://github.com/comodojo/foundation/blob/21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a/src/Comodojo/Foundation/Validation/DataValidation.php#L161-L165 | train |
comodojo/foundation | src/Comodojo/Foundation/Validation/DataValidation.php | DataValidation.validateDatetimeIso8601 | public static function validateDatetimeIso8601($data, callable $filter=null) {
if ( DateTime::createFromFormat(DateTime::ATOM, $data) === false ) return false;
return self::applyFilter($data, $filter);
} | php | public static function validateDatetimeIso8601($data, callable $filter=null) {
if ( DateTime::createFromFormat(DateTime::ATOM, $data) === false ) return false;
return self::applyFilter($data, $filter);
} | [
"public",
"static",
"function",
"validateDatetimeIso8601",
"(",
"$",
"data",
",",
"callable",
"$",
"filter",
"=",
"null",
")",
"{",
"if",
"(",
"DateTime",
"::",
"createFromFormat",
"(",
"DateTime",
"::",
"ATOM",
",",
"$",
"data",
")",
"===",
"false",
")",
"return",
"false",
";",
"return",
"self",
"::",
"applyFilter",
"(",
"$",
"data",
",",
"$",
"filter",
")",
";",
"}"
] | Iso8601-datetime validator.
@param mixed $data Data to validate
@param callable $filter Custom filter
@return bool | [
"Iso8601",
"-",
"datetime",
"validator",
"."
] | 21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a | https://github.com/comodojo/foundation/blob/21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a/src/Comodojo/Foundation/Validation/DataValidation.php#L201-L204 | train |
comodojo/foundation | src/Comodojo/Foundation/Validation/DataValidation.php | DataValidation.validateBase64 | public static function validateBase64($data, callable $filter=null) {
return base64_encode(base64_decode($data, true)) === $data ?
self::applyFilter($data, $filter)
: false;
} | php | public static function validateBase64($data, callable $filter=null) {
return base64_encode(base64_decode($data, true)) === $data ?
self::applyFilter($data, $filter)
: false;
} | [
"public",
"static",
"function",
"validateBase64",
"(",
"$",
"data",
",",
"callable",
"$",
"filter",
"=",
"null",
")",
"{",
"return",
"base64_encode",
"(",
"base64_decode",
"(",
"$",
"data",
",",
"true",
")",
")",
"===",
"$",
"data",
"?",
"self",
"::",
"applyFilter",
"(",
"$",
"data",
",",
"$",
"filter",
")",
":",
"false",
";",
"}"
] | Base64 validator.
@param mixed $data Data to validate
@param callable $filter Custom filter
@return bool | [
"Base64",
"validator",
"."
] | 21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a | https://github.com/comodojo/foundation/blob/21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a/src/Comodojo/Foundation/Validation/DataValidation.php#L213-L217 | train |
brunschgi/TerrificComposerBundle | DependencyInjection/TerrificComposerExtension.php | TerrificComposerExtension.load | public function load(array $configs, ContainerBuilder $container)
{
// Parse configuration
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
// Toolbar
$loader->load('toolbar.xml');
if ($config['toolbar'] === 'demo') {
$mode = ToolbarListener::DEMO;
}
else if ($config['toolbar']) {
$mode = ToolbarListener::ENABLED;
}
else {
$mode = ToolbarListener::DISABLED;
}
// Other Services
$loader->load('services.xml');
// Set parameter
$container->setParameter('terrific_composer.toolbar.mode', $mode);
$container->setParameter('terrific_composer.composition.bundles', $config['composition_bundles']);
$container->setParameter('terrific_composer.module.layout', $config['module_layout']);
$container->setParameter('terrific_composer.module.template', $config['module_template']);
} | php | public function load(array $configs, ContainerBuilder $container)
{
// Parse configuration
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
// Toolbar
$loader->load('toolbar.xml');
if ($config['toolbar'] === 'demo') {
$mode = ToolbarListener::DEMO;
}
else if ($config['toolbar']) {
$mode = ToolbarListener::ENABLED;
}
else {
$mode = ToolbarListener::DISABLED;
}
// Other Services
$loader->load('services.xml');
// Set parameter
$container->setParameter('terrific_composer.toolbar.mode', $mode);
$container->setParameter('terrific_composer.composition.bundles', $config['composition_bundles']);
$container->setParameter('terrific_composer.module.layout', $config['module_layout']);
$container->setParameter('terrific_composer.module.template', $config['module_template']);
} | [
"public",
"function",
"load",
"(",
"array",
"$",
"configs",
",",
"ContainerBuilder",
"$",
"container",
")",
"{",
"// Parse configuration",
"$",
"configuration",
"=",
"new",
"Configuration",
"(",
")",
";",
"$",
"config",
"=",
"$",
"this",
"->",
"processConfiguration",
"(",
"$",
"configuration",
",",
"$",
"configs",
")",
";",
"$",
"loader",
"=",
"new",
"XmlFileLoader",
"(",
"$",
"container",
",",
"new",
"FileLocator",
"(",
"__DIR__",
".",
"'/../Resources/config'",
")",
")",
";",
"// Toolbar",
"$",
"loader",
"->",
"load",
"(",
"'toolbar.xml'",
")",
";",
"if",
"(",
"$",
"config",
"[",
"'toolbar'",
"]",
"===",
"'demo'",
")",
"{",
"$",
"mode",
"=",
"ToolbarListener",
"::",
"DEMO",
";",
"}",
"else",
"if",
"(",
"$",
"config",
"[",
"'toolbar'",
"]",
")",
"{",
"$",
"mode",
"=",
"ToolbarListener",
"::",
"ENABLED",
";",
"}",
"else",
"{",
"$",
"mode",
"=",
"ToolbarListener",
"::",
"DISABLED",
";",
"}",
"// Other Services",
"$",
"loader",
"->",
"load",
"(",
"'services.xml'",
")",
";",
"// Set parameter",
"$",
"container",
"->",
"setParameter",
"(",
"'terrific_composer.toolbar.mode'",
",",
"$",
"mode",
")",
";",
"$",
"container",
"->",
"setParameter",
"(",
"'terrific_composer.composition.bundles'",
",",
"$",
"config",
"[",
"'composition_bundles'",
"]",
")",
";",
"$",
"container",
"->",
"setParameter",
"(",
"'terrific_composer.module.layout'",
",",
"$",
"config",
"[",
"'module_layout'",
"]",
")",
";",
"$",
"container",
"->",
"setParameter",
"(",
"'terrific_composer.module.template'",
",",
"$",
"config",
"[",
"'module_template'",
"]",
")",
";",
"}"
] | Loads the terrific composer configuration.
@param array $configs An array of configuration settings
@param ContainerBuilder $container A ContainerBuilder instance | [
"Loads",
"the",
"terrific",
"composer",
"configuration",
"."
] | 6eef4ace887c19ef166ab6654de385bc1ffbf5f1 | https://github.com/brunschgi/TerrificComposerBundle/blob/6eef4ace887c19ef166ab6654de385bc1ffbf5f1/DependencyInjection/TerrificComposerExtension.php#L39-L67 | train |
togucms/TemplateBundle | Compiler/Compiler.php | Compiler.parseFragment | protected function parseFragment($name) {
$fileName = $this->loader->findFilename($name);
$html5 = new HTML5();
$dom = $html5->loadHTMLFragment(file_get_contents($fileName));
if($html5->getErrors()) {
$errors = "";
foreach($html5->getErrors() as $error) {
$errors .= "\n". $error;
}
throw new \Exception("Parsing error for template " . $name . " Errors: " . $errors);
}
return $dom;
} | php | protected function parseFragment($name) {
$fileName = $this->loader->findFilename($name);
$html5 = new HTML5();
$dom = $html5->loadHTMLFragment(file_get_contents($fileName));
if($html5->getErrors()) {
$errors = "";
foreach($html5->getErrors() as $error) {
$errors .= "\n". $error;
}
throw new \Exception("Parsing error for template " . $name . " Errors: " . $errors);
}
return $dom;
} | [
"protected",
"function",
"parseFragment",
"(",
"$",
"name",
")",
"{",
"$",
"fileName",
"=",
"$",
"this",
"->",
"loader",
"->",
"findFilename",
"(",
"$",
"name",
")",
";",
"$",
"html5",
"=",
"new",
"HTML5",
"(",
")",
";",
"$",
"dom",
"=",
"$",
"html5",
"->",
"loadHTMLFragment",
"(",
"file_get_contents",
"(",
"$",
"fileName",
")",
")",
";",
"if",
"(",
"$",
"html5",
"->",
"getErrors",
"(",
")",
")",
"{",
"$",
"errors",
"=",
"\"\"",
";",
"foreach",
"(",
"$",
"html5",
"->",
"getErrors",
"(",
")",
"as",
"$",
"error",
")",
"{",
"$",
"errors",
".=",
"\"\\n\"",
".",
"$",
"error",
";",
"}",
"throw",
"new",
"\\",
"Exception",
"(",
"\"Parsing error for template \"",
".",
"$",
"name",
".",
"\" Errors: \"",
".",
"$",
"errors",
")",
";",
"}",
"return",
"$",
"dom",
";",
"}"
] | Parses an HTML Togu component
@param string $name
@return HTML5 The parsed DOM | [
"Parses",
"an",
"HTML",
"Togu",
"component"
] | b07d3bff948d547e95f81154503dfa3a333eef64 | https://github.com/togucms/TemplateBundle/blob/b07d3bff948d547e95f81154503dfa3a333eef64/Compiler/Compiler.php#L108-L122 | train |
Aviogram/Common | src/StringUtils.php | StringUtils.underscoreToCamelCase | public static function underscoreToCamelCase($string)
{
static $cache = array();
if (array_key_exists($string, $cache) == true) {
return $cache[$string];
}
$replacer = function(array $matches) {
return strtoupper($matches[1]);
};
return $cache[$string] = preg_replace_callback('/_(.?)/', $replacer, $string);
} | php | public static function underscoreToCamelCase($string)
{
static $cache = array();
if (array_key_exists($string, $cache) == true) {
return $cache[$string];
}
$replacer = function(array $matches) {
return strtoupper($matches[1]);
};
return $cache[$string] = preg_replace_callback('/_(.?)/', $replacer, $string);
} | [
"public",
"static",
"function",
"underscoreToCamelCase",
"(",
"$",
"string",
")",
"{",
"static",
"$",
"cache",
"=",
"array",
"(",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"string",
",",
"$",
"cache",
")",
"==",
"true",
")",
"{",
"return",
"$",
"cache",
"[",
"$",
"string",
"]",
";",
"}",
"$",
"replacer",
"=",
"function",
"(",
"array",
"$",
"matches",
")",
"{",
"return",
"strtoupper",
"(",
"$",
"matches",
"[",
"1",
"]",
")",
";",
"}",
";",
"return",
"$",
"cache",
"[",
"$",
"string",
"]",
"=",
"preg_replace_callback",
"(",
"'/_(.?)/'",
",",
"$",
"replacer",
",",
"$",
"string",
")",
";",
"}"
] | Convert a underscore defined string to his camelCase format
@param string $string
@return string | [
"Convert",
"a",
"underscore",
"defined",
"string",
"to",
"his",
"camelCase",
"format"
] | bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5 | https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/StringUtils.php#L25-L38 | train |
Aviogram/Common | src/StringUtils.php | StringUtils.camelCaseToUnderscore | public static function camelCaseToUnderscore($string)
{
static $cache = array();
if (array_key_exists($string, $cache) === true) {
return $cache[$string];
}
$replacer = function(array $matches) {
return '_' . strtolower($matches[0]);
};
return $cache[$string] = preg_replace_callback('/[A-Z]/', $replacer, $string);
} | php | public static function camelCaseToUnderscore($string)
{
static $cache = array();
if (array_key_exists($string, $cache) === true) {
return $cache[$string];
}
$replacer = function(array $matches) {
return '_' . strtolower($matches[0]);
};
return $cache[$string] = preg_replace_callback('/[A-Z]/', $replacer, $string);
} | [
"public",
"static",
"function",
"camelCaseToUnderscore",
"(",
"$",
"string",
")",
"{",
"static",
"$",
"cache",
"=",
"array",
"(",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"string",
",",
"$",
"cache",
")",
"===",
"true",
")",
"{",
"return",
"$",
"cache",
"[",
"$",
"string",
"]",
";",
"}",
"$",
"replacer",
"=",
"function",
"(",
"array",
"$",
"matches",
")",
"{",
"return",
"'_'",
".",
"strtolower",
"(",
"$",
"matches",
"[",
"0",
"]",
")",
";",
"}",
";",
"return",
"$",
"cache",
"[",
"$",
"string",
"]",
"=",
"preg_replace_callback",
"(",
"'/[A-Z]/'",
",",
"$",
"replacer",
",",
"$",
"string",
")",
";",
"}"
] | Convert a camelCased defined string to his underscore format
@param string $string
@return string | [
"Convert",
"a",
"camelCased",
"defined",
"string",
"to",
"his",
"underscore",
"format"
] | bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5 | https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/StringUtils.php#L59-L72 | train |
OUTRAGElib/psr7-file-stream | lib/File.php | File.setStream | public function setStream(PsrStreamInterface $stream)
{
$this->stream = $stream;
$this->error = UPLOAD_ERR_OK;
return true;
} | php | public function setStream(PsrStreamInterface $stream)
{
$this->stream = $stream;
$this->error = UPLOAD_ERR_OK;
return true;
} | [
"public",
"function",
"setStream",
"(",
"PsrStreamInterface",
"$",
"stream",
")",
"{",
"$",
"this",
"->",
"stream",
"=",
"$",
"stream",
";",
"$",
"this",
"->",
"error",
"=",
"UPLOAD_ERR_OK",
";",
"return",
"true",
";",
"}"
] | Set the stream which this uploaded file refers to. | [
"Set",
"the",
"stream",
"which",
"this",
"uploaded",
"file",
"refers",
"to",
"."
] | 8da9ecad1e4190f31f8776aeadd9c7db41107f68 | https://github.com/OUTRAGElib/psr7-file-stream/blob/8da9ecad1e4190f31f8776aeadd9c7db41107f68/lib/File.php#L40-L46 | train |
wasinger/adaptimage | src/AdaptiveImageResizer.php | AdaptiveImageResizer.addImageSizeDefinition | public function addImageSizeDefinition(ImageResizeDefinition $ird)
{
$this->image_resize_definitions[$ird->getWidth()] = $ird;
ksort($this->image_resize_definitions);
} | php | public function addImageSizeDefinition(ImageResizeDefinition $ird)
{
$this->image_resize_definitions[$ird->getWidth()] = $ird;
ksort($this->image_resize_definitions);
} | [
"public",
"function",
"addImageSizeDefinition",
"(",
"ImageResizeDefinition",
"$",
"ird",
")",
"{",
"$",
"this",
"->",
"image_resize_definitions",
"[",
"$",
"ird",
"->",
"getWidth",
"(",
")",
"]",
"=",
"$",
"ird",
";",
"ksort",
"(",
"$",
"this",
"->",
"image_resize_definitions",
")",
";",
"}"
] | Add another allowed image size
@param ImageResizeDefinition $ird | [
"Add",
"another",
"allowed",
"image",
"size"
] | 7b529b25081b399451c8bbd56d0cef7daaa83ec4 | https://github.com/wasinger/adaptimage/blob/7b529b25081b399451c8bbd56d0cef7daaa83ec4/src/AdaptiveImageResizer.php#L44-L48 | train |
wasinger/adaptimage | src/AdaptiveImageResizer.php | AdaptiveImageResizer.getImageResizeDefinitionForWidth | public function getImageResizeDefinitionForWidth($width, $fit_in_width = false)
{
if (empty($this->image_resize_definitions)) { // no image sizes defined
return null;
}
if ($fit_in_width) {
foreach ($this->image_resize_definitions as $w => $ird) {
if ($w > $width && isset($prev_ird)) {
return $prev_ird;
} elseif ($w >= $width) {
return $ird; // return smallest possible value even if it is greater than required
}
$prev_ird = $ird;
}
return $ird; // return greatest available value
} else {
foreach ($this->image_resize_definitions as $w => $ird) {
if ($w >= $width) {
return $ird;
}
}
return $ird; // return greatest available value
}
} | php | public function getImageResizeDefinitionForWidth($width, $fit_in_width = false)
{
if (empty($this->image_resize_definitions)) { // no image sizes defined
return null;
}
if ($fit_in_width) {
foreach ($this->image_resize_definitions as $w => $ird) {
if ($w > $width && isset($prev_ird)) {
return $prev_ird;
} elseif ($w >= $width) {
return $ird; // return smallest possible value even if it is greater than required
}
$prev_ird = $ird;
}
return $ird; // return greatest available value
} else {
foreach ($this->image_resize_definitions as $w => $ird) {
if ($w >= $width) {
return $ird;
}
}
return $ird; // return greatest available value
}
} | [
"public",
"function",
"getImageResizeDefinitionForWidth",
"(",
"$",
"width",
",",
"$",
"fit_in_width",
"=",
"false",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"image_resize_definitions",
")",
")",
"{",
"// no image sizes defined",
"return",
"null",
";",
"}",
"if",
"(",
"$",
"fit_in_width",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"image_resize_definitions",
"as",
"$",
"w",
"=>",
"$",
"ird",
")",
"{",
"if",
"(",
"$",
"w",
">",
"$",
"width",
"&&",
"isset",
"(",
"$",
"prev_ird",
")",
")",
"{",
"return",
"$",
"prev_ird",
";",
"}",
"elseif",
"(",
"$",
"w",
">=",
"$",
"width",
")",
"{",
"return",
"$",
"ird",
";",
"// return smallest possible value even if it is greater than required",
"}",
"$",
"prev_ird",
"=",
"$",
"ird",
";",
"}",
"return",
"$",
"ird",
";",
"// return greatest available value",
"}",
"else",
"{",
"foreach",
"(",
"$",
"this",
"->",
"image_resize_definitions",
"as",
"$",
"w",
"=>",
"$",
"ird",
")",
"{",
"if",
"(",
"$",
"w",
">=",
"$",
"width",
")",
"{",
"return",
"$",
"ird",
";",
"}",
"}",
"return",
"$",
"ird",
";",
"// return greatest available value",
"}",
"}"
] | Get nearest available ImageSizeDefinition for given screen width
@param int $width
@param boolean $fit_in_width If false, returns ImageSizeDefinition greater than width; if true, returns ImageSizeDefinition smaller than width
@return ImageResizeDefinition|null Matching ImageSizeDefinition or NULL if no ImageSizeDefinitions available | [
"Get",
"nearest",
"available",
"ImageSizeDefinition",
"for",
"given",
"screen",
"width"
] | 7b529b25081b399451c8bbd56d0cef7daaa83ec4 | https://github.com/wasinger/adaptimage/blob/7b529b25081b399451c8bbd56d0cef7daaa83ec4/src/AdaptiveImageResizer.php#L57-L81 | train |
flipbox/spark | src/services/Element.php | Element.isCachedById | protected function isCachedById(int $id, int $siteId = null)
{
// Resolve siteId
$siteId = SiteHelper::resolveSiteId($siteId);
if (!isset($this->cacheById[$siteId])) {
$this->cacheById[$siteId] = [];
}
return array_key_exists($id, $this->cacheById[$siteId]);
} | php | protected function isCachedById(int $id, int $siteId = null)
{
// Resolve siteId
$siteId = SiteHelper::resolveSiteId($siteId);
if (!isset($this->cacheById[$siteId])) {
$this->cacheById[$siteId] = [];
}
return array_key_exists($id, $this->cacheById[$siteId]);
} | [
"protected",
"function",
"isCachedById",
"(",
"int",
"$",
"id",
",",
"int",
"$",
"siteId",
"=",
"null",
")",
"{",
"// Resolve siteId",
"$",
"siteId",
"=",
"SiteHelper",
"::",
"resolveSiteId",
"(",
"$",
"siteId",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"cacheById",
"[",
"$",
"siteId",
"]",
")",
")",
"{",
"$",
"this",
"->",
"cacheById",
"[",
"$",
"siteId",
"]",
"=",
"[",
"]",
";",
"}",
"return",
"array_key_exists",
"(",
"$",
"id",
",",
"$",
"this",
"->",
"cacheById",
"[",
"$",
"siteId",
"]",
")",
";",
"}"
] | Identify whether in cached by ID
@param int $id
@param int|null $siteId
@return bool | [
"Identify",
"whether",
"in",
"cached",
"by",
"ID"
] | 9d75fd3d95744b9c9187921c4f3b9eea42c035d4 | https://github.com/flipbox/spark/blob/9d75fd3d95744b9c9187921c4f3b9eea42c035d4/src/services/Element.php#L276-L286 | train |
andela-doladosu/liteorm | src/Origins/Connection.php | Connection.getEnv | public static function getEnv()
{
if (null !== (getenv('P_DRIVER'))) {
$dotEnv = new Dotenv($_SERVER['DOCUMENT_ROOT']);
$dotEnv->load();
}
self::$driver = getenv('P_DRIVER');
self::$host = getenv('P_HOST');
self::$dbname = getenv('P_DBNAME');
self::$user = getenv('P_USER');
self::$pass = getenv('P_PASS');
} | php | public static function getEnv()
{
if (null !== (getenv('P_DRIVER'))) {
$dotEnv = new Dotenv($_SERVER['DOCUMENT_ROOT']);
$dotEnv->load();
}
self::$driver = getenv('P_DRIVER');
self::$host = getenv('P_HOST');
self::$dbname = getenv('P_DBNAME');
self::$user = getenv('P_USER');
self::$pass = getenv('P_PASS');
} | [
"public",
"static",
"function",
"getEnv",
"(",
")",
"{",
"if",
"(",
"null",
"!==",
"(",
"getenv",
"(",
"'P_DRIVER'",
")",
")",
")",
"{",
"$",
"dotEnv",
"=",
"new",
"Dotenv",
"(",
"$",
"_SERVER",
"[",
"'DOCUMENT_ROOT'",
"]",
")",
";",
"$",
"dotEnv",
"->",
"load",
"(",
")",
";",
"}",
"self",
"::",
"$",
"driver",
"=",
"getenv",
"(",
"'P_DRIVER'",
")",
";",
"self",
"::",
"$",
"host",
"=",
"getenv",
"(",
"'P_HOST'",
")",
";",
"self",
"::",
"$",
"dbname",
"=",
"getenv",
"(",
"'P_DBNAME'",
")",
";",
"self",
"::",
"$",
"user",
"=",
"getenv",
"(",
"'P_USER'",
")",
";",
"self",
"::",
"$",
"pass",
"=",
"getenv",
"(",
"'P_PASS'",
")",
";",
"}"
] | Get environment values from .env file
@return null | [
"Get",
"environment",
"values",
"from",
".",
"env",
"file"
] | e97f69e20be4ce0c078a0c25a9a777307d85e9e4 | https://github.com/andela-doladosu/liteorm/blob/e97f69e20be4ce0c078a0c25a9a777307d85e9e4/src/Origins/Connection.php#L28-L41 | train |
andela-doladosu/liteorm | src/Origins/Connection.php | Connection.connect | public static function connect()
{
self::getEnv();
return new PDO(self::$driver.':host='.self::$host.';dbname='.self::$dbname, self::$user, self::$pass);
} | php | public static function connect()
{
self::getEnv();
return new PDO(self::$driver.':host='.self::$host.';dbname='.self::$dbname, self::$user, self::$pass);
} | [
"public",
"static",
"function",
"connect",
"(",
")",
"{",
"self",
"::",
"getEnv",
"(",
")",
";",
"return",
"new",
"PDO",
"(",
"self",
"::",
"$",
"driver",
".",
"':host='",
".",
"self",
"::",
"$",
"host",
".",
"';dbname='",
".",
"self",
"::",
"$",
"dbname",
",",
"self",
"::",
"$",
"user",
",",
"self",
"::",
"$",
"pass",
")",
";",
"}"
] | Create PDO connections
@return PDO | [
"Create",
"PDO",
"connections"
] | e97f69e20be4ce0c078a0c25a9a777307d85e9e4 | https://github.com/andela-doladosu/liteorm/blob/e97f69e20be4ce0c078a0c25a9a777307d85e9e4/src/Origins/Connection.php#L48-L52 | train |
cloudtek/dynamodm | lib/Cloudtek/DynamoDM/Mapping/Driver/AnnotationDriver.php | AnnotationDriver.propertyNeedsMapping | private function propertyNeedsMapping(ClassMetadata $class, \ReflectionProperty $property)
{
if ($class->isMappedSuperclass && !$property->isPrivate()) {
return false;
}
$inherited = $class->hasAttribute($property->name) && $class->getPropertyMetadata($property->name)->isInherited;
return !$inherited || $property->getDeclaringClass()->name === $class->name;
} | php | private function propertyNeedsMapping(ClassMetadata $class, \ReflectionProperty $property)
{
if ($class->isMappedSuperclass && !$property->isPrivate()) {
return false;
}
$inherited = $class->hasAttribute($property->name) && $class->getPropertyMetadata($property->name)->isInherited;
return !$inherited || $property->getDeclaringClass()->name === $class->name;
} | [
"private",
"function",
"propertyNeedsMapping",
"(",
"ClassMetadata",
"$",
"class",
",",
"\\",
"ReflectionProperty",
"$",
"property",
")",
"{",
"if",
"(",
"$",
"class",
"->",
"isMappedSuperclass",
"&&",
"!",
"$",
"property",
"->",
"isPrivate",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"inherited",
"=",
"$",
"class",
"->",
"hasAttribute",
"(",
"$",
"property",
"->",
"name",
")",
"&&",
"$",
"class",
"->",
"getPropertyMetadata",
"(",
"$",
"property",
"->",
"name",
")",
"->",
"isInherited",
";",
"return",
"!",
"$",
"inherited",
"||",
"$",
"property",
"->",
"getDeclaringClass",
"(",
")",
"->",
"name",
"===",
"$",
"class",
"->",
"name",
";",
"}"
] | Check if the specified property needs to be mapped.
For superclasses, mapping is handled at the child class level except in case
of private properties. For inheritance, it's handled by the declaring class.
@param ClassMetadata $class
@param \ReflectionProperty $property
@return bool
@todo move to ClassMetadataFactory? | [
"Check",
"if",
"the",
"specified",
"property",
"needs",
"to",
"be",
"mapped",
"."
] | 119d355e2c5cbaef1f867970349b4432f5704fcd | https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/Mapping/Driver/AnnotationDriver.php#L308-L317 | train |
bkstg/schedule-bundle | Entity/Schedule.php | Schedule.removeGroup | public function removeGroup(GroupInterface $group): void
{
if (!$group instanceof Production) {
throw new Exception('Group type not supported.');
}
$this->groups->removeElement($group);
} | php | public function removeGroup(GroupInterface $group): void
{
if (!$group instanceof Production) {
throw new Exception('Group type not supported.');
}
$this->groups->removeElement($group);
} | [
"public",
"function",
"removeGroup",
"(",
"GroupInterface",
"$",
"group",
")",
":",
"void",
"{",
"if",
"(",
"!",
"$",
"group",
"instanceof",
"Production",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Group type not supported.'",
")",
";",
"}",
"$",
"this",
"->",
"groups",
"->",
"removeElement",
"(",
"$",
"group",
")",
";",
"}"
] | Remove group.
@param Production $group The group to remove.
@return void | [
"Remove",
"group",
"."
] | e64ac897aa7b28bc48319470d65de13cd4788afe | https://github.com/bkstg/schedule-bundle/blob/e64ac897aa7b28bc48319470d65de13cd4788afe/Entity/Schedule.php#L294-L300 | train |
bkstg/schedule-bundle | Entity/Schedule.php | Schedule.addEvent | public function addEvent(Event $event): self
{
$event->setSchedule($this);
$this->events[] = $event;
return $this;
} | php | public function addEvent(Event $event): self
{
$event->setSchedule($this);
$this->events[] = $event;
return $this;
} | [
"public",
"function",
"addEvent",
"(",
"Event",
"$",
"event",
")",
":",
"self",
"{",
"$",
"event",
"->",
"setSchedule",
"(",
"$",
"this",
")",
";",
"$",
"this",
"->",
"events",
"[",
"]",
"=",
"$",
"event",
";",
"return",
"$",
"this",
";",
"}"
] | Add event.
@param Event $event The event to add.
@return self | [
"Add",
"event",
"."
] | e64ac897aa7b28bc48319470d65de13cd4788afe | https://github.com/bkstg/schedule-bundle/blob/e64ac897aa7b28bc48319470d65de13cd4788afe/Entity/Schedule.php#L337-L343 | train |
bkstg/schedule-bundle | Entity/Schedule.php | Schedule.getStart | public function getStart(): ?\DateTimeInterface
{
$lowest_date = null;
foreach ($this->events as $event) {
if (null === $lowest_date || $event->getStart() < $lowest_date) {
$lowest_date = $event->getStart();
}
}
return $lowest_date;
} | php | public function getStart(): ?\DateTimeInterface
{
$lowest_date = null;
foreach ($this->events as $event) {
if (null === $lowest_date || $event->getStart() < $lowest_date) {
$lowest_date = $event->getStart();
}
}
return $lowest_date;
} | [
"public",
"function",
"getStart",
"(",
")",
":",
"?",
"\\",
"DateTimeInterface",
"{",
"$",
"lowest_date",
"=",
"null",
";",
"foreach",
"(",
"$",
"this",
"->",
"events",
"as",
"$",
"event",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"lowest_date",
"||",
"$",
"event",
"->",
"getStart",
"(",
")",
"<",
"$",
"lowest_date",
")",
"{",
"$",
"lowest_date",
"=",
"$",
"event",
"->",
"getStart",
"(",
")",
";",
"}",
"}",
"return",
"$",
"lowest_date",
";",
"}"
] | Get the start date of the schedule.
@return ?\DateTimeInterface | [
"Get",
"the",
"start",
"date",
"of",
"the",
"schedule",
"."
] | e64ac897aa7b28bc48319470d65de13cd4788afe | https://github.com/bkstg/schedule-bundle/blob/e64ac897aa7b28bc48319470d65de13cd4788afe/Entity/Schedule.php#L372-L382 | train |
bkstg/schedule-bundle | Entity/Schedule.php | Schedule.getEnd | public function getEnd(): ?\DateTimeInterface
{
$highest_date = null;
foreach ($this->events as $event) {
if (null === $highest_date || $event->getEnd() > $highest_date) {
$highest_date = $event->getEnd();
}
}
return $highest_date;
} | php | public function getEnd(): ?\DateTimeInterface
{
$highest_date = null;
foreach ($this->events as $event) {
if (null === $highest_date || $event->getEnd() > $highest_date) {
$highest_date = $event->getEnd();
}
}
return $highest_date;
} | [
"public",
"function",
"getEnd",
"(",
")",
":",
"?",
"\\",
"DateTimeInterface",
"{",
"$",
"highest_date",
"=",
"null",
";",
"foreach",
"(",
"$",
"this",
"->",
"events",
"as",
"$",
"event",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"highest_date",
"||",
"$",
"event",
"->",
"getEnd",
"(",
")",
">",
"$",
"highest_date",
")",
"{",
"$",
"highest_date",
"=",
"$",
"event",
"->",
"getEnd",
"(",
")",
";",
"}",
"}",
"return",
"$",
"highest_date",
";",
"}"
] | Get the end date of the schedule.
@return ?\DateTimeInterface | [
"Get",
"the",
"end",
"date",
"of",
"the",
"schedule",
"."
] | e64ac897aa7b28bc48319470d65de13cd4788afe | https://github.com/bkstg/schedule-bundle/blob/e64ac897aa7b28bc48319470d65de13cd4788afe/Entity/Schedule.php#L389-L399 | train |
staticka/staticka | src/Matter.php | Matter.parse | public static function parse($content)
{
$matter = array();
$text = str_replace(PHP_EOL, $id = uniqid(), $content);
$regex = '/^---' . $id . '(.*?)' . $id . '---/';
if (preg_match($regex, $text, $matches) === 1) {
$yaml = str_replace($id, PHP_EOL, $matches[1]);
$matter = (array) Yaml::parse(trim($yaml));
$body = str_replace($matches[0], '', $text);
$content = str_replace($id, PHP_EOL, $body);
}
return array($matter, (string) trim($content));
} | php | public static function parse($content)
{
$matter = array();
$text = str_replace(PHP_EOL, $id = uniqid(), $content);
$regex = '/^---' . $id . '(.*?)' . $id . '---/';
if (preg_match($regex, $text, $matches) === 1) {
$yaml = str_replace($id, PHP_EOL, $matches[1]);
$matter = (array) Yaml::parse(trim($yaml));
$body = str_replace($matches[0], '', $text);
$content = str_replace($id, PHP_EOL, $body);
}
return array($matter, (string) trim($content));
} | [
"public",
"static",
"function",
"parse",
"(",
"$",
"content",
")",
"{",
"$",
"matter",
"=",
"array",
"(",
")",
";",
"$",
"text",
"=",
"str_replace",
"(",
"PHP_EOL",
",",
"$",
"id",
"=",
"uniqid",
"(",
")",
",",
"$",
"content",
")",
";",
"$",
"regex",
"=",
"'/^---'",
".",
"$",
"id",
".",
"'(.*?)'",
".",
"$",
"id",
".",
"'---/'",
";",
"if",
"(",
"preg_match",
"(",
"$",
"regex",
",",
"$",
"text",
",",
"$",
"matches",
")",
"===",
"1",
")",
"{",
"$",
"yaml",
"=",
"str_replace",
"(",
"$",
"id",
",",
"PHP_EOL",
",",
"$",
"matches",
"[",
"1",
"]",
")",
";",
"$",
"matter",
"=",
"(",
"array",
")",
"Yaml",
"::",
"parse",
"(",
"trim",
"(",
"$",
"yaml",
")",
")",
";",
"$",
"body",
"=",
"str_replace",
"(",
"$",
"matches",
"[",
"0",
"]",
",",
"''",
",",
"$",
"text",
")",
";",
"$",
"content",
"=",
"str_replace",
"(",
"$",
"id",
",",
"PHP_EOL",
",",
"$",
"body",
")",
";",
"}",
"return",
"array",
"(",
"$",
"matter",
",",
"(",
"string",
")",
"trim",
"(",
"$",
"content",
")",
")",
";",
"}"
] | Retrieves the contents from a YAML format.
@param string $content
@return array | [
"Retrieves",
"the",
"contents",
"from",
"a",
"YAML",
"format",
"."
] | 6e3b814c391ed03b0bd409803e11579bae677ce4 | https://github.com/staticka/staticka/blob/6e3b814c391ed03b0bd409803e11579bae677ce4/src/Matter.php#L21-L40 | train |
sndsgd/sndsgd-field | src/field/Error.php | Error.setValue | public function setValue($value)
{
if (is_string($value) && strlen($value) > 100) {
$value = substr($value, 0, 96).'...';
}
$this->value = $value;
} | php | public function setValue($value)
{
if (is_string($value) && strlen($value) > 100) {
$value = substr($value, 0, 96).'...';
}
$this->value = $value;
} | [
"public",
"function",
"setValue",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
"&&",
"strlen",
"(",
"$",
"value",
")",
">",
"100",
")",
"{",
"$",
"value",
"=",
"substr",
"(",
"$",
"value",
",",
"0",
",",
"96",
")",
".",
"'...'",
";",
"}",
"$",
"this",
"->",
"value",
"=",
"$",
"value",
";",
"}"
] | Set the value in the field that failed to validate
@param mixed $value | [
"Set",
"the",
"value",
"in",
"the",
"field",
"that",
"failed",
"to",
"validate"
] | 34ac3aabfe031bd9b259b3b93e84964b04031334 | https://github.com/sndsgd/sndsgd-field/blob/34ac3aabfe031bd9b259b3b93e84964b04031334/src/field/Error.php#L107-L113 | train |
prolic/HumusMvc | src/HumusMvc/MvcEvent.php | MvcEvent.setApplication | public function setApplication(ApplicationInterface $application)
{
$this->setParam('application', $application);
$this->application = $application;
return $this;
} | php | public function setApplication(ApplicationInterface $application)
{
$this->setParam('application', $application);
$this->application = $application;
return $this;
} | [
"public",
"function",
"setApplication",
"(",
"ApplicationInterface",
"$",
"application",
")",
"{",
"$",
"this",
"->",
"setParam",
"(",
"'application'",
",",
"$",
"application",
")",
";",
"$",
"this",
"->",
"application",
"=",
"$",
"application",
";",
"return",
"$",
"this",
";",
"}"
] | Set application instance
@param ApplicationInterface $application
@return MvcEvent | [
"Set",
"application",
"instance"
] | 09e8c6422d84b57745cc643047e10761be2a21a7 | https://github.com/prolic/HumusMvc/blob/09e8c6422d84b57745cc643047e10761be2a21a7/src/HumusMvc/MvcEvent.php#L69-L74 | train |
agentmedia/phine-builtin | src/BuiltIn/Modules/Backend/ChangePasswordConfirmForm.php | ChangePasswordConfirmForm.Wordings | protected function Wordings()
{
$result = array();
$result[] = 'Success';
$result[] = 'Error';
$result[] = 'Password';
$result[] = 'Password.Validation.Required.Missing';
$result[] = 'PasswordRepeat';
$result[] = 'PasswordRepeat.Validation.Required.Missing';
$result[] = 'PasswordRepeat.Validation.CompareCheck.EqualsNot_{0}';
$result[] = 'PasswordChangeSubmit';
return $result;
} | php | protected function Wordings()
{
$result = array();
$result[] = 'Success';
$result[] = 'Error';
$result[] = 'Password';
$result[] = 'Password.Validation.Required.Missing';
$result[] = 'PasswordRepeat';
$result[] = 'PasswordRepeat.Validation.Required.Missing';
$result[] = 'PasswordRepeat.Validation.CompareCheck.EqualsNot_{0}';
$result[] = 'PasswordChangeSubmit';
return $result;
} | [
"protected",
"function",
"Wordings",
"(",
")",
"{",
"$",
"result",
"=",
"array",
"(",
")",
";",
"$",
"result",
"[",
"]",
"=",
"'Success'",
";",
"$",
"result",
"[",
"]",
"=",
"'Error'",
";",
"$",
"result",
"[",
"]",
"=",
"'Password'",
";",
"$",
"result",
"[",
"]",
"=",
"'Password.Validation.Required.Missing'",
";",
"$",
"result",
"[",
"]",
"=",
"'PasswordRepeat'",
";",
"$",
"result",
"[",
"]",
"=",
"'PasswordRepeat.Validation.Required.Missing'",
";",
"$",
"result",
"[",
"]",
"=",
"'PasswordRepeat.Validation.CompareCheck.EqualsNot_{0}'",
";",
"$",
"result",
"[",
"]",
"=",
"'PasswordChangeSubmit'",
";",
"return",
"$",
"result",
";",
"}"
] | Returns the wording labels for success and error
@return string[] Returns the wording labels | [
"Returns",
"the",
"wording",
"labels",
"for",
"success",
"and",
"error"
] | 4dd05bc406a71e997bd4eaa16b12e23dbe62a456 | https://github.com/agentmedia/phine-builtin/blob/4dd05bc406a71e997bd4eaa16b12e23dbe62a456/src/BuiltIn/Modules/Backend/ChangePasswordConfirmForm.php#L92-L104 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.create | public static function create($template = null, $action = null, $method = 'POST', $encType = null) {
return new static($template, $action, $method, $encType);
} | php | public static function create($template = null, $action = null, $method = 'POST', $encType = null) {
return new static($template, $action, $method, $encType);
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"template",
"=",
"null",
",",
"$",
"action",
"=",
"null",
",",
"$",
"method",
"=",
"'POST'",
",",
"$",
"encType",
"=",
"null",
")",
"{",
"return",
"new",
"static",
"(",
"$",
"template",
",",
"$",
"action",
",",
"$",
"method",
",",
"$",
"encType",
")",
";",
"}"
] | Create instance
allows chaining
@param string $template filename
@param string $action attribute
@param string $method request method attribute
@param string $encType encoding type attribute
@return HtmlForm | [
"Create",
"instance",
"allows",
"chaining"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L220-L224 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.bindRequestParameters | public function bindRequestParameters(ParameterBag $bag = null) {
if($bag) {
$this->requestValues = $bag;
}
else {
if($this->request->getMethod() == 'GET') {
$this->requestValues = $this->request->query;
}
else {
$this->requestValues = $this->request->request;
}
}
// set form element values
foreach($this->elements as $name => $element) {
if(is_array($element)) {
$this->setElementArrayRequestValue($name);
}
else {
$this->setElementRequestValue($element);
}
}
return $this;
} | php | public function bindRequestParameters(ParameterBag $bag = null) {
if($bag) {
$this->requestValues = $bag;
}
else {
if($this->request->getMethod() == 'GET') {
$this->requestValues = $this->request->query;
}
else {
$this->requestValues = $this->request->request;
}
}
// set form element values
foreach($this->elements as $name => $element) {
if(is_array($element)) {
$this->setElementArrayRequestValue($name);
}
else {
$this->setElementRequestValue($element);
}
}
return $this;
} | [
"public",
"function",
"bindRequestParameters",
"(",
"ParameterBag",
"$",
"bag",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"bag",
")",
"{",
"$",
"this",
"->",
"requestValues",
"=",
"$",
"bag",
";",
"}",
"else",
"{",
"if",
"(",
"$",
"this",
"->",
"request",
"->",
"getMethod",
"(",
")",
"==",
"'GET'",
")",
"{",
"$",
"this",
"->",
"requestValues",
"=",
"$",
"this",
"->",
"request",
"->",
"query",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"requestValues",
"=",
"$",
"this",
"->",
"request",
"->",
"request",
";",
"}",
"}",
"// set form element values",
"foreach",
"(",
"$",
"this",
"->",
"elements",
"as",
"$",
"name",
"=>",
"$",
"element",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"element",
")",
")",
"{",
"$",
"this",
"->",
"setElementArrayRequestValue",
"(",
"$",
"name",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"setElementRequestValue",
"(",
"$",
"element",
")",
";",
"}",
"}",
"return",
"$",
"this",
";",
"}"
] | initialize parameter bag
parameterbag is either supplied, or depending on request method retrieved from request object
@param ParameterBag $bag
@return HtmlForm | [
"initialize",
"parameter",
"bag",
"parameterbag",
"is",
"either",
"supplied",
"or",
"depending",
"on",
"request",
"method",
"retrieved",
"from",
"request",
"object"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L234-L261 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.setMethod | public function setMethod($method) {
$method = strtoupper($method);
if($method != 'GET' && $method != 'POST') {
throw new HtmlFormException(sprintf("Invalid form method: '%s'.", $method), HtmlFormException::INVALID_METHOD);
}
$this->method = $method;
return $this;
} | php | public function setMethod($method) {
$method = strtoupper($method);
if($method != 'GET' && $method != 'POST') {
throw new HtmlFormException(sprintf("Invalid form method: '%s'.", $method), HtmlFormException::INVALID_METHOD);
}
$this->method = $method;
return $this;
} | [
"public",
"function",
"setMethod",
"(",
"$",
"method",
")",
"{",
"$",
"method",
"=",
"strtoupper",
"(",
"$",
"method",
")",
";",
"if",
"(",
"$",
"method",
"!=",
"'GET'",
"&&",
"$",
"method",
"!=",
"'POST'",
")",
"{",
"throw",
"new",
"HtmlFormException",
"(",
"sprintf",
"(",
"\"Invalid form method: '%s'.\"",
",",
"$",
"method",
")",
",",
"HtmlFormException",
"::",
"INVALID_METHOD",
")",
";",
"}",
"$",
"this",
"->",
"method",
"=",
"$",
"method",
";",
"return",
"$",
"this",
";",
"}"
] | set submission method
'GET' and 'POST' are the only allowed values
@param string $method
@return HtmlForm
@throws HtmlFormException | [
"set",
"submission",
"method",
"GET",
"and",
"POST",
"are",
"the",
"only",
"allowed",
"values"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L272-L282 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.setAttribute | public function setAttribute($attr, $value) {
$attr = strtolower($attr);
switch($attr) {
case 'action':
$this->setAction($value);
return $this;
case 'enctype':
$this->setEncType($value);
return $this;
case 'method':
$this->setMethod($value);
return $this;
default:
$this->attributes[$attr] = $value;
}
return $this;
} | php | public function setAttribute($attr, $value) {
$attr = strtolower($attr);
switch($attr) {
case 'action':
$this->setAction($value);
return $this;
case 'enctype':
$this->setEncType($value);
return $this;
case 'method':
$this->setMethod($value);
return $this;
default:
$this->attributes[$attr] = $value;
}
return $this;
} | [
"public",
"function",
"setAttribute",
"(",
"$",
"attr",
",",
"$",
"value",
")",
"{",
"$",
"attr",
"=",
"strtolower",
"(",
"$",
"attr",
")",
";",
"switch",
"(",
"$",
"attr",
")",
"{",
"case",
"'action'",
":",
"$",
"this",
"->",
"setAction",
"(",
"$",
"value",
")",
";",
"return",
"$",
"this",
";",
"case",
"'enctype'",
":",
"$",
"this",
"->",
"setEncType",
"(",
"$",
"value",
")",
";",
"return",
"$",
"this",
";",
"case",
"'method'",
":",
"$",
"this",
"->",
"setMethod",
"(",
"$",
"value",
")",
";",
"return",
"$",
"this",
";",
"default",
":",
"$",
"this",
"->",
"attributes",
"[",
"$",
"attr",
"]",
"=",
"$",
"value",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | set miscellaneous attribute of form
@param string $attr
@param string $value
@return HtmlForm
@throws HtmlFormException | [
"set",
"miscellaneous",
"attribute",
"of",
"form"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L331-L354 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.getAttribute | public function getAttribute($attr, $default = null) {
return ($attr && array_key_exists($attr, $this->attributes)) ? $this->attributes[$attr] : $default;
} | php | public function getAttribute($attr, $default = null) {
return ($attr && array_key_exists($attr, $this->attributes)) ? $this->attributes[$attr] : $default;
} | [
"public",
"function",
"getAttribute",
"(",
"$",
"attr",
",",
"$",
"default",
"=",
"null",
")",
"{",
"return",
"(",
"$",
"attr",
"&&",
"array_key_exists",
"(",
"$",
"attr",
",",
"$",
"this",
"->",
"attributes",
")",
")",
"?",
"$",
"this",
"->",
"attributes",
"[",
"$",
"attr",
"]",
":",
"$",
"default",
";",
"}"
] | get an attribute, if the attribute was not set previously a
default value can be supplied
@param string $attr
@param string $default
@return string | [
"get",
"an",
"attribute",
"if",
"the",
"attribute",
"was",
"not",
"set",
"previously",
"a",
"default",
"value",
"can",
"be",
"supplied"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L364-L368 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.setAttributes | public function setAttributes(array $attrs) {
foreach($attrs as $k => $v) {
$this->setAttribute($k, $v);
}
return $this;
} | php | public function setAttributes(array $attrs) {
foreach($attrs as $k => $v) {
$this->setAttribute($k, $v);
}
return $this;
} | [
"public",
"function",
"setAttributes",
"(",
"array",
"$",
"attrs",
")",
"{",
"foreach",
"(",
"$",
"attrs",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"$",
"this",
"->",
"setAttribute",
"(",
"$",
"k",
",",
"$",
"v",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | sets sevaral form attributes stored in associative array
@param array $attrs
@return HtmlForm
@throws HtmlFormException | [
"sets",
"sevaral",
"form",
"attributes",
"stored",
"in",
"associative",
"array"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L377-L385 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.getSubmittingElement | public function getSubmittingElement() {
// cache submitting element
if(!empty($this->clickedSubmit)) {
return $this->clickedSubmit;
}
if(is_null($this->requestValues)) {
return null;
}
foreach($this->elements as $name => $e) {
if(is_array($e)) {
// parse one-dimensional arrays
foreach($this->requestValues->keys() as $k) {
if(preg_match('/^' . $name . '\\[(.*?)\\]$/', $k, $m)) {
if(isset($this->elements[$name][$m[1]]) && $this->elements[$name][$m[1]]->canSubmit()) {
$this->clickedSubmit = $this->elements[$name][$m[1]];
return $this->clickedSubmit;
}
}
}
foreach($e as $k => $ee) {
if(
$ee instanceof ImageElement &&
($arr = $this->requestValues->get($name . '_x')) &&
isset($arr[$k])
) {
$this->clickedSubmit = $ee;
return $ee;
}
else if(
$ee->canSubmit() &&
($arr = $this->requestValues->get($name)) &&
isset($arr[$k])
) {
$this->clickedSubmit = $ee;
return $ee;
}
}
}
else if($e instanceof ImageElement && !is_null($this->requestValues->get($name . '_x'))) {
$this->clickedSubmit = $e;
return $e;
}
else if($e->canSubmit() && !is_null($this->requestValues->get($name))) {
$this->clickedSubmit = $e;
return $e;
}
}
} | php | public function getSubmittingElement() {
// cache submitting element
if(!empty($this->clickedSubmit)) {
return $this->clickedSubmit;
}
if(is_null($this->requestValues)) {
return null;
}
foreach($this->elements as $name => $e) {
if(is_array($e)) {
// parse one-dimensional arrays
foreach($this->requestValues->keys() as $k) {
if(preg_match('/^' . $name . '\\[(.*?)\\]$/', $k, $m)) {
if(isset($this->elements[$name][$m[1]]) && $this->elements[$name][$m[1]]->canSubmit()) {
$this->clickedSubmit = $this->elements[$name][$m[1]];
return $this->clickedSubmit;
}
}
}
foreach($e as $k => $ee) {
if(
$ee instanceof ImageElement &&
($arr = $this->requestValues->get($name . '_x')) &&
isset($arr[$k])
) {
$this->clickedSubmit = $ee;
return $ee;
}
else if(
$ee->canSubmit() &&
($arr = $this->requestValues->get($name)) &&
isset($arr[$k])
) {
$this->clickedSubmit = $ee;
return $ee;
}
}
}
else if($e instanceof ImageElement && !is_null($this->requestValues->get($name . '_x'))) {
$this->clickedSubmit = $e;
return $e;
}
else if($e->canSubmit() && !is_null($this->requestValues->get($name))) {
$this->clickedSubmit = $e;
return $e;
}
}
} | [
"public",
"function",
"getSubmittingElement",
"(",
")",
"{",
"// cache submitting element",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"clickedSubmit",
")",
")",
"{",
"return",
"$",
"this",
"->",
"clickedSubmit",
";",
"}",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"requestValues",
")",
")",
"{",
"return",
"null",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"elements",
"as",
"$",
"name",
"=>",
"$",
"e",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"e",
")",
")",
"{",
"// parse one-dimensional arrays",
"foreach",
"(",
"$",
"this",
"->",
"requestValues",
"->",
"keys",
"(",
")",
"as",
"$",
"k",
")",
"{",
"if",
"(",
"preg_match",
"(",
"'/^'",
".",
"$",
"name",
".",
"'\\\\[(.*?)\\\\]$/'",
",",
"$",
"k",
",",
"$",
"m",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"elements",
"[",
"$",
"name",
"]",
"[",
"$",
"m",
"[",
"1",
"]",
"]",
")",
"&&",
"$",
"this",
"->",
"elements",
"[",
"$",
"name",
"]",
"[",
"$",
"m",
"[",
"1",
"]",
"]",
"->",
"canSubmit",
"(",
")",
")",
"{",
"$",
"this",
"->",
"clickedSubmit",
"=",
"$",
"this",
"->",
"elements",
"[",
"$",
"name",
"]",
"[",
"$",
"m",
"[",
"1",
"]",
"]",
";",
"return",
"$",
"this",
"->",
"clickedSubmit",
";",
"}",
"}",
"}",
"foreach",
"(",
"$",
"e",
"as",
"$",
"k",
"=>",
"$",
"ee",
")",
"{",
"if",
"(",
"$",
"ee",
"instanceof",
"ImageElement",
"&&",
"(",
"$",
"arr",
"=",
"$",
"this",
"->",
"requestValues",
"->",
"get",
"(",
"$",
"name",
".",
"'_x'",
")",
")",
"&&",
"isset",
"(",
"$",
"arr",
"[",
"$",
"k",
"]",
")",
")",
"{",
"$",
"this",
"->",
"clickedSubmit",
"=",
"$",
"ee",
";",
"return",
"$",
"ee",
";",
"}",
"else",
"if",
"(",
"$",
"ee",
"->",
"canSubmit",
"(",
")",
"&&",
"(",
"$",
"arr",
"=",
"$",
"this",
"->",
"requestValues",
"->",
"get",
"(",
"$",
"name",
")",
")",
"&&",
"isset",
"(",
"$",
"arr",
"[",
"$",
"k",
"]",
")",
")",
"{",
"$",
"this",
"->",
"clickedSubmit",
"=",
"$",
"ee",
";",
"return",
"$",
"ee",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"$",
"e",
"instanceof",
"ImageElement",
"&&",
"!",
"is_null",
"(",
"$",
"this",
"->",
"requestValues",
"->",
"get",
"(",
"$",
"name",
".",
"'_x'",
")",
")",
")",
"{",
"$",
"this",
"->",
"clickedSubmit",
"=",
"$",
"e",
";",
"return",
"$",
"e",
";",
"}",
"else",
"if",
"(",
"$",
"e",
"->",
"canSubmit",
"(",
")",
"&&",
"!",
"is_null",
"(",
"$",
"this",
"->",
"requestValues",
"->",
"get",
"(",
"$",
"name",
")",
")",
")",
"{",
"$",
"this",
"->",
"clickedSubmit",
"=",
"$",
"e",
";",
"return",
"$",
"e",
";",
"}",
"}",
"}"
] | Returns FormElement which submitted form, result is cached
@return FormElement | [
"Returns",
"FormElement",
"which",
"submitted",
"form",
"result",
"is",
"cached"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L392-L456 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.render | public function render() {
if($this->loadTemplate()) {
$this
->primeTemplate()
->insertFormFields()
->insertErrorMessages()
->insertFormStart()
->insertFormEnd()
->cleanupHtml()
;
return $this->html;
}
} | php | public function render() {
if($this->loadTemplate()) {
$this
->primeTemplate()
->insertFormFields()
->insertErrorMessages()
->insertFormStart()
->insertFormEnd()
->cleanupHtml()
;
return $this->html;
}
} | [
"public",
"function",
"render",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"loadTemplate",
"(",
")",
")",
"{",
"$",
"this",
"->",
"primeTemplate",
"(",
")",
"->",
"insertFormFields",
"(",
")",
"->",
"insertErrorMessages",
"(",
")",
"->",
"insertFormStart",
"(",
")",
"->",
"insertFormEnd",
"(",
")",
"->",
"cleanupHtml",
"(",
")",
";",
"return",
"$",
"this",
"->",
"html",
";",
"}",
"}"
] | renders complete form markup
@throws HtmlFormException | [
"renders",
"complete",
"form",
"markup"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L478-L495 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.getValidFormValues | public function getValidFormValues($getSubmits = false) {
if(is_null($this->requestValues)) {
throw new HtmlFormException('Values can not be evaluated. No request bound.', HtmlFormException::NO_REQUEST_BOUND);
}
$tmp = new ValuesBag();
foreach($this->elements as $name => $e) {
if(is_array($e)) {
$vals = [];
foreach($e as $ndx => $elem) {
if(!$elem->isValid()) {
continue;
}
// @todo since elements in an array are all of same type they don't need to be checked individually
if($elem->canSubmit() && !$getSubmits) {
continue;
}
if($elem instanceof CheckboxElement && !in_array($elem->getValue(), $this->requestValues->get($name, []))) {
continue;
}
$vals[$ndx] = $elem->getModifiedValue();
}
$tmp->set($name, $vals);
}
else {
if(
$e->canSubmit() && !$getSubmits ||
!$e->isValid() ||
$e instanceof CheckboxElement && !$this->requestValues->get($name)
) {
continue;
}
$tmp->set($name, $e->getModifiedValue());
}
}
return $tmp;
} | php | public function getValidFormValues($getSubmits = false) {
if(is_null($this->requestValues)) {
throw new HtmlFormException('Values can not be evaluated. No request bound.', HtmlFormException::NO_REQUEST_BOUND);
}
$tmp = new ValuesBag();
foreach($this->elements as $name => $e) {
if(is_array($e)) {
$vals = [];
foreach($e as $ndx => $elem) {
if(!$elem->isValid()) {
continue;
}
// @todo since elements in an array are all of same type they don't need to be checked individually
if($elem->canSubmit() && !$getSubmits) {
continue;
}
if($elem instanceof CheckboxElement && !in_array($elem->getValue(), $this->requestValues->get($name, []))) {
continue;
}
$vals[$ndx] = $elem->getModifiedValue();
}
$tmp->set($name, $vals);
}
else {
if(
$e->canSubmit() && !$getSubmits ||
!$e->isValid() ||
$e instanceof CheckboxElement && !$this->requestValues->get($name)
) {
continue;
}
$tmp->set($name, $e->getModifiedValue());
}
}
return $tmp;
} | [
"public",
"function",
"getValidFormValues",
"(",
"$",
"getSubmits",
"=",
"false",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"requestValues",
")",
")",
"{",
"throw",
"new",
"HtmlFormException",
"(",
"'Values can not be evaluated. No request bound.'",
",",
"HtmlFormException",
"::",
"NO_REQUEST_BOUND",
")",
";",
"}",
"$",
"tmp",
"=",
"new",
"ValuesBag",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"elements",
"as",
"$",
"name",
"=>",
"$",
"e",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"e",
")",
")",
"{",
"$",
"vals",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"e",
"as",
"$",
"ndx",
"=>",
"$",
"elem",
")",
"{",
"if",
"(",
"!",
"$",
"elem",
"->",
"isValid",
"(",
")",
")",
"{",
"continue",
";",
"}",
"// @todo since elements in an array are all of same type they don't need to be checked individually",
"if",
"(",
"$",
"elem",
"->",
"canSubmit",
"(",
")",
"&&",
"!",
"$",
"getSubmits",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"$",
"elem",
"instanceof",
"CheckboxElement",
"&&",
"!",
"in_array",
"(",
"$",
"elem",
"->",
"getValue",
"(",
")",
",",
"$",
"this",
"->",
"requestValues",
"->",
"get",
"(",
"$",
"name",
",",
"[",
"]",
")",
")",
")",
"{",
"continue",
";",
"}",
"$",
"vals",
"[",
"$",
"ndx",
"]",
"=",
"$",
"elem",
"->",
"getModifiedValue",
"(",
")",
";",
"}",
"$",
"tmp",
"->",
"set",
"(",
"$",
"name",
",",
"$",
"vals",
")",
";",
"}",
"else",
"{",
"if",
"(",
"$",
"e",
"->",
"canSubmit",
"(",
")",
"&&",
"!",
"$",
"getSubmits",
"||",
"!",
"$",
"e",
"->",
"isValid",
"(",
")",
"||",
"$",
"e",
"instanceof",
"CheckboxElement",
"&&",
"!",
"$",
"this",
"->",
"requestValues",
"->",
"get",
"(",
"$",
"name",
")",
")",
"{",
"continue",
";",
"}",
"$",
"tmp",
"->",
"set",
"(",
"$",
"name",
",",
"$",
"e",
"->",
"getModifiedValue",
"(",
")",
")",
";",
"}",
"}",
"return",
"$",
"tmp",
";",
"}"
] | deliver all valid form values
@param boolean $getSubmits,deliver submit buttons when TRUE, defaults to FALSE
@return ValuesBag
@throws HtmlFormException | [
"deliver",
"all",
"valid",
"form",
"values"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L505-L561 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.setInitFormValues | public function setInitFormValues(array $values) {
$this->initFormValues = $values;
foreach($values as $name => $value) {
if(isset($this->elements[$name]) && is_object($this->elements[$name])) {
if($this->elements[$name] instanceof CheckboxElement) {
if(empty($this->requestValues)) {
$this->elements[$name]->setChecked($this->elements[$name]->getValue() == $value);
}
else {
$this->elements[$name]->setChecked(!is_null($this->requestValues->get($name)));
}
}
else if(is_null($this->elements[$name]->getValue())) {
$this->elements[$name]->setValue($value);
}
}
}
return $this;
} | php | public function setInitFormValues(array $values) {
$this->initFormValues = $values;
foreach($values as $name => $value) {
if(isset($this->elements[$name]) && is_object($this->elements[$name])) {
if($this->elements[$name] instanceof CheckboxElement) {
if(empty($this->requestValues)) {
$this->elements[$name]->setChecked($this->elements[$name]->getValue() == $value);
}
else {
$this->elements[$name]->setChecked(!is_null($this->requestValues->get($name)));
}
}
else if(is_null($this->elements[$name]->getValue())) {
$this->elements[$name]->setValue($value);
}
}
}
return $this;
} | [
"public",
"function",
"setInitFormValues",
"(",
"array",
"$",
"values",
")",
"{",
"$",
"this",
"->",
"initFormValues",
"=",
"$",
"values",
";",
"foreach",
"(",
"$",
"values",
"as",
"$",
"name",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"elements",
"[",
"$",
"name",
"]",
")",
"&&",
"is_object",
"(",
"$",
"this",
"->",
"elements",
"[",
"$",
"name",
"]",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"elements",
"[",
"$",
"name",
"]",
"instanceof",
"CheckboxElement",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"requestValues",
")",
")",
"{",
"$",
"this",
"->",
"elements",
"[",
"$",
"name",
"]",
"->",
"setChecked",
"(",
"$",
"this",
"->",
"elements",
"[",
"$",
"name",
"]",
"->",
"getValue",
"(",
")",
"==",
"$",
"value",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"elements",
"[",
"$",
"name",
"]",
"->",
"setChecked",
"(",
"!",
"is_null",
"(",
"$",
"this",
"->",
"requestValues",
"->",
"get",
"(",
"$",
"name",
")",
")",
")",
";",
"}",
"}",
"else",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"elements",
"[",
"$",
"name",
"]",
"->",
"getValue",
"(",
")",
")",
")",
"{",
"$",
"this",
"->",
"elements",
"[",
"$",
"name",
"]",
"->",
"setValue",
"(",
"$",
"value",
")",
";",
"}",
"}",
"}",
"return",
"$",
"this",
";",
"}"
] | sets initial form values stored in associative array
values will only be applied to elements with previously declared value NULL
checkbox elements will be checked when their value equals form value
@param array $values
@return HtmlForm | [
"sets",
"initial",
"form",
"values",
"stored",
"in",
"associative",
"array",
"values",
"will",
"only",
"be",
"applied",
"to",
"elements",
"with",
"previously",
"declared",
"value",
"NULL",
"checkbox",
"elements",
"will",
"be",
"checked",
"when",
"their",
"value",
"equals",
"form",
"value"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L572-L596 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.setError | public function setError($errorName, $errorNameIndex = null, $message = null) {
if(is_null($errorNameIndex)) {
$this->formErrors[$errorName] = new FormError($message);
}
else {
$this->formErrors[$errorName][$errorNameIndex] = new FormError($message);
}
return $this;
} | php | public function setError($errorName, $errorNameIndex = null, $message = null) {
if(is_null($errorNameIndex)) {
$this->formErrors[$errorName] = new FormError($message);
}
else {
$this->formErrors[$errorName][$errorNameIndex] = new FormError($message);
}
return $this;
} | [
"public",
"function",
"setError",
"(",
"$",
"errorName",
",",
"$",
"errorNameIndex",
"=",
"null",
",",
"$",
"message",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"errorNameIndex",
")",
")",
"{",
"$",
"this",
"->",
"formErrors",
"[",
"$",
"errorName",
"]",
"=",
"new",
"FormError",
"(",
"$",
"message",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"formErrors",
"[",
"$",
"errorName",
"]",
"[",
"$",
"errorNameIndex",
"]",
"=",
"new",
"FormError",
"(",
"$",
"message",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | add custom error and force error message in template
@param string $errorName
@param mixed $errorNameIndex
@param string message
@return HtmlForm | [
"add",
"custom",
"error",
"and",
"force",
"error",
"message",
"in",
"template"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L707-L718 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.getElementsByName | public function getElementsByName($name) {
if(isset($this->elements[$name])) {
return $this->elements[$name];
}
throw new \InvalidArgumentException(sprintf("Unknown form element '%s'", $name));
} | php | public function getElementsByName($name) {
if(isset($this->elements[$name])) {
return $this->elements[$name];
}
throw new \InvalidArgumentException(sprintf("Unknown form element '%s'", $name));
} | [
"public",
"function",
"getElementsByName",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"elements",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"elements",
"[",
"$",
"name",
"]",
";",
"}",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"\"Unknown form element '%s'\"",
",",
"$",
"name",
")",
")",
";",
"}"
] | get one or more elements by name
@param string $name of element or elements
@return FormElement|array
@throws \InvalidArgumentException | [
"get",
"one",
"or",
"more",
"elements",
"by",
"name"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L738-L746 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.addElement | public function addElement(FormElement $element) {
if(!empty($this->elements[$element->getName()])) {
throw new HtmlFormException(sprintf("Element '%s' already assigned.", $element->getName()));
}
$this->elements[$element->getName()] = $element;
$element->setForm($this);
return $this;
} | php | public function addElement(FormElement $element) {
if(!empty($this->elements[$element->getName()])) {
throw new HtmlFormException(sprintf("Element '%s' already assigned.", $element->getName()));
}
$this->elements[$element->getName()] = $element;
$element->setForm($this);
return $this;
} | [
"public",
"function",
"addElement",
"(",
"FormElement",
"$",
"element",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"elements",
"[",
"$",
"element",
"->",
"getName",
"(",
")",
"]",
")",
")",
"{",
"throw",
"new",
"HtmlFormException",
"(",
"sprintf",
"(",
"\"Element '%s' already assigned.\"",
",",
"$",
"element",
"->",
"getName",
"(",
")",
")",
")",
";",
"}",
"$",
"this",
"->",
"elements",
"[",
"$",
"element",
"->",
"getName",
"(",
")",
"]",
"=",
"$",
"element",
";",
"$",
"element",
"->",
"setForm",
"(",
"$",
"this",
")",
";",
"return",
"$",
"this",
";",
"}"
] | add form element to form
@param FormElement $element
@throws HtmlFormException
@return \vxPHP\Form\HtmlForm | [
"add",
"form",
"element",
"to",
"form"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L755-L768 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.addElementArray | public function addElementArray(array $elements) {
if(count($elements)) {
$firstElement = array_shift($elements);
$name = $firstElement->getName();
// remove any array indexes from name
$name = preg_replace('~\[\w*\]$~i', '', $name);
if(!empty($this->elements[$name])) {
throw new HtmlFormException(sprintf("Element '%s' already assigned.", $name));
}
$arrayName = $name . '[]';
$firstElement
->setName($arrayName)
->setForm($this)
;
$this->elements[$name] = [$firstElement];
foreach($elements as $e) {
if(get_class($e) !== get_class($firstElement)) {
throw new HtmlFormException(sprintf("Class mismatch of form elements array. Expected '%s', found '%s'.", get_class($firstElement), get_class($e)));
}
// check whether names of element arrays match
$nameToCheck = preg_replace('~\[\w*\]$~i', '', $e->getName());
if($nameToCheck && $nameToCheck !== $name) {
throw new HtmlFormException(sprintf("Name mismatch of form elements array. Expected '%s' or empty name, found '%s'.", $name, $e->getName()));
}
$e
->setName($arrayName)
->setForm($this)
;
$this->elements[$name][] = $e;
}
}
return $this;
} | php | public function addElementArray(array $elements) {
if(count($elements)) {
$firstElement = array_shift($elements);
$name = $firstElement->getName();
// remove any array indexes from name
$name = preg_replace('~\[\w*\]$~i', '', $name);
if(!empty($this->elements[$name])) {
throw new HtmlFormException(sprintf("Element '%s' already assigned.", $name));
}
$arrayName = $name . '[]';
$firstElement
->setName($arrayName)
->setForm($this)
;
$this->elements[$name] = [$firstElement];
foreach($elements as $e) {
if(get_class($e) !== get_class($firstElement)) {
throw new HtmlFormException(sprintf("Class mismatch of form elements array. Expected '%s', found '%s'.", get_class($firstElement), get_class($e)));
}
// check whether names of element arrays match
$nameToCheck = preg_replace('~\[\w*\]$~i', '', $e->getName());
if($nameToCheck && $nameToCheck !== $name) {
throw new HtmlFormException(sprintf("Name mismatch of form elements array. Expected '%s' or empty name, found '%s'.", $name, $e->getName()));
}
$e
->setName($arrayName)
->setForm($this)
;
$this->elements[$name][] = $e;
}
}
return $this;
} | [
"public",
"function",
"addElementArray",
"(",
"array",
"$",
"elements",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"elements",
")",
")",
"{",
"$",
"firstElement",
"=",
"array_shift",
"(",
"$",
"elements",
")",
";",
"$",
"name",
"=",
"$",
"firstElement",
"->",
"getName",
"(",
")",
";",
"// remove any array indexes from name",
"$",
"name",
"=",
"preg_replace",
"(",
"'~\\[\\w*\\]$~i'",
",",
"''",
",",
"$",
"name",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"elements",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"new",
"HtmlFormException",
"(",
"sprintf",
"(",
"\"Element '%s' already assigned.\"",
",",
"$",
"name",
")",
")",
";",
"}",
"$",
"arrayName",
"=",
"$",
"name",
".",
"'[]'",
";",
"$",
"firstElement",
"->",
"setName",
"(",
"$",
"arrayName",
")",
"->",
"setForm",
"(",
"$",
"this",
")",
";",
"$",
"this",
"->",
"elements",
"[",
"$",
"name",
"]",
"=",
"[",
"$",
"firstElement",
"]",
";",
"foreach",
"(",
"$",
"elements",
"as",
"$",
"e",
")",
"{",
"if",
"(",
"get_class",
"(",
"$",
"e",
")",
"!==",
"get_class",
"(",
"$",
"firstElement",
")",
")",
"{",
"throw",
"new",
"HtmlFormException",
"(",
"sprintf",
"(",
"\"Class mismatch of form elements array. Expected '%s', found '%s'.\"",
",",
"get_class",
"(",
"$",
"firstElement",
")",
",",
"get_class",
"(",
"$",
"e",
")",
")",
")",
";",
"}",
"// check whether names of element arrays match",
"$",
"nameToCheck",
"=",
"preg_replace",
"(",
"'~\\[\\w*\\]$~i'",
",",
"''",
",",
"$",
"e",
"->",
"getName",
"(",
")",
")",
";",
"if",
"(",
"$",
"nameToCheck",
"&&",
"$",
"nameToCheck",
"!==",
"$",
"name",
")",
"{",
"throw",
"new",
"HtmlFormException",
"(",
"sprintf",
"(",
"\"Name mismatch of form elements array. Expected '%s' or empty name, found '%s'.\"",
",",
"$",
"name",
",",
"$",
"e",
"->",
"getName",
"(",
")",
")",
")",
";",
"}",
"$",
"e",
"->",
"setName",
"(",
"$",
"arrayName",
")",
"->",
"setForm",
"(",
"$",
"this",
")",
";",
"$",
"this",
"->",
"elements",
"[",
"$",
"name",
"]",
"[",
"]",
"=",
"$",
"e",
";",
"}",
"}",
"return",
"$",
"this",
";",
"}"
] | add several form elements stored in array to form
the elements have to be of same type and have to have the same
name or an empty name
@param array FormElement[]
@throws HtmlFormException
@return \vxPHP\Form\HtmlForm | [
"add",
"several",
"form",
"elements",
"stored",
"in",
"array",
"to",
"form"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L781-L836 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.renderCsrfToken | private function renderCsrfToken() {
$tokenManager = new CsrfTokenManager();
$token = $tokenManager->refreshToken('_' . $this->action . '_');
$e = new InputElement(self::CSRF_TOKEN_NAME, $token->getValue());
$e->setAttribute('type', 'hidden');
return $e->render();
} | php | private function renderCsrfToken() {
$tokenManager = new CsrfTokenManager();
$token = $tokenManager->refreshToken('_' . $this->action . '_');
$e = new InputElement(self::CSRF_TOKEN_NAME, $token->getValue());
$e->setAttribute('type', 'hidden');
return $e->render();
} | [
"private",
"function",
"renderCsrfToken",
"(",
")",
"{",
"$",
"tokenManager",
"=",
"new",
"CsrfTokenManager",
"(",
")",
";",
"$",
"token",
"=",
"$",
"tokenManager",
"->",
"refreshToken",
"(",
"'_'",
".",
"$",
"this",
"->",
"action",
".",
"'_'",
")",
";",
"$",
"e",
"=",
"new",
"InputElement",
"(",
"self",
"::",
"CSRF_TOKEN_NAME",
",",
"$",
"token",
"->",
"getValue",
"(",
")",
")",
";",
"$",
"e",
"->",
"setAttribute",
"(",
"'type'",
",",
"'hidden'",
")",
";",
"return",
"$",
"e",
"->",
"render",
"(",
")",
";",
"}"
] | render CSRF token element
the token will use the form action as id
@return string | [
"render",
"CSRF",
"token",
"element",
"the",
"token",
"will",
"use",
"the",
"form",
"action",
"as",
"id"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L1009-L1018 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.checkCsrfToken | private function checkCsrfToken() {
$tokenManager = new CsrfTokenManager();
$token = new CsrfToken(
'_' . $this->action . '_',
$this->requestValues->get(self::CSRF_TOKEN_NAME)
);
return $tokenManager->isTokenValid($token);
} | php | private function checkCsrfToken() {
$tokenManager = new CsrfTokenManager();
$token = new CsrfToken(
'_' . $this->action . '_',
$this->requestValues->get(self::CSRF_TOKEN_NAME)
);
return $tokenManager->isTokenValid($token);
} | [
"private",
"function",
"checkCsrfToken",
"(",
")",
"{",
"$",
"tokenManager",
"=",
"new",
"CsrfTokenManager",
"(",
")",
";",
"$",
"token",
"=",
"new",
"CsrfToken",
"(",
"'_'",
".",
"$",
"this",
"->",
"action",
".",
"'_'",
",",
"$",
"this",
"->",
"requestValues",
"->",
"get",
"(",
"self",
"::",
"CSRF_TOKEN_NAME",
")",
")",
";",
"return",
"$",
"tokenManager",
"->",
"isTokenValid",
"(",
"$",
"token",
")",
";",
"}"
] | check whether a CSRF token remained untainted
compares the stored token with the request value
@return boolean | [
"check",
"whether",
"a",
"CSRF",
"token",
"remained",
"untainted",
"compares",
"the",
"stored",
"token",
"with",
"the",
"request",
"value"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L1026-L1037 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.renderAntiSpam | private function renderAntiSpam() {
$secret = md5(uniqid(null, true));
$label = md5($secret);
Session::getSessionDataBag()->set('antiSpamTimer', [$secret => microtime(true)]);
$e = new InputElement('verify', null);
$e->setAttribute('type', 'hidden');
$this->addElement($e);
$e->setValue($secret);
return sprintf("
<div>%s
<span style='display:none;'>
<label for='confirm_entry_%s'>Leave this field empty!</label>
<input id='confirm_entry_%s' name='confirm_entry_%s' value=''>
</span>
</div>", $e->render(), $label, $label, $label);
} | php | private function renderAntiSpam() {
$secret = md5(uniqid(null, true));
$label = md5($secret);
Session::getSessionDataBag()->set('antiSpamTimer', [$secret => microtime(true)]);
$e = new InputElement('verify', null);
$e->setAttribute('type', 'hidden');
$this->addElement($e);
$e->setValue($secret);
return sprintf("
<div>%s
<span style='display:none;'>
<label for='confirm_entry_%s'>Leave this field empty!</label>
<input id='confirm_entry_%s' name='confirm_entry_%s' value=''>
</span>
</div>", $e->render(), $label, $label, $label);
} | [
"private",
"function",
"renderAntiSpam",
"(",
")",
"{",
"$",
"secret",
"=",
"md5",
"(",
"uniqid",
"(",
"null",
",",
"true",
")",
")",
";",
"$",
"label",
"=",
"md5",
"(",
"$",
"secret",
")",
";",
"Session",
"::",
"getSessionDataBag",
"(",
")",
"->",
"set",
"(",
"'antiSpamTimer'",
",",
"[",
"$",
"secret",
"=>",
"microtime",
"(",
"true",
")",
"]",
")",
";",
"$",
"e",
"=",
"new",
"InputElement",
"(",
"'verify'",
",",
"null",
")",
";",
"$",
"e",
"->",
"setAttribute",
"(",
"'type'",
",",
"'hidden'",
")",
";",
"$",
"this",
"->",
"addElement",
"(",
"$",
"e",
")",
";",
"$",
"e",
"->",
"setValue",
"(",
"$",
"secret",
")",
";",
"return",
"sprintf",
"(",
"\"\n\t\t\t<div>%s\n\t\t\t\t<span style='display:none;'>\n\t\t\t\t\t<label for='confirm_entry_%s'>Leave this field empty!</label>\n\t\t\t\t\t<input id='confirm_entry_%s' name='confirm_entry_%s' value=''>\n\t\t\t\t</span>\n\t\t\t</div>\"",
",",
"$",
"e",
"->",
"render",
"(",
")",
",",
"$",
"label",
",",
"$",
"label",
",",
"$",
"label",
")",
";",
"}"
] | render spam countermeasures
@throws HtmlFormException | [
"render",
"spam",
"countermeasures"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L1043-L1064 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.detectSpam | public function detectSpam(array $fields = [], $threshold = 3) {
$verify = $this->requestValues->get('verify');
$timer = Session::getSessionDataBag()->get('antiSpamTimer');
if(
!$verify ||
!isset($timer[$verify]) ||
(microtime(true) - $timer[$verify] < 1)
) {
return true;
}
$label = md5($verify);
if(is_null($this->requestValues->get('confirm_entry_' . $label)) || $this->requestValues->get('confirm_entry_' . $label) !== '') {
return true;
}
foreach($fields as $f) {
if(preg_match_all('~<\s*a\s+href\s*\=\s*(\\\\*"|\\\\*\'){0,1}http://~i', $this->requestValues->get($f), $tmp) > $threshold) {
return true;
}
if(preg_match('~\[\s*url.*?\]~i', $this->requestValues->get($f))) {
return true;
}
}
return false;
} | php | public function detectSpam(array $fields = [], $threshold = 3) {
$verify = $this->requestValues->get('verify');
$timer = Session::getSessionDataBag()->get('antiSpamTimer');
if(
!$verify ||
!isset($timer[$verify]) ||
(microtime(true) - $timer[$verify] < 1)
) {
return true;
}
$label = md5($verify);
if(is_null($this->requestValues->get('confirm_entry_' . $label)) || $this->requestValues->get('confirm_entry_' . $label) !== '') {
return true;
}
foreach($fields as $f) {
if(preg_match_all('~<\s*a\s+href\s*\=\s*(\\\\*"|\\\\*\'){0,1}http://~i', $this->requestValues->get($f), $tmp) > $threshold) {
return true;
}
if(preg_match('~\[\s*url.*?\]~i', $this->requestValues->get($f))) {
return true;
}
}
return false;
} | [
"public",
"function",
"detectSpam",
"(",
"array",
"$",
"fields",
"=",
"[",
"]",
",",
"$",
"threshold",
"=",
"3",
")",
"{",
"$",
"verify",
"=",
"$",
"this",
"->",
"requestValues",
"->",
"get",
"(",
"'verify'",
")",
";",
"$",
"timer",
"=",
"Session",
"::",
"getSessionDataBag",
"(",
")",
"->",
"get",
"(",
"'antiSpamTimer'",
")",
";",
"if",
"(",
"!",
"$",
"verify",
"||",
"!",
"isset",
"(",
"$",
"timer",
"[",
"$",
"verify",
"]",
")",
"||",
"(",
"microtime",
"(",
"true",
")",
"-",
"$",
"timer",
"[",
"$",
"verify",
"]",
"<",
"1",
")",
")",
"{",
"return",
"true",
";",
"}",
"$",
"label",
"=",
"md5",
"(",
"$",
"verify",
")",
";",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"requestValues",
"->",
"get",
"(",
"'confirm_entry_'",
".",
"$",
"label",
")",
")",
"||",
"$",
"this",
"->",
"requestValues",
"->",
"get",
"(",
"'confirm_entry_'",
".",
"$",
"label",
")",
"!==",
"''",
")",
"{",
"return",
"true",
";",
"}",
"foreach",
"(",
"$",
"fields",
"as",
"$",
"f",
")",
"{",
"if",
"(",
"preg_match_all",
"(",
"'~<\\s*a\\s+href\\s*\\=\\s*(\\\\\\\\*\"|\\\\\\\\*\\'){0,1}http://~i'",
",",
"$",
"this",
"->",
"requestValues",
"->",
"get",
"(",
"$",
"f",
")",
",",
"$",
"tmp",
")",
">",
"$",
"threshold",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"preg_match",
"(",
"'~\\[\\s*url.*?\\]~i'",
",",
"$",
"this",
"->",
"requestValues",
"->",
"get",
"(",
"$",
"f",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | check for spam
@param array $fields names of fields to check against spam
@param int $threshold number of suspicious content which when exceeded will indicate spam
@return boolean $spam_detected | [
"check",
"for",
"spam"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L1073-L1102 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.insertFormFields | private function insertFormFields() {
$this->html = preg_replace_callback(
'/\{\s*(dropdown|input|image|button|textarea|options|checkbox|selectbox|label|element):(\w+)(?:\s+(\{.*?\}))?\s*\}/i',
function($matches) {
// check whether element was assigned
if(empty($this->elements[$matches[2]])) {
if($this->onlyAssignedElements) {
throw new HtmlFormException(sprintf("Element '%s' not assigned to form.", $matches[2]), HtmlFormException::INVALID_MARKUP);
}
}
else {
// validate JSON attribute string
if (!empty($matches[3])) {
$attributes = json_decode($matches[3], true, 2);
if (is_null($attributes)) {
throw new HtmlFormException(sprintf("Could not parse JSON attributes for element '%s'.", $matches[2]), HtmlFormException::INVALID_MARKUP);
}
$attributes = array_change_key_case($attributes, CASE_LOWER);
if (isset($attributes['name'])) {
throw new HtmlFormException(sprintf("Attribute 'name' is not allowed with element '%s'.", $matches[2]), HtmlFormException::INVALID_MARKUP);
}
}
// insert rendered element or label
if (is_array($this->elements[$matches[2]])) {
if (!isset($this->formElementIndexes[$matches[2]])) {
$this->formElementIndexes[$matches[2]] = 0;
}
if ('label' === strtolower($matches[1])) {
// insert label, array index does not advance
$e = $this->elements[$matches[2]][$this->formElementIndexes[$matches[2]]]->getLabel();
} else {
// insert element, advance array index
$e = $this->elements[$matches[2]][$this->formElementIndexes[$matches[2]]++];
}
} else {
// insert element
$e = $this->elements[$matches[2]];
if ('label' === strtolower($matches[1])) {
// insert label
$e = $e->getLabel();
}
}
if($e) {
if (isset($attributes)) {
$e->setAttributes($attributes);
}
return $e->render();
}
}
},
$this->template
);
return $this;
} | php | private function insertFormFields() {
$this->html = preg_replace_callback(
'/\{\s*(dropdown|input|image|button|textarea|options|checkbox|selectbox|label|element):(\w+)(?:\s+(\{.*?\}))?\s*\}/i',
function($matches) {
// check whether element was assigned
if(empty($this->elements[$matches[2]])) {
if($this->onlyAssignedElements) {
throw new HtmlFormException(sprintf("Element '%s' not assigned to form.", $matches[2]), HtmlFormException::INVALID_MARKUP);
}
}
else {
// validate JSON attribute string
if (!empty($matches[3])) {
$attributes = json_decode($matches[3], true, 2);
if (is_null($attributes)) {
throw new HtmlFormException(sprintf("Could not parse JSON attributes for element '%s'.", $matches[2]), HtmlFormException::INVALID_MARKUP);
}
$attributes = array_change_key_case($attributes, CASE_LOWER);
if (isset($attributes['name'])) {
throw new HtmlFormException(sprintf("Attribute 'name' is not allowed with element '%s'.", $matches[2]), HtmlFormException::INVALID_MARKUP);
}
}
// insert rendered element or label
if (is_array($this->elements[$matches[2]])) {
if (!isset($this->formElementIndexes[$matches[2]])) {
$this->formElementIndexes[$matches[2]] = 0;
}
if ('label' === strtolower($matches[1])) {
// insert label, array index does not advance
$e = $this->elements[$matches[2]][$this->formElementIndexes[$matches[2]]]->getLabel();
} else {
// insert element, advance array index
$e = $this->elements[$matches[2]][$this->formElementIndexes[$matches[2]]++];
}
} else {
// insert element
$e = $this->elements[$matches[2]];
if ('label' === strtolower($matches[1])) {
// insert label
$e = $e->getLabel();
}
}
if($e) {
if (isset($attributes)) {
$e->setAttributes($attributes);
}
return $e->render();
}
}
},
$this->template
);
return $this;
} | [
"private",
"function",
"insertFormFields",
"(",
")",
"{",
"$",
"this",
"->",
"html",
"=",
"preg_replace_callback",
"(",
"'/\\{\\s*(dropdown|input|image|button|textarea|options|checkbox|selectbox|label|element):(\\w+)(?:\\s+(\\{.*?\\}))?\\s*\\}/i'",
",",
"function",
"(",
"$",
"matches",
")",
"{",
"// check whether element was assigned",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"elements",
"[",
"$",
"matches",
"[",
"2",
"]",
"]",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"onlyAssignedElements",
")",
"{",
"throw",
"new",
"HtmlFormException",
"(",
"sprintf",
"(",
"\"Element '%s' not assigned to form.\"",
",",
"$",
"matches",
"[",
"2",
"]",
")",
",",
"HtmlFormException",
"::",
"INVALID_MARKUP",
")",
";",
"}",
"}",
"else",
"{",
"// validate JSON attribute string",
"if",
"(",
"!",
"empty",
"(",
"$",
"matches",
"[",
"3",
"]",
")",
")",
"{",
"$",
"attributes",
"=",
"json_decode",
"(",
"$",
"matches",
"[",
"3",
"]",
",",
"true",
",",
"2",
")",
";",
"if",
"(",
"is_null",
"(",
"$",
"attributes",
")",
")",
"{",
"throw",
"new",
"HtmlFormException",
"(",
"sprintf",
"(",
"\"Could not parse JSON attributes for element '%s'.\"",
",",
"$",
"matches",
"[",
"2",
"]",
")",
",",
"HtmlFormException",
"::",
"INVALID_MARKUP",
")",
";",
"}",
"$",
"attributes",
"=",
"array_change_key_case",
"(",
"$",
"attributes",
",",
"CASE_LOWER",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"attributes",
"[",
"'name'",
"]",
")",
")",
"{",
"throw",
"new",
"HtmlFormException",
"(",
"sprintf",
"(",
"\"Attribute 'name' is not allowed with element '%s'.\"",
",",
"$",
"matches",
"[",
"2",
"]",
")",
",",
"HtmlFormException",
"::",
"INVALID_MARKUP",
")",
";",
"}",
"}",
"// insert rendered element or label",
"if",
"(",
"is_array",
"(",
"$",
"this",
"->",
"elements",
"[",
"$",
"matches",
"[",
"2",
"]",
"]",
")",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"formElementIndexes",
"[",
"$",
"matches",
"[",
"2",
"]",
"]",
")",
")",
"{",
"$",
"this",
"->",
"formElementIndexes",
"[",
"$",
"matches",
"[",
"2",
"]",
"]",
"=",
"0",
";",
"}",
"if",
"(",
"'label'",
"===",
"strtolower",
"(",
"$",
"matches",
"[",
"1",
"]",
")",
")",
"{",
"// insert label, array index does not advance",
"$",
"e",
"=",
"$",
"this",
"->",
"elements",
"[",
"$",
"matches",
"[",
"2",
"]",
"]",
"[",
"$",
"this",
"->",
"formElementIndexes",
"[",
"$",
"matches",
"[",
"2",
"]",
"]",
"]",
"->",
"getLabel",
"(",
")",
";",
"}",
"else",
"{",
"// insert element, advance array index",
"$",
"e",
"=",
"$",
"this",
"->",
"elements",
"[",
"$",
"matches",
"[",
"2",
"]",
"]",
"[",
"$",
"this",
"->",
"formElementIndexes",
"[",
"$",
"matches",
"[",
"2",
"]",
"]",
"++",
"]",
";",
"}",
"}",
"else",
"{",
"// insert element",
"$",
"e",
"=",
"$",
"this",
"->",
"elements",
"[",
"$",
"matches",
"[",
"2",
"]",
"]",
";",
"if",
"(",
"'label'",
"===",
"strtolower",
"(",
"$",
"matches",
"[",
"1",
"]",
")",
")",
"{",
"// insert label",
"$",
"e",
"=",
"$",
"e",
"->",
"getLabel",
"(",
")",
";",
"}",
"}",
"if",
"(",
"$",
"e",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"attributes",
")",
")",
"{",
"$",
"e",
"->",
"setAttributes",
"(",
"$",
"attributes",
")",
";",
"}",
"return",
"$",
"e",
"->",
"render",
"(",
")",
";",
"}",
"}",
"}",
",",
"$",
"this",
"->",
"template",
")",
";",
"return",
"$",
"this",
";",
"}"
] | insert form fields into template
form fields are expected in the following form
{element: <name> [ {attributes}]}
the optional attributes are provided as JSON encoded key-value pairs
future versions may observe *only* the "element" string and deprecate
specific element types
@return HtmlForm | [
"insert",
"form",
"fields",
"into",
"template"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L1448-L1540 | train |
Vectrex/vxPHP | src/Form/HtmlForm.php | HtmlForm.insertErrorMessages | private function insertErrorMessages() {
$rex = '/\{(?:\w+\|)*error_%s(?:\|\w+)*:([^\}]+)\}/i';
foreach($this->formErrors as $name => $v) {
if(!is_array($v)) {
$this->html = preg_replace(
sprintf($rex, $name),
'$1',
$this->html
);
}
else {
foreach(array_keys($this->formErrors[$name]) as $ndx) {
$this->html = preg_replace(
sprintf($rex, $name),
empty($this->formErrors[$name][$ndx]) ? '' : '$1',
$this->html,
1
);
}
}
}
return $this;
} | php | private function insertErrorMessages() {
$rex = '/\{(?:\w+\|)*error_%s(?:\|\w+)*:([^\}]+)\}/i';
foreach($this->formErrors as $name => $v) {
if(!is_array($v)) {
$this->html = preg_replace(
sprintf($rex, $name),
'$1',
$this->html
);
}
else {
foreach(array_keys($this->formErrors[$name]) as $ndx) {
$this->html = preg_replace(
sprintf($rex, $name),
empty($this->formErrors[$name][$ndx]) ? '' : '$1',
$this->html,
1
);
}
}
}
return $this;
} | [
"private",
"function",
"insertErrorMessages",
"(",
")",
"{",
"$",
"rex",
"=",
"'/\\{(?:\\w+\\|)*error_%s(?:\\|\\w+)*:([^\\}]+)\\}/i'",
";",
"foreach",
"(",
"$",
"this",
"->",
"formErrors",
"as",
"$",
"name",
"=>",
"$",
"v",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"v",
")",
")",
"{",
"$",
"this",
"->",
"html",
"=",
"preg_replace",
"(",
"sprintf",
"(",
"$",
"rex",
",",
"$",
"name",
")",
",",
"'$1'",
",",
"$",
"this",
"->",
"html",
")",
";",
"}",
"else",
"{",
"foreach",
"(",
"array_keys",
"(",
"$",
"this",
"->",
"formErrors",
"[",
"$",
"name",
"]",
")",
"as",
"$",
"ndx",
")",
"{",
"$",
"this",
"->",
"html",
"=",
"preg_replace",
"(",
"sprintf",
"(",
"$",
"rex",
",",
"$",
"name",
")",
",",
"empty",
"(",
"$",
"this",
"->",
"formErrors",
"[",
"$",
"name",
"]",
"[",
"$",
"ndx",
"]",
")",
"?",
"''",
":",
"'$1'",
",",
"$",
"this",
"->",
"html",
",",
"1",
")",
";",
"}",
"}",
"}",
"return",
"$",
"this",
";",
"}"
] | insert error messages into template
placeholder for error messages are replaced
@return HtmlForm | [
"insert",
"error",
"messages",
"into",
"template",
"placeholder",
"for",
"error",
"messages",
"are",
"replaced"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/HtmlForm.php#L1694-L1720 | train |
TitaPHP/framework | src/TitaPHP/Http/Router.php | Router.match | public function match()
{
$requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
$method = $this->getRequestMethod();
$uri = $this->getCurrentUri();
// Loop all routes
foreach ($this->routes[$method] as $route) {
// we have a match!
if (preg_match_all('#^' . $route['pattern'] . '$#', $uri, $matches, PREG_OFFSET_CAPTURE)) {
die("route matched");
}
}
die("no route matched");
} | php | public function match()
{
$requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
$method = $this->getRequestMethod();
$uri = $this->getCurrentUri();
// Loop all routes
foreach ($this->routes[$method] as $route) {
// we have a match!
if (preg_match_all('#^' . $route['pattern'] . '$#', $uri, $matches, PREG_OFFSET_CAPTURE)) {
die("route matched");
}
}
die("no route matched");
} | [
"public",
"function",
"match",
"(",
")",
"{",
"$",
"requestUrl",
"=",
"isset",
"(",
"$",
"_SERVER",
"[",
"'REQUEST_URI'",
"]",
")",
"?",
"$",
"_SERVER",
"[",
"'REQUEST_URI'",
"]",
":",
"'/'",
";",
"$",
"method",
"=",
"$",
"this",
"->",
"getRequestMethod",
"(",
")",
";",
"$",
"uri",
"=",
"$",
"this",
"->",
"getCurrentUri",
"(",
")",
";",
"// Loop all routes",
"foreach",
"(",
"$",
"this",
"->",
"routes",
"[",
"$",
"method",
"]",
"as",
"$",
"route",
")",
"{",
"// we have a match!",
"if",
"(",
"preg_match_all",
"(",
"'#^'",
".",
"$",
"route",
"[",
"'pattern'",
"]",
".",
"'$#'",
",",
"$",
"uri",
",",
"$",
"matches",
",",
"PREG_OFFSET_CAPTURE",
")",
")",
"{",
"die",
"(",
"\"route matched\"",
")",
";",
"}",
"}",
"die",
"(",
"\"no route matched\"",
")",
";",
"}"
] | match a current request
@return string The Request method to handle | [
"match",
"a",
"current",
"request"
] | 72283a45733a49c1d9c1fc0eba22ff13a802295c | https://github.com/TitaPHP/framework/blob/72283a45733a49c1d9c1fc0eba22ff13a802295c/src/TitaPHP/Http/Router.php#L40-L54 | train |
fridge-project/dbal | src/Fridge/DBAL/Query/Rewriter/PositionalQueryRewriter.php | PositionalQueryRewriter.determinePlaceholderPosition | private static function determinePlaceholderPosition($query, $index, array $placeholdersPositions = array())
{
// The placeholder position.
$placeholderPosition = null;
// Find the previous cached placeholder position in the stack to optimize the current placeholder position
// search.
// The previous parameter index cached.
$previousIndex = $index - 1;
// Iterate each cached placeholder positions to find the previous one & the previous parameter index.
while (($previousIndex >= 0) && ($placeholderPosition === null)) {
// Check if the previous cached placeholder positions exists.
if (isset($placeholdersPositions[$previousIndex])) {
$placeholderPosition = $placeholdersPositions[$previousIndex];
$previousIndex++;
} else {
$previousIndex--;
}
}
// Check if the previous placeholder position has been found.
if ($placeholderPosition === null) {
$previousIndex = 0;
$placeholderPosition = 0;
}
// Determine the query length.
$queryLength = strlen($query);
// Iterate from the previous cached parameter index to the current one.
for ($placeholderIndex = $previousIndex; $placeholderIndex <= $index; $placeholderIndex++) {
// TRUE if we are in an escaped section else FALSE.
$escaped = false;
// Iterate each query char from the previous placeholder position to the end in order to find the current
// placeholder.
while ($placeholderPosition < $queryLength) {
// Switch the escaped flag if the current statement char is an escape delimiter.
if (in_array($query[$placeholderPosition], array('\'', '"'))) {
$escaped = !$escaped;
}
// Check if we are not in an escaped section and if the current char is a placeholder.
if (!$escaped && ($query[$placeholderPosition] === '?')) {
// If we are not on the current placeholder, we increment the placeholder position.
if ($placeholderIndex < $index) {
$placeholderPosition++;
}
break;
}
$placeholderPosition++;
}
// Check if we have found the placeholder position.
if ($placeholderPosition === $queryLength) {
throw QueryRewriterException::positionalPlaceholderDoesNotExist($index, $query);
}
}
return $placeholderPosition;
} | php | private static function determinePlaceholderPosition($query, $index, array $placeholdersPositions = array())
{
// The placeholder position.
$placeholderPosition = null;
// Find the previous cached placeholder position in the stack to optimize the current placeholder position
// search.
// The previous parameter index cached.
$previousIndex = $index - 1;
// Iterate each cached placeholder positions to find the previous one & the previous parameter index.
while (($previousIndex >= 0) && ($placeholderPosition === null)) {
// Check if the previous cached placeholder positions exists.
if (isset($placeholdersPositions[$previousIndex])) {
$placeholderPosition = $placeholdersPositions[$previousIndex];
$previousIndex++;
} else {
$previousIndex--;
}
}
// Check if the previous placeholder position has been found.
if ($placeholderPosition === null) {
$previousIndex = 0;
$placeholderPosition = 0;
}
// Determine the query length.
$queryLength = strlen($query);
// Iterate from the previous cached parameter index to the current one.
for ($placeholderIndex = $previousIndex; $placeholderIndex <= $index; $placeholderIndex++) {
// TRUE if we are in an escaped section else FALSE.
$escaped = false;
// Iterate each query char from the previous placeholder position to the end in order to find the current
// placeholder.
while ($placeholderPosition < $queryLength) {
// Switch the escaped flag if the current statement char is an escape delimiter.
if (in_array($query[$placeholderPosition], array('\'', '"'))) {
$escaped = !$escaped;
}
// Check if we are not in an escaped section and if the current char is a placeholder.
if (!$escaped && ($query[$placeholderPosition] === '?')) {
// If we are not on the current placeholder, we increment the placeholder position.
if ($placeholderIndex < $index) {
$placeholderPosition++;
}
break;
}
$placeholderPosition++;
}
// Check if we have found the placeholder position.
if ($placeholderPosition === $queryLength) {
throw QueryRewriterException::positionalPlaceholderDoesNotExist($index, $query);
}
}
return $placeholderPosition;
} | [
"private",
"static",
"function",
"determinePlaceholderPosition",
"(",
"$",
"query",
",",
"$",
"index",
",",
"array",
"$",
"placeholdersPositions",
"=",
"array",
"(",
")",
")",
"{",
"// The placeholder position.",
"$",
"placeholderPosition",
"=",
"null",
";",
"// Find the previous cached placeholder position in the stack to optimize the current placeholder position",
"// search.",
"// The previous parameter index cached.",
"$",
"previousIndex",
"=",
"$",
"index",
"-",
"1",
";",
"// Iterate each cached placeholder positions to find the previous one & the previous parameter index.",
"while",
"(",
"(",
"$",
"previousIndex",
">=",
"0",
")",
"&&",
"(",
"$",
"placeholderPosition",
"===",
"null",
")",
")",
"{",
"// Check if the previous cached placeholder positions exists.",
"if",
"(",
"isset",
"(",
"$",
"placeholdersPositions",
"[",
"$",
"previousIndex",
"]",
")",
")",
"{",
"$",
"placeholderPosition",
"=",
"$",
"placeholdersPositions",
"[",
"$",
"previousIndex",
"]",
";",
"$",
"previousIndex",
"++",
";",
"}",
"else",
"{",
"$",
"previousIndex",
"--",
";",
"}",
"}",
"// Check if the previous placeholder position has been found.",
"if",
"(",
"$",
"placeholderPosition",
"===",
"null",
")",
"{",
"$",
"previousIndex",
"=",
"0",
";",
"$",
"placeholderPosition",
"=",
"0",
";",
"}",
"// Determine the query length.",
"$",
"queryLength",
"=",
"strlen",
"(",
"$",
"query",
")",
";",
"// Iterate from the previous cached parameter index to the current one.",
"for",
"(",
"$",
"placeholderIndex",
"=",
"$",
"previousIndex",
";",
"$",
"placeholderIndex",
"<=",
"$",
"index",
";",
"$",
"placeholderIndex",
"++",
")",
"{",
"// TRUE if we are in an escaped section else FALSE.",
"$",
"escaped",
"=",
"false",
";",
"// Iterate each query char from the previous placeholder position to the end in order to find the current",
"// placeholder.",
"while",
"(",
"$",
"placeholderPosition",
"<",
"$",
"queryLength",
")",
"{",
"// Switch the escaped flag if the current statement char is an escape delimiter.",
"if",
"(",
"in_array",
"(",
"$",
"query",
"[",
"$",
"placeholderPosition",
"]",
",",
"array",
"(",
"'\\''",
",",
"'\"'",
")",
")",
")",
"{",
"$",
"escaped",
"=",
"!",
"$",
"escaped",
";",
"}",
"// Check if we are not in an escaped section and if the current char is a placeholder.",
"if",
"(",
"!",
"$",
"escaped",
"&&",
"(",
"$",
"query",
"[",
"$",
"placeholderPosition",
"]",
"===",
"'?'",
")",
")",
"{",
"// If we are not on the current placeholder, we increment the placeholder position.",
"if",
"(",
"$",
"placeholderIndex",
"<",
"$",
"index",
")",
"{",
"$",
"placeholderPosition",
"++",
";",
"}",
"break",
";",
"}",
"$",
"placeholderPosition",
"++",
";",
"}",
"// Check if we have found the placeholder position.",
"if",
"(",
"$",
"placeholderPosition",
"===",
"$",
"queryLength",
")",
"{",
"throw",
"QueryRewriterException",
"::",
"positionalPlaceholderDoesNotExist",
"(",
"$",
"index",
",",
"$",
"query",
")",
";",
"}",
"}",
"return",
"$",
"placeholderPosition",
";",
"}"
] | Determines the placeholder position in the query.
Example:
- parameters:
- query: SELECT * FROM foo WHERE foo IN (?) AND bar IN (?)
^ (33) ^ (47)
- index: 1
- cachedPlaceholdersPositions: array(33)
- result:
- placeholderPosition: 47
@param string $query The query.
@param integer $index The query parameter index (indexed by 0).
@param array $placeholdersPositions The cached placeholders positions.
@throws \Fridge\DBAL\Exception\QueryRewriterException If the placeholder does not exist.
@return integer The placeholder position. | [
"Determines",
"the",
"placeholder",
"position",
"in",
"the",
"query",
"."
] | d0b8c3551922d696836487aa0eb1bd74014edcd4 | https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/Query/Rewriter/PositionalQueryRewriter.php#L124-L192 | train |
fridge-project/dbal | src/Fridge/DBAL/Query/Rewriter/PositionalQueryRewriter.php | PositionalQueryRewriter.rewriteQuery | private static function rewriteQuery($query, $placeholderPosition, array $newPlaceholders)
{
return substr($query, 0, $placeholderPosition).
implode(', ', $newPlaceholders).
substr($query, $placeholderPosition + 1);
} | php | private static function rewriteQuery($query, $placeholderPosition, array $newPlaceholders)
{
return substr($query, 0, $placeholderPosition).
implode(', ', $newPlaceholders).
substr($query, $placeholderPosition + 1);
} | [
"private",
"static",
"function",
"rewriteQuery",
"(",
"$",
"query",
",",
"$",
"placeholderPosition",
",",
"array",
"$",
"newPlaceholders",
")",
"{",
"return",
"substr",
"(",
"$",
"query",
",",
"0",
",",
"$",
"placeholderPosition",
")",
".",
"implode",
"(",
"', '",
",",
"$",
"newPlaceholders",
")",
".",
"substr",
"(",
"$",
"query",
",",
"$",
"placeholderPosition",
"+",
"1",
")",
";",
"}"
] | Rewrites the query according to the placeholder position and new placeholders.
Example:
- parameters:
- query: SELECT * FROM foo WHERE foo IN (?)
^ (32)
- placeholderPosition: 32
- newPlaceholders: array('?', '?', '?')
- result:
- rewrittenQuery: SELECT * FROM foo WHERE foo IN (?, ?, ?)
@param string $query The query.
@param integer $placeholderPosition The placeholder position.
@param array $newPlaceholders The new placeholders.
@return string The rewritten query. | [
"Rewrites",
"the",
"query",
"according",
"to",
"the",
"placeholder",
"position",
"and",
"new",
"placeholders",
"."
] | d0b8c3551922d696836487aa0eb1bd74014edcd4 | https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/Query/Rewriter/PositionalQueryRewriter.php#L212-L217 | train |
fridge-project/dbal | src/Fridge/DBAL/Query/Rewriter/PositionalQueryRewriter.php | PositionalQueryRewriter.rewriteParameterAndType | private static function rewriteParameterAndType(array $parameters, array $types, $index)
{
// The parameter value according.
$parameterValue = $parameters[$index];
// The parameter count.
$parameterCount = count($parameterValue);
// Extract the fridge type.
$type = static::extractType($types[$index]);
// Shift parameters and types placed just after the current rewritten position according to the gap.
// This will prepare the parameters & types to be rewritten with new placeholders.
// Determine the interval to shift.
$minPosition = $index;
$maxPosition = max(array_keys($parameters));
// Iterate the interval to shift each of them according to the parameter count.
for ($rewritePosition = $maxPosition; $rewritePosition > $minPosition; $rewritePosition--) {
// Determine the new position.
$newPosition = $rewritePosition + $parameterCount - 1;
// Shift the parameter.
$parameters[$newPosition] = $parameters[$rewritePosition];
// Shift or unset the type if it does not exist.
if (isset($types[$rewritePosition])) {
$types[$newPosition] = $types[$rewritePosition];
} elseif (isset($types[$newPosition])) {
unset($types[$newPosition]);
}
}
// Rewrite parameters and types according to the parameter count.
for ($newPlaceholderIndex = 0; $newPlaceholderIndex < $parameterCount; $newPlaceholderIndex++) {
// Determine the new position.
$newPosition = $index + $newPlaceholderIndex;
// Rewrite the parameter and type.
$parameters[$newPosition] = $parameterValue[$newPlaceholderIndex];
$types[$newPosition] = $type;
}
return array($parameters, $types);
} | php | private static function rewriteParameterAndType(array $parameters, array $types, $index)
{
// The parameter value according.
$parameterValue = $parameters[$index];
// The parameter count.
$parameterCount = count($parameterValue);
// Extract the fridge type.
$type = static::extractType($types[$index]);
// Shift parameters and types placed just after the current rewritten position according to the gap.
// This will prepare the parameters & types to be rewritten with new placeholders.
// Determine the interval to shift.
$minPosition = $index;
$maxPosition = max(array_keys($parameters));
// Iterate the interval to shift each of them according to the parameter count.
for ($rewritePosition = $maxPosition; $rewritePosition > $minPosition; $rewritePosition--) {
// Determine the new position.
$newPosition = $rewritePosition + $parameterCount - 1;
// Shift the parameter.
$parameters[$newPosition] = $parameters[$rewritePosition];
// Shift or unset the type if it does not exist.
if (isset($types[$rewritePosition])) {
$types[$newPosition] = $types[$rewritePosition];
} elseif (isset($types[$newPosition])) {
unset($types[$newPosition]);
}
}
// Rewrite parameters and types according to the parameter count.
for ($newPlaceholderIndex = 0; $newPlaceholderIndex < $parameterCount; $newPlaceholderIndex++) {
// Determine the new position.
$newPosition = $index + $newPlaceholderIndex;
// Rewrite the parameter and type.
$parameters[$newPosition] = $parameterValue[$newPlaceholderIndex];
$types[$newPosition] = $type;
}
return array($parameters, $types);
} | [
"private",
"static",
"function",
"rewriteParameterAndType",
"(",
"array",
"$",
"parameters",
",",
"array",
"$",
"types",
",",
"$",
"index",
")",
"{",
"// The parameter value according.",
"$",
"parameterValue",
"=",
"$",
"parameters",
"[",
"$",
"index",
"]",
";",
"// The parameter count.",
"$",
"parameterCount",
"=",
"count",
"(",
"$",
"parameterValue",
")",
";",
"// Extract the fridge type.",
"$",
"type",
"=",
"static",
"::",
"extractType",
"(",
"$",
"types",
"[",
"$",
"index",
"]",
")",
";",
"// Shift parameters and types placed just after the current rewritten position according to the gap.",
"// This will prepare the parameters & types to be rewritten with new placeholders.",
"// Determine the interval to shift.",
"$",
"minPosition",
"=",
"$",
"index",
";",
"$",
"maxPosition",
"=",
"max",
"(",
"array_keys",
"(",
"$",
"parameters",
")",
")",
";",
"// Iterate the interval to shift each of them according to the parameter count.",
"for",
"(",
"$",
"rewritePosition",
"=",
"$",
"maxPosition",
";",
"$",
"rewritePosition",
">",
"$",
"minPosition",
";",
"$",
"rewritePosition",
"--",
")",
"{",
"// Determine the new position.",
"$",
"newPosition",
"=",
"$",
"rewritePosition",
"+",
"$",
"parameterCount",
"-",
"1",
";",
"// Shift the parameter.",
"$",
"parameters",
"[",
"$",
"newPosition",
"]",
"=",
"$",
"parameters",
"[",
"$",
"rewritePosition",
"]",
";",
"// Shift or unset the type if it does not exist.",
"if",
"(",
"isset",
"(",
"$",
"types",
"[",
"$",
"rewritePosition",
"]",
")",
")",
"{",
"$",
"types",
"[",
"$",
"newPosition",
"]",
"=",
"$",
"types",
"[",
"$",
"rewritePosition",
"]",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"types",
"[",
"$",
"newPosition",
"]",
")",
")",
"{",
"unset",
"(",
"$",
"types",
"[",
"$",
"newPosition",
"]",
")",
";",
"}",
"}",
"// Rewrite parameters and types according to the parameter count.",
"for",
"(",
"$",
"newPlaceholderIndex",
"=",
"0",
";",
"$",
"newPlaceholderIndex",
"<",
"$",
"parameterCount",
";",
"$",
"newPlaceholderIndex",
"++",
")",
"{",
"// Determine the new position.",
"$",
"newPosition",
"=",
"$",
"index",
"+",
"$",
"newPlaceholderIndex",
";",
"// Rewrite the parameter and type.",
"$",
"parameters",
"[",
"$",
"newPosition",
"]",
"=",
"$",
"parameterValue",
"[",
"$",
"newPlaceholderIndex",
"]",
";",
"$",
"types",
"[",
"$",
"newPosition",
"]",
"=",
"$",
"type",
";",
"}",
"return",
"array",
"(",
"$",
"parameters",
",",
"$",
"types",
")",
";",
"}"
] | Rewrites the parameter & type according to the parameter index .
Example:
- parameters:
- parameters: array(array(1, 3, 5))
- types: array('integer[]')
- index: 0
- result:
- rewrittenParameters: array(1, 3, 5)
- rewrittenTypes: array('integer', 'integer', 'integer')
@param array $parameters The query parameters.
@param array $types The query types.
@param integer $index The query parameter index.
@return array 0 => The rewritten parameters, 1 => The rewritten types. | [
"Rewrites",
"the",
"parameter",
"&",
"type",
"according",
"to",
"the",
"parameter",
"index",
"."
] | d0b8c3551922d696836487aa0eb1bd74014edcd4 | https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/Query/Rewriter/PositionalQueryRewriter.php#L237-L284 | train |
ReputationVIP/composer-assets-installer | src/AssetsInstallerPlugin.php | AssetsInstallerPlugin.activate | public function activate(Composer $composer, IOInterface $io)
{
$this->assetsInstaller = new AssetsInstaller($composer, $io);
} | php | public function activate(Composer $composer, IOInterface $io)
{
$this->assetsInstaller = new AssetsInstaller($composer, $io);
} | [
"public",
"function",
"activate",
"(",
"Composer",
"$",
"composer",
",",
"IOInterface",
"$",
"io",
")",
"{",
"$",
"this",
"->",
"assetsInstaller",
"=",
"new",
"AssetsInstaller",
"(",
"$",
"composer",
",",
"$",
"io",
")",
";",
"}"
] | Initializes the plugin
Reads the composer.json file and
retrieves the assets-dir set if any.
This assets-dir is the path where
the other packages assets will be installed
@param Composer $composer
@param IOInterface $io | [
"Initializes",
"the",
"plugin",
"Reads",
"the",
"composer",
".",
"json",
"file",
"and",
"retrieves",
"the",
"assets",
"-",
"dir",
"set",
"if",
"any",
".",
"This",
"assets",
"-",
"dir",
"is",
"the",
"path",
"where",
"the",
"other",
"packages",
"assets",
"will",
"be",
"installed"
] | c8dea009795fe23dcd7f41d8b9a5bf4a970d842b | https://github.com/ReputationVIP/composer-assets-installer/blob/c8dea009795fe23dcd7f41d8b9a5bf4a970d842b/src/AssetsInstallerPlugin.php#L29-L32 | train |
cloudtek/dynamodm | lib/Cloudtek/DynamoDM/Expression/Expr.php | Expr.addCriteria | public function addCriteria(array $criteria)
{
foreach ($criteria as $key => $value) {
$this->attr($key)->matches($value);
}
return $this;
} | php | public function addCriteria(array $criteria)
{
foreach ($criteria as $key => $value) {
$this->attr($key)->matches($value);
}
return $this;
} | [
"public",
"function",
"addCriteria",
"(",
"array",
"$",
"criteria",
")",
"{",
"foreach",
"(",
"$",
"criteria",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"attr",
"(",
"$",
"key",
")",
"->",
"matches",
"(",
"$",
"value",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Add an array of criteria to the expression as AND clauses.
@see QueryBuilder::addCriteria()
@param array $criteria values indexed by property name
@return QueryBuilder|$this | [
"Add",
"an",
"array",
"of",
"criteria",
"to",
"the",
"expression",
"as",
"AND",
"clauses",
"."
] | 119d355e2c5cbaef1f867970349b4432f5704fcd | https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/Expression/Expr.php#L68-L75 | train |
cloudtek/dynamodm | lib/Cloudtek/DynamoDM/Expression/Expr.php | Expr.addOr | public function addOr(Expr $subexpression /*, $subexpression2, ... */)
{
$or = new Condition\Logical\AddOr;
$or->add(...array_map(
function (Expr $expr) {
return $expr->condition;
},
func_get_args()
));
$this->addCondition($or);
return $this;
} | php | public function addOr(Expr $subexpression /*, $subexpression2, ... */)
{
$or = new Condition\Logical\AddOr;
$or->add(...array_map(
function (Expr $expr) {
return $expr->condition;
},
func_get_args()
));
$this->addCondition($or);
return $this;
} | [
"public",
"function",
"addOr",
"(",
"Expr",
"$",
"subexpression",
"/*, $subexpression2, ... */",
")",
"{",
"$",
"or",
"=",
"new",
"Condition",
"\\",
"Logical",
"\\",
"AddOr",
";",
"$",
"or",
"->",
"add",
"(",
"...",
"array_map",
"(",
"function",
"(",
"Expr",
"$",
"expr",
")",
"{",
"return",
"$",
"expr",
"->",
"condition",
";",
"}",
",",
"func_get_args",
"(",
")",
")",
")",
";",
"$",
"this",
"->",
"addCondition",
"(",
"$",
"or",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Add one or more OR clauses to the expression.
@see QueryBuilder::addOr()
@param Expr $subexpression,...
@return QueryBuilder|$this | [
"Add",
"one",
"or",
"more",
"OR",
"clauses",
"to",
"the",
"expression",
"."
] | 119d355e2c5cbaef1f867970349b4432f5704fcd | https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/Expression/Expr.php#L86-L99 | train |
cloudtek/dynamodm | lib/Cloudtek/DynamoDM/Expression/Expr.php | Expr.attr | public function attr($name, $discriminatorValue = null)
{
if (empty($name)) {
throw new \InvalidArgumentException;
}
return new Operand\Attribute($this, $name, $discriminatorValue);
} | php | public function attr($name, $discriminatorValue = null)
{
if (empty($name)) {
throw new \InvalidArgumentException;
}
return new Operand\Attribute($this, $name, $discriminatorValue);
} | [
"public",
"function",
"attr",
"(",
"$",
"name",
",",
"$",
"discriminatorValue",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"name",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
";",
"}",
"return",
"new",
"Operand",
"\\",
"Attribute",
"(",
"$",
"this",
",",
"$",
"name",
",",
"$",
"discriminatorValue",
")",
";",
"}"
] | Return an attribute object, used for building an expression.
@see QueryBuilder::attr()
@param string $name Top-level attribute name.
@param string|null $discriminatorValue
@return Operand\Attribute|Operand\RootAttribute | [
"Return",
"an",
"attribute",
"object",
"used",
"for",
"building",
"an",
"expression",
"."
] | 119d355e2c5cbaef1f867970349b4432f5704fcd | https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/Expression/Expr.php#L111-L118 | train |
cloudtek/dynamodm | lib/Cloudtek/DynamoDM/Expression/Expr.php | Expr.not | public function not(Expr $subexpression)
{
$not = new Condition\Logical\Not;
$not->add($subexpression->condition);
return $this;
} | php | public function not(Expr $subexpression)
{
$not = new Condition\Logical\Not;
$not->add($subexpression->condition);
return $this;
} | [
"public",
"function",
"not",
"(",
"Expr",
"$",
"subexpression",
")",
"{",
"$",
"not",
"=",
"new",
"Condition",
"\\",
"Logical",
"\\",
"Not",
";",
"$",
"not",
"->",
"add",
"(",
"$",
"subexpression",
"->",
"condition",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Add a NOT clause to the expression.
@see QueryBuilder::not()
@param Expr $subexpression
@return QueryBuilder|$this | [
"Add",
"a",
"NOT",
"clause",
"to",
"the",
"expression",
"."
] | 119d355e2c5cbaef1f867970349b4432f5704fcd | https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/Expression/Expr.php#L212-L218 | train |
cloudtek/dynamodm | lib/Cloudtek/DynamoDM/Expression/Expr.php | Expr.value | public function value($value)
{
if (!$value instanceof Operand\OperandInterface && !$value instanceof Update\Func) {
$value = new Operand\Value($this, $value);
}
return $value;
} | php | public function value($value)
{
if (!$value instanceof Operand\OperandInterface && !$value instanceof Update\Func) {
$value = new Operand\Value($this, $value);
}
return $value;
} | [
"public",
"function",
"value",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"$",
"value",
"instanceof",
"Operand",
"\\",
"OperandInterface",
"&&",
"!",
"$",
"value",
"instanceof",
"Update",
"\\",
"Func",
")",
"{",
"$",
"value",
"=",
"new",
"Operand",
"\\",
"Value",
"(",
"$",
"this",
",",
"$",
"value",
")",
";",
"}",
"return",
"$",
"value",
";",
"}"
] | Return a value object, used for building an expression.
@param Operand\OperandInterface|Update\Func|mixed $value
@return Operand\Value|Operand\OperandInterface|Update\Func|mixed | [
"Return",
"a",
"value",
"object",
"used",
"for",
"building",
"an",
"expression",
"."
] | 119d355e2c5cbaef1f867970349b4432f5704fcd | https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/Expression/Expr.php#L227-L234 | train |
mermshaus/kaloa-renderer | src/Inigo/Parser.php | Parser.getNextTag | private function getNextTag(&$s, $i, &$position)
{
$j = mb_strpos($s, '[', $i);
$k = mb_strpos($s, ']', $j + 1);
if ($j === false || $k === false) {
$position = false;
return null;
}
$t = mb_substr($s, $j + 1, $k - ($j + 1));
$l = mb_strrpos($t, '[');
if ($l !== false) {
$j += $l + 1;
}
$position = $j;
$tagString = mb_substr($s, $j, $k - $j + 1);
return new Tag($tagString, $this->getHandlers());
} | php | private function getNextTag(&$s, $i, &$position)
{
$j = mb_strpos($s, '[', $i);
$k = mb_strpos($s, ']', $j + 1);
if ($j === false || $k === false) {
$position = false;
return null;
}
$t = mb_substr($s, $j + 1, $k - ($j + 1));
$l = mb_strrpos($t, '[');
if ($l !== false) {
$j += $l + 1;
}
$position = $j;
$tagString = mb_substr($s, $j, $k - $j + 1);
return new Tag($tagString, $this->getHandlers());
} | [
"private",
"function",
"getNextTag",
"(",
"&",
"$",
"s",
",",
"$",
"i",
",",
"&",
"$",
"position",
")",
"{",
"$",
"j",
"=",
"mb_strpos",
"(",
"$",
"s",
",",
"'['",
",",
"$",
"i",
")",
";",
"$",
"k",
"=",
"mb_strpos",
"(",
"$",
"s",
",",
"']'",
",",
"$",
"j",
"+",
"1",
")",
";",
"if",
"(",
"$",
"j",
"===",
"false",
"||",
"$",
"k",
"===",
"false",
")",
"{",
"$",
"position",
"=",
"false",
";",
"return",
"null",
";",
"}",
"$",
"t",
"=",
"mb_substr",
"(",
"$",
"s",
",",
"$",
"j",
"+",
"1",
",",
"$",
"k",
"-",
"(",
"$",
"j",
"+",
"1",
")",
")",
";",
"$",
"l",
"=",
"mb_strrpos",
"(",
"$",
"t",
",",
"'['",
")",
";",
"if",
"(",
"$",
"l",
"!==",
"false",
")",
"{",
"$",
"j",
"+=",
"$",
"l",
"+",
"1",
";",
"}",
"$",
"position",
"=",
"$",
"j",
";",
"$",
"tagString",
"=",
"mb_substr",
"(",
"$",
"s",
",",
"$",
"j",
",",
"$",
"k",
"-",
"$",
"j",
"+",
"1",
")",
";",
"return",
"new",
"Tag",
"(",
"$",
"tagString",
",",
"$",
"this",
"->",
"getHandlers",
"(",
")",
")",
";",
"}"
] | Gets the next tag
@param string $s String to parse
@param int $i Offset where search begins
@param int $position Will be filled with next tag's offset (FALSE if
there are no more tags)
@return Tag | [
"Gets",
"the",
"next",
"tag"
] | ece78bfa1d5cec75a1409759e1f944b8c47d2aac | https://github.com/mermshaus/kaloa-renderer/blob/ece78bfa1d5cec75a1409759e1f944b8c47d2aac/src/Inigo/Parser.php#L193-L215 | train |
mermshaus/kaloa-renderer | src/Inigo/Parser.php | Parser.formatString | private function formatString($s)
{
static $last_tag = null;
if ($this->m_stack->count() > 0
&& $this->m_stack->top()->isOfType(self::TAG_PRE)
) {
// Do not format text inside of TAG_PRE tags
return $s;
}
/*
* TODO Replace double-quotes alternately with nice left and right
* quotes
*/
if ($last_tag !== null) {
#echo $last_tag->getName();
}
#echo '|' . $s . '|';
// opening quote
if ($last_tag !== null && $last_tag->isOfType(self::TAG_INLINE)) {
$s = preg_replace('/([\s])"/', '\1»', $s);
#echo 'without';
} else {
$s = preg_replace('/([\s]|^)"/', '\1»', $s);
}
// [X][X] will always be rendered as [S][S], not as [S][E]
$s = preg_replace('/(»)"/', '\1»', $s);
#echo '<br />';
// everything else is closing quote
$s = str_replace('"', '«', $s);
$s = str_replace('--', '–', $s);
if ($this->m_stack->count() > 0) {
$last_tag = $this->m_stack->top();
} else {
$last_tag = null;
}
$e = function ($s) { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); };
return $e($s);
} | php | private function formatString($s)
{
static $last_tag = null;
if ($this->m_stack->count() > 0
&& $this->m_stack->top()->isOfType(self::TAG_PRE)
) {
// Do not format text inside of TAG_PRE tags
return $s;
}
/*
* TODO Replace double-quotes alternately with nice left and right
* quotes
*/
if ($last_tag !== null) {
#echo $last_tag->getName();
}
#echo '|' . $s . '|';
// opening quote
if ($last_tag !== null && $last_tag->isOfType(self::TAG_INLINE)) {
$s = preg_replace('/([\s])"/', '\1»', $s);
#echo 'without';
} else {
$s = preg_replace('/([\s]|^)"/', '\1»', $s);
}
// [X][X] will always be rendered as [S][S], not as [S][E]
$s = preg_replace('/(»)"/', '\1»', $s);
#echo '<br />';
// everything else is closing quote
$s = str_replace('"', '«', $s);
$s = str_replace('--', '–', $s);
if ($this->m_stack->count() > 0) {
$last_tag = $this->m_stack->top();
} else {
$last_tag = null;
}
$e = function ($s) { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); };
return $e($s);
} | [
"private",
"function",
"formatString",
"(",
"$",
"s",
")",
"{",
"static",
"$",
"last_tag",
"=",
"null",
";",
"if",
"(",
"$",
"this",
"->",
"m_stack",
"->",
"count",
"(",
")",
">",
"0",
"&&",
"$",
"this",
"->",
"m_stack",
"->",
"top",
"(",
")",
"->",
"isOfType",
"(",
"self",
"::",
"TAG_PRE",
")",
")",
"{",
"// Do not format text inside of TAG_PRE tags",
"return",
"$",
"s",
";",
"}",
"/*\n * TODO Replace double-quotes alternately with nice left and right\n * quotes\n */",
"if",
"(",
"$",
"last_tag",
"!==",
"null",
")",
"{",
"#echo $last_tag->getName();",
"}",
"#echo '|' . $s . '|';",
"// opening quote",
"if",
"(",
"$",
"last_tag",
"!==",
"null",
"&&",
"$",
"last_tag",
"->",
"isOfType",
"(",
"self",
"::",
"TAG_INLINE",
")",
")",
"{",
"$",
"s",
"=",
"preg_replace",
"(",
"'/([\\s])"/'",
",",
"'\\1»'",
",",
"$",
"s",
")",
";",
"#echo 'without';",
"}",
"else",
"{",
"$",
"s",
"=",
"preg_replace",
"(",
"'/([\\s]|^)"/'",
",",
"'\\1»'",
",",
"$",
"s",
")",
";",
"}",
"// [X][X] will always be rendered as [S][S], not as [S][E]",
"$",
"s",
"=",
"preg_replace",
"(",
"'/(»)"/'",
",",
"'\\1»'",
",",
"$",
"s",
")",
";",
"#echo '<br />';",
"// everything else is closing quote",
"$",
"s",
"=",
"str_replace",
"(",
"'"'",
",",
"'«'",
",",
"$",
"s",
")",
";",
"$",
"s",
"=",
"str_replace",
"(",
"'--'",
",",
"'–'",
",",
"$",
"s",
")",
";",
"if",
"(",
"$",
"this",
"->",
"m_stack",
"->",
"count",
"(",
")",
">",
"0",
")",
"{",
"$",
"last_tag",
"=",
"$",
"this",
"->",
"m_stack",
"->",
"top",
"(",
")",
";",
"}",
"else",
"{",
"$",
"last_tag",
"=",
"null",
";",
"}",
"$",
"e",
"=",
"function",
"(",
"$",
"s",
")",
"{",
"return",
"htmlspecialchars",
"(",
"$",
"s",
",",
"ENT_QUOTES",
",",
"'UTF-8'",
")",
";",
"}",
";",
"return",
"$",
"e",
"(",
"$",
"s",
")",
";",
"}"
] | Formats small pieces of CDATA
@param string $s
@return string | [
"Formats",
"small",
"pieces",
"of",
"CDATA"
] | ece78bfa1d5cec75a1409759e1f944b8c47d2aac | https://github.com/mermshaus/kaloa-renderer/blob/ece78bfa1d5cec75a1409759e1f944b8c47d2aac/src/Inigo/Parser.php#L409-L460 | train |
mermshaus/kaloa-renderer | src/Inigo/Parser.php | Parser.printCData | private function printCData(&$cdata, $outline = false)
{
$cdata = trim($cdata);
$ret = '';
/*$t = '';
if ($outline) {
//echo $tag->getName();
$t = ' yes';
}*/
if ($cdata === '') {
return $ret;
}
//$e = function ($s) { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); };
if (
// All top-level blocks of CDATA have to be surrounded with <p>
//($this->m_stack->size() == 0)
// An outline tag starts after this CDATA block
//|| ($tag != null)
/*||*/ $outline
/*
* Obvious. Should make a difference between \n and \n\n though
* TODO
*/
|| (mb_strpos($cdata, "\n"))
/* TODO Add FORCE_PARAGRAPHS parameter to tags (li?, blockquote, ...) */
|| ($this->m_stack->count() > 0
&& $this->m_stack->top()->isOfType(self::TAG_FORCE_PARAGRAPHS))
) {
if ($this->m_stack->count() > 0
&& $this->m_stack->top()->isOfType(self::TAG_PRE)
) {
/*
* We are inside of a TAG_PRE tag and do not want the CDATA to
* be reformatted
*/
//$ret .= '[CDATA' . $t . ']' . $cdata . '[/CDATA]';
$ret .= $cdata;
} else {
//$cdata = $e($cdata);
$cdata = str_replace("\n\n", '</p><p>', $cdata);
$cdata = str_replace("\n", "<br />\n", $cdata);
$cdata = str_replace('</p><p>', "</p>\n\n<p>", $cdata);
//$ret .= '<p>' . '[CDATA' . $t . ']' . $cdata . '[/CDATA]' . "</p>\n";
$ret .= '<p>' . $cdata . "</p>\n";
}
} else {
/* No need to add paragraph markup (something like [li]CDATA[/li]) */
//$ret .= '[CDATA' . $t . ']' . $cdata . '[/CDATA]';
$ret .= $cdata;
}
$cdata = '';
return $ret;
} | php | private function printCData(&$cdata, $outline = false)
{
$cdata = trim($cdata);
$ret = '';
/*$t = '';
if ($outline) {
//echo $tag->getName();
$t = ' yes';
}*/
if ($cdata === '') {
return $ret;
}
//$e = function ($s) { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); };
if (
// All top-level blocks of CDATA have to be surrounded with <p>
//($this->m_stack->size() == 0)
// An outline tag starts after this CDATA block
//|| ($tag != null)
/*||*/ $outline
/*
* Obvious. Should make a difference between \n and \n\n though
* TODO
*/
|| (mb_strpos($cdata, "\n"))
/* TODO Add FORCE_PARAGRAPHS parameter to tags (li?, blockquote, ...) */
|| ($this->m_stack->count() > 0
&& $this->m_stack->top()->isOfType(self::TAG_FORCE_PARAGRAPHS))
) {
if ($this->m_stack->count() > 0
&& $this->m_stack->top()->isOfType(self::TAG_PRE)
) {
/*
* We are inside of a TAG_PRE tag and do not want the CDATA to
* be reformatted
*/
//$ret .= '[CDATA' . $t . ']' . $cdata . '[/CDATA]';
$ret .= $cdata;
} else {
//$cdata = $e($cdata);
$cdata = str_replace("\n\n", '</p><p>', $cdata);
$cdata = str_replace("\n", "<br />\n", $cdata);
$cdata = str_replace('</p><p>', "</p>\n\n<p>", $cdata);
//$ret .= '<p>' . '[CDATA' . $t . ']' . $cdata . '[/CDATA]' . "</p>\n";
$ret .= '<p>' . $cdata . "</p>\n";
}
} else {
/* No need to add paragraph markup (something like [li]CDATA[/li]) */
//$ret .= '[CDATA' . $t . ']' . $cdata . '[/CDATA]';
$ret .= $cdata;
}
$cdata = '';
return $ret;
} | [
"private",
"function",
"printCData",
"(",
"&",
"$",
"cdata",
",",
"$",
"outline",
"=",
"false",
")",
"{",
"$",
"cdata",
"=",
"trim",
"(",
"$",
"cdata",
")",
";",
"$",
"ret",
"=",
"''",
";",
"/*$t = '';\n\n if ($outline) {\n //echo $tag->getName();\n $t = ' yes';\n }*/",
"if",
"(",
"$",
"cdata",
"===",
"''",
")",
"{",
"return",
"$",
"ret",
";",
"}",
"//$e = function ($s) { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); };",
"if",
"(",
"// All top-level blocks of CDATA have to be surrounded with <p>",
"//($this->m_stack->size() == 0)",
"// An outline tag starts after this CDATA block",
"//|| ($tag != null)",
"/*||*/",
"$",
"outline",
"/*\n * Obvious. Should make a difference between \\n and \\n\\n though\n * TODO\n */",
"||",
"(",
"mb_strpos",
"(",
"$",
"cdata",
",",
"\"\\n\"",
")",
")",
"/* TODO Add FORCE_PARAGRAPHS parameter to tags (li?, blockquote, ...) */",
"||",
"(",
"$",
"this",
"->",
"m_stack",
"->",
"count",
"(",
")",
">",
"0",
"&&",
"$",
"this",
"->",
"m_stack",
"->",
"top",
"(",
")",
"->",
"isOfType",
"(",
"self",
"::",
"TAG_FORCE_PARAGRAPHS",
")",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"m_stack",
"->",
"count",
"(",
")",
">",
"0",
"&&",
"$",
"this",
"->",
"m_stack",
"->",
"top",
"(",
")",
"->",
"isOfType",
"(",
"self",
"::",
"TAG_PRE",
")",
")",
"{",
"/*\n * We are inside of a TAG_PRE tag and do not want the CDATA to\n * be reformatted\n */",
"//$ret .= '[CDATA' . $t . ']' . $cdata . '[/CDATA]';",
"$",
"ret",
".=",
"$",
"cdata",
";",
"}",
"else",
"{",
"//$cdata = $e($cdata);",
"$",
"cdata",
"=",
"str_replace",
"(",
"\"\\n\\n\"",
",",
"'</p><p>'",
",",
"$",
"cdata",
")",
";",
"$",
"cdata",
"=",
"str_replace",
"(",
"\"\\n\"",
",",
"\"<br />\\n\"",
",",
"$",
"cdata",
")",
";",
"$",
"cdata",
"=",
"str_replace",
"(",
"'</p><p>'",
",",
"\"</p>\\n\\n<p>\"",
",",
"$",
"cdata",
")",
";",
"//$ret .= '<p>' . '[CDATA' . $t . ']' . $cdata . '[/CDATA]' . \"</p>\\n\";",
"$",
"ret",
".=",
"'<p>'",
".",
"$",
"cdata",
".",
"\"</p>\\n\"",
";",
"}",
"}",
"else",
"{",
"/* No need to add paragraph markup (something like [li]CDATA[/li]) */",
"//$ret .= '[CDATA' . $t . ']' . $cdata . '[/CDATA]';",
"$",
"ret",
".=",
"$",
"cdata",
";",
"}",
"$",
"cdata",
"=",
"''",
";",
"return",
"$",
"ret",
";",
"}"
] | Formats whole blocks of CDATA
@param string $cdata
@param boolean $outline
@return string | [
"Formats",
"whole",
"blocks",
"of",
"CDATA"
] | ece78bfa1d5cec75a1409759e1f944b8c47d2aac | https://github.com/mermshaus/kaloa-renderer/blob/ece78bfa1d5cec75a1409759e1f944b8c47d2aac/src/Inigo/Parser.php#L469-L534 | train |
pdscopes/php-arrays | src/Collection.php | Collection.nth | public function nth($position)
{
if ($position < 0) {
$position = $this->count() + $position;
}
if ($position < 0 || $this->count() < $position) {
throw new \InvalidArgumentException('Invalid Position');
}
$slice = array_slice($this->items, $position, 1);
return empty($slice) ? null : reset($slice);
} | php | public function nth($position)
{
if ($position < 0) {
$position = $this->count() + $position;
}
if ($position < 0 || $this->count() < $position) {
throw new \InvalidArgumentException('Invalid Position');
}
$slice = array_slice($this->items, $position, 1);
return empty($slice) ? null : reset($slice);
} | [
"public",
"function",
"nth",
"(",
"$",
"position",
")",
"{",
"if",
"(",
"$",
"position",
"<",
"0",
")",
"{",
"$",
"position",
"=",
"$",
"this",
"->",
"count",
"(",
")",
"+",
"$",
"position",
";",
"}",
"if",
"(",
"$",
"position",
"<",
"0",
"||",
"$",
"this",
"->",
"count",
"(",
")",
"<",
"$",
"position",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Invalid Position'",
")",
";",
"}",
"$",
"slice",
"=",
"array_slice",
"(",
"$",
"this",
"->",
"items",
",",
"$",
"position",
",",
"1",
")",
";",
"return",
"empty",
"(",
"$",
"slice",
")",
"?",
"null",
":",
"reset",
"(",
"$",
"slice",
")",
";",
"}"
] | Get the nth item in the collection.
@param int $position
@return mixed | [
"Get",
"the",
"nth",
"item",
"in",
"the",
"collection",
"."
] | 4648ef6d34a63682f4cb367716ba7c205b60ae1f | https://github.com/pdscopes/php-arrays/blob/4648ef6d34a63682f4cb367716ba7c205b60ae1f/src/Collection.php#L87-L98 | train |
pdscopes/php-arrays | src/Collection.php | Collection.implode | public function implode($glue = '', callable $callback = null)
{
return implode($glue, $callback ? array_map($callback, $this->items) : $this->items);
} | php | public function implode($glue = '', callable $callback = null)
{
return implode($glue, $callback ? array_map($callback, $this->items) : $this->items);
} | [
"public",
"function",
"implode",
"(",
"$",
"glue",
"=",
"''",
",",
"callable",
"$",
"callback",
"=",
"null",
")",
"{",
"return",
"implode",
"(",
"$",
"glue",
",",
"$",
"callback",
"?",
"array_map",
"(",
"$",
"callback",
",",
"$",
"this",
"->",
"items",
")",
":",
"$",
"this",
"->",
"items",
")",
";",
"}"
] | Implode the collection values.
@see implode()
@param string $glue
@param callable|null $callback
@return string | [
"Implode",
"the",
"collection",
"values",
"."
] | 4648ef6d34a63682f4cb367716ba7c205b60ae1f | https://github.com/pdscopes/php-arrays/blob/4648ef6d34a63682f4cb367716ba7c205b60ae1f/src/Collection.php#L349-L352 | train |
phpffcms/ffcms-core | src/Exception/TemplateException.php | TemplateException.display | public function display()
{
// hide path root and stip tags from exception message
$msg = Str::replace(root, '$DOCUMENT_ROOT', $this->getMessage());
$msg = App::$Security->strip_tags($msg);
// get message translation
$this->text = App::$Translate->get('Default', $this->text, ['e' => $msg]);
// if exception is throwed not from html-based environment
if (env_type !== 'html') {
if (env_type === 'json') {
return (new JsonException($msg))->display();
} else {
return $this->text;
}
}
// add notification in debug bar if exist
if (App::$Debug !== null) {
App::$Debug->addException($this);
}
// return rendered result
return $this->buildFakePage();
} | php | public function display()
{
// hide path root and stip tags from exception message
$msg = Str::replace(root, '$DOCUMENT_ROOT', $this->getMessage());
$msg = App::$Security->strip_tags($msg);
// get message translation
$this->text = App::$Translate->get('Default', $this->text, ['e' => $msg]);
// if exception is throwed not from html-based environment
if (env_type !== 'html') {
if (env_type === 'json') {
return (new JsonException($msg))->display();
} else {
return $this->text;
}
}
// add notification in debug bar if exist
if (App::$Debug !== null) {
App::$Debug->addException($this);
}
// return rendered result
return $this->buildFakePage();
} | [
"public",
"function",
"display",
"(",
")",
"{",
"// hide path root and stip tags from exception message",
"$",
"msg",
"=",
"Str",
"::",
"replace",
"(",
"root",
",",
"'$DOCUMENT_ROOT'",
",",
"$",
"this",
"->",
"getMessage",
"(",
")",
")",
";",
"$",
"msg",
"=",
"App",
"::",
"$",
"Security",
"->",
"strip_tags",
"(",
"$",
"msg",
")",
";",
"// get message translation",
"$",
"this",
"->",
"text",
"=",
"App",
"::",
"$",
"Translate",
"->",
"get",
"(",
"'Default'",
",",
"$",
"this",
"->",
"text",
",",
"[",
"'e'",
"=>",
"$",
"msg",
"]",
")",
";",
"// if exception is throwed not from html-based environment",
"if",
"(",
"env_type",
"!==",
"'html'",
")",
"{",
"if",
"(",
"env_type",
"===",
"'json'",
")",
"{",
"return",
"(",
"new",
"JsonException",
"(",
"$",
"msg",
")",
")",
"->",
"display",
"(",
")",
";",
"}",
"else",
"{",
"return",
"$",
"this",
"->",
"text",
";",
"}",
"}",
"// add notification in debug bar if exist",
"if",
"(",
"App",
"::",
"$",
"Debug",
"!==",
"null",
")",
"{",
"App",
"::",
"$",
"Debug",
"->",
"addException",
"(",
"$",
"this",
")",
";",
"}",
"// return rendered result",
"return",
"$",
"this",
"->",
"buildFakePage",
"(",
")",
";",
"}"
] | Display exception template
@return string | [
"Display",
"exception",
"template"
] | 44a309553ef9f115ccfcfd71f2ac6e381c612082 | https://github.com/phpffcms/ffcms-core/blob/44a309553ef9f115ccfcfd71f2ac6e381c612082/src/Exception/TemplateException.php#L20-L44 | train |
phpffcms/ffcms-core | src/Exception/TemplateException.php | TemplateException.buildFakePage | protected function buildFakePage()
{
try {
$rawResponse = App::$View->render('_core/exceptions/' . $this->tpl, ['msg' => $this->text]);
if (Str::likeEmpty($rawResponse)) {
$rawResponse = $this->text;
}
} catch (\Exception $e) {
$rawResponse = $this->text;
}
// set status code for header
App::$Response->setStatusCode((int)$this->status);
// return compiled html output
return $rawResponse;
} | php | protected function buildFakePage()
{
try {
$rawResponse = App::$View->render('_core/exceptions/' . $this->tpl, ['msg' => $this->text]);
if (Str::likeEmpty($rawResponse)) {
$rawResponse = $this->text;
}
} catch (\Exception $e) {
$rawResponse = $this->text;
}
// set status code for header
App::$Response->setStatusCode((int)$this->status);
// return compiled html output
return $rawResponse;
} | [
"protected",
"function",
"buildFakePage",
"(",
")",
"{",
"try",
"{",
"$",
"rawResponse",
"=",
"App",
"::",
"$",
"View",
"->",
"render",
"(",
"'_core/exceptions/'",
".",
"$",
"this",
"->",
"tpl",
",",
"[",
"'msg'",
"=>",
"$",
"this",
"->",
"text",
"]",
")",
";",
"if",
"(",
"Str",
"::",
"likeEmpty",
"(",
"$",
"rawResponse",
")",
")",
"{",
"$",
"rawResponse",
"=",
"$",
"this",
"->",
"text",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"$",
"rawResponse",
"=",
"$",
"this",
"->",
"text",
";",
"}",
"// set status code for header",
"App",
"::",
"$",
"Response",
"->",
"setStatusCode",
"(",
"(",
"int",
")",
"$",
"this",
"->",
"status",
")",
";",
"// return compiled html output",
"return",
"$",
"rawResponse",
";",
"}"
] | Build fake page with error based on fake controller initiation | [
"Build",
"fake",
"page",
"with",
"error",
"based",
"on",
"fake",
"controller",
"initiation"
] | 44a309553ef9f115ccfcfd71f2ac6e381c612082 | https://github.com/phpffcms/ffcms-core/blob/44a309553ef9f115ccfcfd71f2ac6e381c612082/src/Exception/TemplateException.php#L49-L63 | train |
spoom-php/core | src/extension/Event.php | Event.emitter | public static function emitter(): EmitterInterface {
if( !isset( self::$emitter_map[ static::class ] ) ) {
// this should find the first subclass after the `Event`. Get the parent list (it's sorted from the latest parent, so we have to reverse it), and select the one after the `Event` baseclass
$class = array_reverse( array_values( class_parents( static::class ) ) )[1] ?? static::class;
// Fill the subclass cache with the found class's cache (and create it if not exists). This is for performance reasons, keep parent class calculations minimal
self::$emitter_map[ static::class ] = self::$emitter_map[ $class ] ?? (self::$emitter_map[ $class ] = new Emitter());
}
return self::$emitter_map[ static::class ];
} | php | public static function emitter(): EmitterInterface {
if( !isset( self::$emitter_map[ static::class ] ) ) {
// this should find the first subclass after the `Event`. Get the parent list (it's sorted from the latest parent, so we have to reverse it), and select the one after the `Event` baseclass
$class = array_reverse( array_values( class_parents( static::class ) ) )[1] ?? static::class;
// Fill the subclass cache with the found class's cache (and create it if not exists). This is for performance reasons, keep parent class calculations minimal
self::$emitter_map[ static::class ] = self::$emitter_map[ $class ] ?? (self::$emitter_map[ $class ] = new Emitter());
}
return self::$emitter_map[ static::class ];
} | [
"public",
"static",
"function",
"emitter",
"(",
")",
":",
"EmitterInterface",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"emitter_map",
"[",
"static",
"::",
"class",
"]",
")",
")",
"{",
"// this should find the first subclass after the `Event`. Get the parent list (it's sorted from the latest parent, so we have to reverse it), and select the one after the `Event` baseclass",
"$",
"class",
"=",
"array_reverse",
"(",
"array_values",
"(",
"class_parents",
"(",
"static",
"::",
"class",
")",
")",
")",
"[",
"1",
"]",
"??",
"static",
"::",
"class",
";",
"// Fill the subclass cache with the found class's cache (and create it if not exists). This is for performance reasons, keep parent class calculations minimal",
"self",
"::",
"$",
"emitter_map",
"[",
"static",
"::",
"class",
"]",
"=",
"self",
"::",
"$",
"emitter_map",
"[",
"$",
"class",
"]",
"??",
"(",
"self",
"::",
"$",
"emitter_map",
"[",
"$",
"class",
"]",
"=",
"new",
"Emitter",
"(",
")",
")",
";",
"}",
"return",
"self",
"::",
"$",
"emitter_map",
"[",
"static",
"::",
"class",
"]",
";",
"}"
] | Get the event's emitter, to manipulate callbacks for the event | [
"Get",
"the",
"event",
"s",
"emitter",
"to",
"manipulate",
"callbacks",
"for",
"the",
"event"
] | ea7184213352fa2fad7636927a019e5798734e04 | https://github.com/spoom-php/core/blob/ea7184213352fa2fad7636927a019e5798734e04/src/extension/Event.php#L74-L86 | train |
t3v/t3v_core | Classes/Utility/Page/BodyTagUtility.php | BodyTagUtility.build | public function build(string $bodyCssClass = self::DEFAULT_BODY_CSS_CLASS): string {
$page = $this->pageService->getCurrentPage();
$backendLayout = $this->pageService->getBackendLayoutForPage($page['uid']);
if (!empty($backendLayout)) {
$bodyCssClass = "{$backendLayout} {$bodyCssClass}";
}
return '<body class="' . $bodyCssClass . '">';
} | php | public function build(string $bodyCssClass = self::DEFAULT_BODY_CSS_CLASS): string {
$page = $this->pageService->getCurrentPage();
$backendLayout = $this->pageService->getBackendLayoutForPage($page['uid']);
if (!empty($backendLayout)) {
$bodyCssClass = "{$backendLayout} {$bodyCssClass}";
}
return '<body class="' . $bodyCssClass . '">';
} | [
"public",
"function",
"build",
"(",
"string",
"$",
"bodyCssClass",
"=",
"self",
"::",
"DEFAULT_BODY_CSS_CLASS",
")",
":",
"string",
"{",
"$",
"page",
"=",
"$",
"this",
"->",
"pageService",
"->",
"getCurrentPage",
"(",
")",
";",
"$",
"backendLayout",
"=",
"$",
"this",
"->",
"pageService",
"->",
"getBackendLayoutForPage",
"(",
"$",
"page",
"[",
"'uid'",
"]",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"backendLayout",
")",
")",
"{",
"$",
"bodyCssClass",
"=",
"\"{$backendLayout} {$bodyCssClass}\"",
";",
"}",
"return",
"'<body class=\"'",
".",
"$",
"bodyCssClass",
".",
"'\">'",
";",
"}"
] | Builds a body tag.
@param string $bodyCssClass The CSS class of the body tag, defaults to `BodyTagUtility::DEFAULT_BODY_CSS_CLASS`
@return string The body tag | [
"Builds",
"a",
"body",
"tag",
"."
] | 8c04b7688cc2773f11fcc87fda3f7cd53d80a980 | https://github.com/t3v/t3v_core/blob/8c04b7688cc2773f11fcc87fda3f7cd53d80a980/Classes/Utility/Page/BodyTagUtility.php#L40-L49 | train |
freialib/ran.tools | src/Trait/Meta.php | MetaTrait.addmeta | function addmeta($name, $values = null) {
if ($values != null) {
foreach ($values as $value) {
$this->add($name, $value);
}
}
return $this;
} | php | function addmeta($name, $values = null) {
if ($values != null) {
foreach ($values as $value) {
$this->add($name, $value);
}
}
return $this;
} | [
"function",
"addmeta",
"(",
"$",
"name",
",",
"$",
"values",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"values",
"!=",
"null",
")",
"{",
"foreach",
"(",
"$",
"values",
"as",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"add",
"(",
"$",
"name",
",",
"$",
"value",
")",
";",
"}",
"}",
"return",
"$",
"this",
";",
"}"
] | Convenient way to add multiple meta attributes in a single call.
Roughly equivalent to calling foreach on $values and performing add.
@return static $this | [
"Convenient",
"way",
"to",
"add",
"multiple",
"meta",
"attributes",
"in",
"a",
"single",
"call",
"."
] | f4cbb926ef54da357b102cbfa4b6ce273be6ce63 | https://github.com/freialib/ran.tools/blob/f4cbb926ef54da357b102cbfa4b6ce273be6ce63/src/Trait/Meta.php#L58-L66 | train |
johnkrovitch/SamBundle | src/Watcher/Indexer/FileIndexer.php | FileIndexer.add | public function add(SplFileInfo $splFileInfo)
{
$fileSystem = new Filesystem();
if (!$fileSystem->exists($splFileInfo->getRealPath())) {
throw new Exception('Trying to add '.$splFileInfo->getRealPath().' missing file to the index');
}
// if the file is already present in the index, and its mtime has been modified, we add it to the change set
if ($this->has($splFileInfo->getRealPath())
&& $splFileInfo->getMTime() !== $this->index[$splFileInfo->getRealPath()]) {
$this->changes[$splFileInfo->getRealPath()] = $splFileInfo;
}
// add new or existing file to the index
$this->index[$splFileInfo->getRealPath()] = $splFileInfo->getMTime();
} | php | public function add(SplFileInfo $splFileInfo)
{
$fileSystem = new Filesystem();
if (!$fileSystem->exists($splFileInfo->getRealPath())) {
throw new Exception('Trying to add '.$splFileInfo->getRealPath().' missing file to the index');
}
// if the file is already present in the index, and its mtime has been modified, we add it to the change set
if ($this->has($splFileInfo->getRealPath())
&& $splFileInfo->getMTime() !== $this->index[$splFileInfo->getRealPath()]) {
$this->changes[$splFileInfo->getRealPath()] = $splFileInfo;
}
// add new or existing file to the index
$this->index[$splFileInfo->getRealPath()] = $splFileInfo->getMTime();
} | [
"public",
"function",
"add",
"(",
"SplFileInfo",
"$",
"splFileInfo",
")",
"{",
"$",
"fileSystem",
"=",
"new",
"Filesystem",
"(",
")",
";",
"if",
"(",
"!",
"$",
"fileSystem",
"->",
"exists",
"(",
"$",
"splFileInfo",
"->",
"getRealPath",
"(",
")",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Trying to add '",
".",
"$",
"splFileInfo",
"->",
"getRealPath",
"(",
")",
".",
"' missing file to the index'",
")",
";",
"}",
"// if the file is already present in the index, and its mtime has been modified, we add it to the change set",
"if",
"(",
"$",
"this",
"->",
"has",
"(",
"$",
"splFileInfo",
"->",
"getRealPath",
"(",
")",
")",
"&&",
"$",
"splFileInfo",
"->",
"getMTime",
"(",
")",
"!==",
"$",
"this",
"->",
"index",
"[",
"$",
"splFileInfo",
"->",
"getRealPath",
"(",
")",
"]",
")",
"{",
"$",
"this",
"->",
"changes",
"[",
"$",
"splFileInfo",
"->",
"getRealPath",
"(",
")",
"]",
"=",
"$",
"splFileInfo",
";",
"}",
"// add new or existing file to the index",
"$",
"this",
"->",
"index",
"[",
"$",
"splFileInfo",
"->",
"getRealPath",
"(",
")",
"]",
"=",
"$",
"splFileInfo",
"->",
"getMTime",
"(",
")",
";",
"}"
] | Add an entry to the indexer. If a entry already exists, it will also be added to the changes.
@param SplFileInfo $splFileInfo
@throws Exception | [
"Add",
"an",
"entry",
"to",
"the",
"indexer",
".",
"If",
"a",
"entry",
"already",
"exists",
"it",
"will",
"also",
"be",
"added",
"to",
"the",
"changes",
"."
] | 6cc08ef2dd8f7cd5c33ee27818edd4697afa435e | https://github.com/johnkrovitch/SamBundle/blob/6cc08ef2dd8f7cd5c33ee27818edd4697afa435e/src/Watcher/Indexer/FileIndexer.php#L70-L85 | train |
pluf/discount | src/Discount/Views/Discount.php | Discount_Views_Discount.getDiscountByCode | public static function getDiscountByCode($request, $code)
{
$discount = Discount_Shortcuts_GetDiscountByCodeOr404($code);
$discountEngine = $discount->get_engine();
$validationCode = $discountEngine->validate($discount, $request);
$discount->__set('validation_code', $validationCode);
// حق دسترسی
// CMS_Precondition::userCanAccessContent($request, $content);
// اجرای درخواست
return $discount;
} | php | public static function getDiscountByCode($request, $code)
{
$discount = Discount_Shortcuts_GetDiscountByCodeOr404($code);
$discountEngine = $discount->get_engine();
$validationCode = $discountEngine->validate($discount, $request);
$discount->__set('validation_code', $validationCode);
// حق دسترسی
// CMS_Precondition::userCanAccessContent($request, $content);
// اجرای درخواست
return $discount;
} | [
"public",
"static",
"function",
"getDiscountByCode",
"(",
"$",
"request",
",",
"$",
"code",
")",
"{",
"$",
"discount",
"=",
"Discount_Shortcuts_GetDiscountByCodeOr404",
"(",
"$",
"code",
")",
";",
"$",
"discountEngine",
"=",
"$",
"discount",
"->",
"get_engine",
"(",
")",
";",
"$",
"validationCode",
"=",
"$",
"discountEngine",
"->",
"validate",
"(",
"$",
"discount",
",",
"$",
"request",
")",
";",
"$",
"discount",
"->",
"__set",
"(",
"'validation_code'",
",",
"$",
"validationCode",
")",
";",
"// حق دسترسی",
"// CMS_Precondition::userCanAccessContent($request, $content);",
"// اجرای درخواست",
"return",
"$",
"discount",
";",
"}"
] | Returns tag with given name.
@param Pluf_HTTP_Request $request
@param string $code
@return Discount_Discount | [
"Returns",
"tag",
"with",
"given",
"name",
"."
] | b0006d6b25dd61241f51b5b098d7d546b470de26 | https://github.com/pluf/discount/blob/b0006d6b25dd61241f51b5b098d7d546b470de26/src/Discount/Views/Discount.php#L50-L60 | train |
chalasr/RCHCapistranoBundle | Util/LocalizableTrait.php | LocalizableTrait.getBundleVendorDir | public function getBundleVendorDir()
{
$psr4Path = $this->getRootDir().'/../vendor/rch/capistrano-bundle';
$psr0Path = $psr4Path.'/RCH/CapistranoBundle';
if (is_dir($psr0Path)) {
return $psr0Path;
}
return $psr4Path;
} | php | public function getBundleVendorDir()
{
$psr4Path = $this->getRootDir().'/../vendor/rch/capistrano-bundle';
$psr0Path = $psr4Path.'/RCH/CapistranoBundle';
if (is_dir($psr0Path)) {
return $psr0Path;
}
return $psr4Path;
} | [
"public",
"function",
"getBundleVendorDir",
"(",
")",
"{",
"$",
"psr4Path",
"=",
"$",
"this",
"->",
"getRootDir",
"(",
")",
".",
"'/../vendor/rch/capistrano-bundle'",
";",
"$",
"psr0Path",
"=",
"$",
"psr4Path",
".",
"'/RCH/CapistranoBundle'",
";",
"if",
"(",
"is_dir",
"(",
"$",
"psr0Path",
")",
")",
"{",
"return",
"$",
"psr0Path",
";",
"}",
"return",
"$",
"psr4Path",
";",
"}"
] | Get bundle directory.
@return string | [
"Get",
"bundle",
"directory",
"."
] | c4a4cbaa2bc05f33bf431fd3afe6cac39947640e | https://github.com/chalasr/RCHCapistranoBundle/blob/c4a4cbaa2bc05f33bf431fd3afe6cac39947640e/Util/LocalizableTrait.php#L38-L48 | train |
chalasr/RCHCapistranoBundle | Util/LocalizableTrait.php | LocalizableTrait.getContainer | public function getContainer()
{
if (property_exists(__CLASS__, 'container')) {
return $this->container;
} else {
return parent::getContainer();
}
throw new RuntimeException(sprintf('The service container must be accessible from class %s to use this trait', __CLASS__));
} | php | public function getContainer()
{
if (property_exists(__CLASS__, 'container')) {
return $this->container;
} else {
return parent::getContainer();
}
throw new RuntimeException(sprintf('The service container must be accessible from class %s to use this trait', __CLASS__));
} | [
"public",
"function",
"getContainer",
"(",
")",
"{",
"if",
"(",
"property_exists",
"(",
"__CLASS__",
",",
"'container'",
")",
")",
"{",
"return",
"$",
"this",
"->",
"container",
";",
"}",
"else",
"{",
"return",
"parent",
"::",
"getContainer",
"(",
")",
";",
"}",
"throw",
"new",
"RuntimeException",
"(",
"sprintf",
"(",
"'The service container must be accessible from class %s to use this trait'",
",",
"__CLASS__",
")",
")",
";",
"}"
] | Get the Service Container.
@return \Symfony\Component\DependencyInjection\ContainerInterface
@throws RuntimeException If the service container is not accessible | [
"Get",
"the",
"Service",
"Container",
"."
] | c4a4cbaa2bc05f33bf431fd3afe6cac39947640e | https://github.com/chalasr/RCHCapistranoBundle/blob/c4a4cbaa2bc05f33bf431fd3afe6cac39947640e/Util/LocalizableTrait.php#L97-L106 | train |
railken/lem | src/Manager.php | Manager.setAgent | public function setAgent(AgentContract $agent = null)
{
if (!$agent) {
$agent = new Agents\SystemAgent();
}
$this->agent = $agent;
return $this;
} | php | public function setAgent(AgentContract $agent = null)
{
if (!$agent) {
$agent = new Agents\SystemAgent();
}
$this->agent = $agent;
return $this;
} | [
"public",
"function",
"setAgent",
"(",
"AgentContract",
"$",
"agent",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"agent",
")",
"{",
"$",
"agent",
"=",
"new",
"Agents",
"\\",
"SystemAgent",
"(",
")",
";",
"}",
"$",
"this",
"->",
"agent",
"=",
"$",
"agent",
";",
"return",
"$",
"this",
";",
"}"
] | set agent.
@param AgentContract $agent
@return $this | [
"set",
"agent",
"."
] | cff1efcd090a9504b2faf5594121885786dea67a | https://github.com/railken/lem/blob/cff1efcd090a9504b2faf5594121885786dea67a/src/Manager.php#L257-L266 | train |
railken/lem | src/Manager.php | Manager.create | public function create($parameters)
{
return $this->update($this->repository->newEntity(), $parameters, Tokens::PERMISSION_CREATE);
} | php | public function create($parameters)
{
return $this->update($this->repository->newEntity(), $parameters, Tokens::PERMISSION_CREATE);
} | [
"public",
"function",
"create",
"(",
"$",
"parameters",
")",
"{",
"return",
"$",
"this",
"->",
"update",
"(",
"$",
"this",
"->",
"repository",
"->",
"newEntity",
"(",
")",
",",
"$",
"parameters",
",",
"Tokens",
"::",
"PERMISSION_CREATE",
")",
";",
"}"
] | Create a new EntityContract given parameters.
@param Bag|array $parameters
@return ResultContract | [
"Create",
"a",
"new",
"EntityContract",
"given",
"parameters",
"."
] | cff1efcd090a9504b2faf5594121885786dea67a | https://github.com/railken/lem/blob/cff1efcd090a9504b2faf5594121885786dea67a/src/Manager.php#L297-L300 | train |
railken/lem | src/Manager.php | Manager.update | public function update(EntityContract $entity, $parameters, $permission = Tokens::PERMISSION_UPDATE)
{
$parameters = $this->castParameters($parameters);
$result = new Result();
try {
DB::beginTransaction();
$result->addErrors($this->getAuthorizer()->authorize($permission, $entity, $parameters));
if ($result->ok()) {
$result->addErrors($this->getValidator()->validate($entity, $parameters));
}
if ($result->ok()) {
$result->addErrors($this->fill($entity, $parameters)->getErrors());
}
if ($result->ok()) {
$result->addErrors($this->save($entity)->getErrors());
}
if (!$result->ok()) {
DB::rollBack();
return $result;
}
$result->getResources()->push($entity);
DB::commit();
} catch (Exception $e) {
DB::rollBack();
throw $e;
}
return $result;
} | php | public function update(EntityContract $entity, $parameters, $permission = Tokens::PERMISSION_UPDATE)
{
$parameters = $this->castParameters($parameters);
$result = new Result();
try {
DB::beginTransaction();
$result->addErrors($this->getAuthorizer()->authorize($permission, $entity, $parameters));
if ($result->ok()) {
$result->addErrors($this->getValidator()->validate($entity, $parameters));
}
if ($result->ok()) {
$result->addErrors($this->fill($entity, $parameters)->getErrors());
}
if ($result->ok()) {
$result->addErrors($this->save($entity)->getErrors());
}
if (!$result->ok()) {
DB::rollBack();
return $result;
}
$result->getResources()->push($entity);
DB::commit();
} catch (Exception $e) {
DB::rollBack();
throw $e;
}
return $result;
} | [
"public",
"function",
"update",
"(",
"EntityContract",
"$",
"entity",
",",
"$",
"parameters",
",",
"$",
"permission",
"=",
"Tokens",
"::",
"PERMISSION_UPDATE",
")",
"{",
"$",
"parameters",
"=",
"$",
"this",
"->",
"castParameters",
"(",
"$",
"parameters",
")",
";",
"$",
"result",
"=",
"new",
"Result",
"(",
")",
";",
"try",
"{",
"DB",
"::",
"beginTransaction",
"(",
")",
";",
"$",
"result",
"->",
"addErrors",
"(",
"$",
"this",
"->",
"getAuthorizer",
"(",
")",
"->",
"authorize",
"(",
"$",
"permission",
",",
"$",
"entity",
",",
"$",
"parameters",
")",
")",
";",
"if",
"(",
"$",
"result",
"->",
"ok",
"(",
")",
")",
"{",
"$",
"result",
"->",
"addErrors",
"(",
"$",
"this",
"->",
"getValidator",
"(",
")",
"->",
"validate",
"(",
"$",
"entity",
",",
"$",
"parameters",
")",
")",
";",
"}",
"if",
"(",
"$",
"result",
"->",
"ok",
"(",
")",
")",
"{",
"$",
"result",
"->",
"addErrors",
"(",
"$",
"this",
"->",
"fill",
"(",
"$",
"entity",
",",
"$",
"parameters",
")",
"->",
"getErrors",
"(",
")",
")",
";",
"}",
"if",
"(",
"$",
"result",
"->",
"ok",
"(",
")",
")",
"{",
"$",
"result",
"->",
"addErrors",
"(",
"$",
"this",
"->",
"save",
"(",
"$",
"entity",
")",
"->",
"getErrors",
"(",
")",
")",
";",
"}",
"if",
"(",
"!",
"$",
"result",
"->",
"ok",
"(",
")",
")",
"{",
"DB",
"::",
"rollBack",
"(",
")",
";",
"return",
"$",
"result",
";",
"}",
"$",
"result",
"->",
"getResources",
"(",
")",
"->",
"push",
"(",
"$",
"entity",
")",
";",
"DB",
"::",
"commit",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"DB",
"::",
"rollBack",
"(",
")",
";",
"throw",
"$",
"e",
";",
"}",
"return",
"$",
"result",
";",
"}"
] | Update a EntityContract given parameters.
@param \Railken\Lem\Contracts\EntityContract $entity
@param Bag|array $parameters
@param string $permission
@return ResultContract | [
"Update",
"a",
"EntityContract",
"given",
"parameters",
"."
] | cff1efcd090a9504b2faf5594121885786dea67a | https://github.com/railken/lem/blob/cff1efcd090a9504b2faf5594121885786dea67a/src/Manager.php#L311-L350 | train |
railken/lem | src/Manager.php | Manager.fill | public function fill(EntityContract $entity, $parameters)
{
$result = new Result();
foreach ($this->getAttributes() as $attribute) {
$result->addErrors($attribute->update($entity, $parameters));
}
return $result;
} | php | public function fill(EntityContract $entity, $parameters)
{
$result = new Result();
foreach ($this->getAttributes() as $attribute) {
$result->addErrors($attribute->update($entity, $parameters));
}
return $result;
} | [
"public",
"function",
"fill",
"(",
"EntityContract",
"$",
"entity",
",",
"$",
"parameters",
")",
"{",
"$",
"result",
"=",
"new",
"Result",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getAttributes",
"(",
")",
"as",
"$",
"attribute",
")",
"{",
"$",
"result",
"->",
"addErrors",
"(",
"$",
"attribute",
"->",
"update",
"(",
"$",
"entity",
",",
"$",
"parameters",
")",
")",
";",
"}",
"return",
"$",
"result",
";",
"}"
] | Fill entity.
@param EntityContract $entity
@param Bag|array $parameters
@return Result | [
"Fill",
"entity",
"."
] | cff1efcd090a9504b2faf5594121885786dea67a | https://github.com/railken/lem/blob/cff1efcd090a9504b2faf5594121885786dea67a/src/Manager.php#L360-L369 | train |
railken/lem | src/Manager.php | Manager.save | public function save(EntityContract $entity)
{
$result = new Result();
$saving = $entity->save();
foreach ($this->getAttributes() as $attribute) {
$result->addErrors($attribute->save($entity));
}
return $result;
} | php | public function save(EntityContract $entity)
{
$result = new Result();
$saving = $entity->save();
foreach ($this->getAttributes() as $attribute) {
$result->addErrors($attribute->save($entity));
}
return $result;
} | [
"public",
"function",
"save",
"(",
"EntityContract",
"$",
"entity",
")",
"{",
"$",
"result",
"=",
"new",
"Result",
"(",
")",
";",
"$",
"saving",
"=",
"$",
"entity",
"->",
"save",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getAttributes",
"(",
")",
"as",
"$",
"attribute",
")",
"{",
"$",
"result",
"->",
"addErrors",
"(",
"$",
"attribute",
"->",
"save",
"(",
"$",
"entity",
")",
")",
";",
"}",
"return",
"$",
"result",
";",
"}"
] | Save the entity.
@param \Railken\Lem\Contracts\EntityContract $entity
@return Result | [
"Save",
"the",
"entity",
"."
] | cff1efcd090a9504b2faf5594121885786dea67a | https://github.com/railken/lem/blob/cff1efcd090a9504b2faf5594121885786dea67a/src/Manager.php#L378-L389 | train |
railken/lem | src/Manager.php | Manager.delete | public function delete(EntityContract $entity)
{
$result = new Result();
$result->addErrors($this->authorizer->authorize(Tokens::PERMISSION_REMOVE, $entity, Bag::factory([])));
if (!$result->ok()) {
return $result;
}
try {
DB::beginTransaction();
$entity->delete();
DB::commit();
} catch (Exception $e) {
DB::rollBack();
throw $e;
}
return $result;
} | php | public function delete(EntityContract $entity)
{
$result = new Result();
$result->addErrors($this->authorizer->authorize(Tokens::PERMISSION_REMOVE, $entity, Bag::factory([])));
if (!$result->ok()) {
return $result;
}
try {
DB::beginTransaction();
$entity->delete();
DB::commit();
} catch (Exception $e) {
DB::rollBack();
throw $e;
}
return $result;
} | [
"public",
"function",
"delete",
"(",
"EntityContract",
"$",
"entity",
")",
"{",
"$",
"result",
"=",
"new",
"Result",
"(",
")",
";",
"$",
"result",
"->",
"addErrors",
"(",
"$",
"this",
"->",
"authorizer",
"->",
"authorize",
"(",
"Tokens",
"::",
"PERMISSION_REMOVE",
",",
"$",
"entity",
",",
"Bag",
"::",
"factory",
"(",
"[",
"]",
")",
")",
")",
";",
"if",
"(",
"!",
"$",
"result",
"->",
"ok",
"(",
")",
")",
"{",
"return",
"$",
"result",
";",
"}",
"try",
"{",
"DB",
"::",
"beginTransaction",
"(",
")",
";",
"$",
"entity",
"->",
"delete",
"(",
")",
";",
"DB",
"::",
"commit",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"DB",
"::",
"rollBack",
"(",
")",
";",
"throw",
"$",
"e",
";",
"}",
"return",
"$",
"result",
";",
"}"
] | Delete a EntityContract.
@param \Railken\Lem\Contracts\EntityContract $entity
@return ResultContract | [
"Delete",
"a",
"EntityContract",
"."
] | cff1efcd090a9504b2faf5594121885786dea67a | https://github.com/railken/lem/blob/cff1efcd090a9504b2faf5594121885786dea67a/src/Manager.php#L410-L431 | train |
railken/lem | src/Manager.php | Manager.findOrCreate | public function findOrCreate($criteria, $parameters = null)
{
if ($criteria instanceof Bag) {
$criteria = $criteria->toArray();
}
if ($parameters === null) {
$parameters = $criteria;
}
$parameters = $this->castParameters($parameters);
$entity = $this->getRepository()->findOneBy($criteria);
if ($entity == null) {
return $this->create($parameters);
}
$result = new Result();
$result->getResources()->push($entity);
return $result;
} | php | public function findOrCreate($criteria, $parameters = null)
{
if ($criteria instanceof Bag) {
$criteria = $criteria->toArray();
}
if ($parameters === null) {
$parameters = $criteria;
}
$parameters = $this->castParameters($parameters);
$entity = $this->getRepository()->findOneBy($criteria);
if ($entity == null) {
return $this->create($parameters);
}
$result = new Result();
$result->getResources()->push($entity);
return $result;
} | [
"public",
"function",
"findOrCreate",
"(",
"$",
"criteria",
",",
"$",
"parameters",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"criteria",
"instanceof",
"Bag",
")",
"{",
"$",
"criteria",
"=",
"$",
"criteria",
"->",
"toArray",
"(",
")",
";",
"}",
"if",
"(",
"$",
"parameters",
"===",
"null",
")",
"{",
"$",
"parameters",
"=",
"$",
"criteria",
";",
"}",
"$",
"parameters",
"=",
"$",
"this",
"->",
"castParameters",
"(",
"$",
"parameters",
")",
";",
"$",
"entity",
"=",
"$",
"this",
"->",
"getRepository",
"(",
")",
"->",
"findOneBy",
"(",
"$",
"criteria",
")",
";",
"if",
"(",
"$",
"entity",
"==",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"create",
"(",
"$",
"parameters",
")",
";",
"}",
"$",
"result",
"=",
"new",
"Result",
"(",
")",
";",
"$",
"result",
"->",
"getResources",
"(",
")",
"->",
"push",
"(",
"$",
"entity",
")",
";",
"return",
"$",
"result",
";",
"}"
] | First or create.
@param Bag|array $criteria
@param Bag|array $parameters
@return ResultContract | [
"First",
"or",
"create",
"."
] | cff1efcd090a9504b2faf5594121885786dea67a | https://github.com/railken/lem/blob/cff1efcd090a9504b2faf5594121885786dea67a/src/Manager.php#L441-L462 | train |
railken/lem | src/Manager.php | Manager.updateOrCreate | public function updateOrCreate($criteria, $parameters = null)
{
if ($criteria instanceof Bag) {
$criteria = $criteria->toArray();
}
if ($parameters === null) {
$parameters = $criteria;
}
$parameters = $this->castParameters($parameters);
$entity = $this->getRepository()->findOneBy($criteria);
return $entity !== null ? $this->update($entity, $parameters) : $this->create($parameters->merge($criteria));
} | php | public function updateOrCreate($criteria, $parameters = null)
{
if ($criteria instanceof Bag) {
$criteria = $criteria->toArray();
}
if ($parameters === null) {
$parameters = $criteria;
}
$parameters = $this->castParameters($parameters);
$entity = $this->getRepository()->findOneBy($criteria);
return $entity !== null ? $this->update($entity, $parameters) : $this->create($parameters->merge($criteria));
} | [
"public",
"function",
"updateOrCreate",
"(",
"$",
"criteria",
",",
"$",
"parameters",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"criteria",
"instanceof",
"Bag",
")",
"{",
"$",
"criteria",
"=",
"$",
"criteria",
"->",
"toArray",
"(",
")",
";",
"}",
"if",
"(",
"$",
"parameters",
"===",
"null",
")",
"{",
"$",
"parameters",
"=",
"$",
"criteria",
";",
"}",
"$",
"parameters",
"=",
"$",
"this",
"->",
"castParameters",
"(",
"$",
"parameters",
")",
";",
"$",
"entity",
"=",
"$",
"this",
"->",
"getRepository",
"(",
")",
"->",
"findOneBy",
"(",
"$",
"criteria",
")",
";",
"return",
"$",
"entity",
"!==",
"null",
"?",
"$",
"this",
"->",
"update",
"(",
"$",
"entity",
",",
"$",
"parameters",
")",
":",
"$",
"this",
"->",
"create",
"(",
"$",
"parameters",
"->",
"merge",
"(",
"$",
"criteria",
")",
")",
";",
"}"
] | Update or create.
@param Bag|array $criteria
@param Bag|array $parameters
@return ResultContract | [
"Update",
"or",
"create",
"."
] | cff1efcd090a9504b2faf5594121885786dea67a | https://github.com/railken/lem/blob/cff1efcd090a9504b2faf5594121885786dea67a/src/Manager.php#L472-L486 | train |
joegreen88/zf1-component-validate | src/Zend/Validate/PostCode.php | Zend_Validate_PostCode.setLocale | public function setLocale($locale = null)
{
$this->_locale = Zend_Locale::findLocale($locale);
$locale = new Zend_Locale($this->_locale);
$region = $locale->getRegion();
if (empty($region)) {
throw new Zend_Validate_Exception("Unable to detect a region for the locale '$locale'");
}
$format = Zend_Locale::getTranslation(
$locale->getRegion(),
'postaltoterritory',
$this->_locale
);
if (empty($format)) {
throw new Zend_Validate_Exception("Unable to detect a postcode format for the region '{$locale->getRegion()}'");
}
$this->setFormat($format);
return $this;
} | php | public function setLocale($locale = null)
{
$this->_locale = Zend_Locale::findLocale($locale);
$locale = new Zend_Locale($this->_locale);
$region = $locale->getRegion();
if (empty($region)) {
throw new Zend_Validate_Exception("Unable to detect a region for the locale '$locale'");
}
$format = Zend_Locale::getTranslation(
$locale->getRegion(),
'postaltoterritory',
$this->_locale
);
if (empty($format)) {
throw new Zend_Validate_Exception("Unable to detect a postcode format for the region '{$locale->getRegion()}'");
}
$this->setFormat($format);
return $this;
} | [
"public",
"function",
"setLocale",
"(",
"$",
"locale",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"_locale",
"=",
"Zend_Locale",
"::",
"findLocale",
"(",
"$",
"locale",
")",
";",
"$",
"locale",
"=",
"new",
"Zend_Locale",
"(",
"$",
"this",
"->",
"_locale",
")",
";",
"$",
"region",
"=",
"$",
"locale",
"->",
"getRegion",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"region",
")",
")",
"{",
"throw",
"new",
"Zend_Validate_Exception",
"(",
"\"Unable to detect a region for the locale '$locale'\"",
")",
";",
"}",
"$",
"format",
"=",
"Zend_Locale",
"::",
"getTranslation",
"(",
"$",
"locale",
"->",
"getRegion",
"(",
")",
",",
"'postaltoterritory'",
",",
"$",
"this",
"->",
"_locale",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"format",
")",
")",
"{",
"throw",
"new",
"Zend_Validate_Exception",
"(",
"\"Unable to detect a postcode format for the region '{$locale->getRegion()}'\"",
")",
";",
"}",
"$",
"this",
"->",
"setFormat",
"(",
"$",
"format",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Sets the locale to use
@param string|Zend_Locale $locale
@throws Zend_Validate_Exception On unrecognised region
@throws Zend_Validate_Exception On not detected format
@return Zend_Validate_PostCode Provides fluid interface | [
"Sets",
"the",
"locale",
"to",
"use"
] | 88d9ea016f73d48ff0ba7d06ecbbf28951fd279e | https://github.com/joegreen88/zf1-component-validate/blob/88d9ea016f73d48ff0ba7d06ecbbf28951fd279e/src/Zend/Validate/PostCode.php#L124-L148 | train |
joegreen88/zf1-component-validate | src/Zend/Validate/PostCode.php | Zend_Validate_PostCode.setFormat | public function setFormat($format)
{
if (empty($format) || !is_string($format)) {
throw new Zend_Validate_Exception("A postcode-format string has to be given for validation");
}
if ($format[0] !== '/') {
$format = '/^' . $format;
}
if ($format[strlen($format) - 1] !== '/') {
$format .= '$/';
}
$this->_format = $format;
return $this;
} | php | public function setFormat($format)
{
if (empty($format) || !is_string($format)) {
throw new Zend_Validate_Exception("A postcode-format string has to be given for validation");
}
if ($format[0] !== '/') {
$format = '/^' . $format;
}
if ($format[strlen($format) - 1] !== '/') {
$format .= '$/';
}
$this->_format = $format;
return $this;
} | [
"public",
"function",
"setFormat",
"(",
"$",
"format",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"format",
")",
"||",
"!",
"is_string",
"(",
"$",
"format",
")",
")",
"{",
"throw",
"new",
"Zend_Validate_Exception",
"(",
"\"A postcode-format string has to be given for validation\"",
")",
";",
"}",
"if",
"(",
"$",
"format",
"[",
"0",
"]",
"!==",
"'/'",
")",
"{",
"$",
"format",
"=",
"'/^'",
".",
"$",
"format",
";",
"}",
"if",
"(",
"$",
"format",
"[",
"strlen",
"(",
"$",
"format",
")",
"-",
"1",
"]",
"!==",
"'/'",
")",
"{",
"$",
"format",
".=",
"'$/'",
";",
"}",
"$",
"this",
"->",
"_format",
"=",
"$",
"format",
";",
"return",
"$",
"this",
";",
"}"
] | Sets a self defined postal format as regex
@param string $format
@throws Zend_Validate_Exception On empty format
@return Zend_Validate_PostCode Provides fluid interface | [
"Sets",
"a",
"self",
"defined",
"postal",
"format",
"as",
"regex"
] | 88d9ea016f73d48ff0ba7d06ecbbf28951fd279e | https://github.com/joegreen88/zf1-component-validate/blob/88d9ea016f73d48ff0ba7d06ecbbf28951fd279e/src/Zend/Validate/PostCode.php#L167-L184 | train |
bytic/orm | src/Traits/Searchable/SearchableRecordsTrait.php | SearchableRecordsTrait.paginate | public function paginate(Paginator $paginator, $params = [])
{
$query = $this->paramsToQuery($params);
$countQuery = $this->getDB()->newSelect();
$countQuery->count(['*', 'count']);
$countQuery->from([$query, 'tbl']);
$results = $countQuery->execute()->fetchResults();
$count = $results[0]['count'];
$paginator->setCount($count);
$params['limit'] = $paginator->getLimits();
return $this->findByParams($params);
} | php | public function paginate(Paginator $paginator, $params = [])
{
$query = $this->paramsToQuery($params);
$countQuery = $this->getDB()->newSelect();
$countQuery->count(['*', 'count']);
$countQuery->from([$query, 'tbl']);
$results = $countQuery->execute()->fetchResults();
$count = $results[0]['count'];
$paginator->setCount($count);
$params['limit'] = $paginator->getLimits();
return $this->findByParams($params);
} | [
"public",
"function",
"paginate",
"(",
"Paginator",
"$",
"paginator",
",",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"query",
"=",
"$",
"this",
"->",
"paramsToQuery",
"(",
"$",
"params",
")",
";",
"$",
"countQuery",
"=",
"$",
"this",
"->",
"getDB",
"(",
")",
"->",
"newSelect",
"(",
")",
";",
"$",
"countQuery",
"->",
"count",
"(",
"[",
"'*'",
",",
"'count'",
"]",
")",
";",
"$",
"countQuery",
"->",
"from",
"(",
"[",
"$",
"query",
",",
"'tbl'",
"]",
")",
";",
"$",
"results",
"=",
"$",
"countQuery",
"->",
"execute",
"(",
")",
"->",
"fetchResults",
"(",
")",
";",
"$",
"count",
"=",
"$",
"results",
"[",
"0",
"]",
"[",
"'count'",
"]",
";",
"$",
"paginator",
"->",
"setCount",
"(",
"$",
"count",
")",
";",
"$",
"params",
"[",
"'limit'",
"]",
"=",
"$",
"paginator",
"->",
"getLimits",
"(",
")",
";",
"return",
"$",
"this",
"->",
"findByParams",
"(",
"$",
"params",
")",
";",
"}"
] | Returns paginated results
@param Paginator $paginator
@param array $params
@return mixed | [
"Returns",
"paginated",
"results"
] | 8d9a79b47761af0bfd9b8d1d28c83221dcac0de0 | https://github.com/bytic/orm/blob/8d9a79b47761af0bfd9b8d1d28c83221dcac0de0/src/Traits/Searchable/SearchableRecordsTrait.php#L23-L38 | train |
bytic/orm | src/Traits/Searchable/SearchableRecordsTrait.php | SearchableRecordsTrait.findOne | public function findOne($primary)
{
$item = $this->getRegistry()->get($primary);
if (!$item) {
$all = $this->getRegistry()->get("all");
if ($all) {
$item = $all[$primary];
}
if (!$item) {
$params['where'][] = ["`{$this->getTable()}`.`{$this->getPrimaryKey()}` = ?", $primary];
$item = $this->findOneByParams($params);
if ($item) {
$this->getRegistry()->set($primary, $item);
}
return $item;
}
}
return $item;
} | php | public function findOne($primary)
{
$item = $this->getRegistry()->get($primary);
if (!$item) {
$all = $this->getRegistry()->get("all");
if ($all) {
$item = $all[$primary];
}
if (!$item) {
$params['where'][] = ["`{$this->getTable()}`.`{$this->getPrimaryKey()}` = ?", $primary];
$item = $this->findOneByParams($params);
if ($item) {
$this->getRegistry()->set($primary, $item);
}
return $item;
}
}
return $item;
} | [
"public",
"function",
"findOne",
"(",
"$",
"primary",
")",
"{",
"$",
"item",
"=",
"$",
"this",
"->",
"getRegistry",
"(",
")",
"->",
"get",
"(",
"$",
"primary",
")",
";",
"if",
"(",
"!",
"$",
"item",
")",
"{",
"$",
"all",
"=",
"$",
"this",
"->",
"getRegistry",
"(",
")",
"->",
"get",
"(",
"\"all\"",
")",
";",
"if",
"(",
"$",
"all",
")",
"{",
"$",
"item",
"=",
"$",
"all",
"[",
"$",
"primary",
"]",
";",
"}",
"if",
"(",
"!",
"$",
"item",
")",
"{",
"$",
"params",
"[",
"'where'",
"]",
"[",
"]",
"=",
"[",
"\"`{$this->getTable()}`.`{$this->getPrimaryKey()}` = ?\"",
",",
"$",
"primary",
"]",
";",
"$",
"item",
"=",
"$",
"this",
"->",
"findOneByParams",
"(",
"$",
"params",
")",
";",
"if",
"(",
"$",
"item",
")",
"{",
"$",
"this",
"->",
"getRegistry",
"(",
")",
"->",
"set",
"(",
"$",
"primary",
",",
"$",
"item",
")",
";",
"}",
"return",
"$",
"item",
";",
"}",
"}",
"return",
"$",
"item",
";",
"}"
] | Checks the registry before fetching from the database
@param mixed $primary
@return Record | [
"Checks",
"the",
"registry",
"before",
"fetching",
"from",
"the",
"database"
] | 8d9a79b47761af0bfd9b8d1d28c83221dcac0de0 | https://github.com/bytic/orm/blob/8d9a79b47761af0bfd9b8d1d28c83221dcac0de0/src/Traits/Searchable/SearchableRecordsTrait.php#L71-L91 | train |
bytic/orm | src/Traits/Searchable/SearchableRecordsTrait.php | SearchableRecordsTrait.findByPrimary | public function findByPrimary($pk_list = [])
{
$pk = $this->getPrimaryKey();
$return = $this->newCollection();
if ($pk_list) {
$pk_list = array_unique($pk_list);
foreach ($pk_list as $key => $value) {
$item = $this->getRegistry()->get($value);
if ($item) {
unset($pk_list[$key]);
$return[$item->{$pk}] = $item;
}
}
if ($pk_list) {
$query = $this->paramsToQuery();
$query->where("$pk IN ?", $pk_list);
$items = $this->findByQuery($query);
if (count($items)) {
foreach ($items as $item) {
$this->getRegistry()->set($item->{$pk}, $item);
$return[$item->{$pk}] = $item;
}
}
}
}
return $return;
} | php | public function findByPrimary($pk_list = [])
{
$pk = $this->getPrimaryKey();
$return = $this->newCollection();
if ($pk_list) {
$pk_list = array_unique($pk_list);
foreach ($pk_list as $key => $value) {
$item = $this->getRegistry()->get($value);
if ($item) {
unset($pk_list[$key]);
$return[$item->{$pk}] = $item;
}
}
if ($pk_list) {
$query = $this->paramsToQuery();
$query->where("$pk IN ?", $pk_list);
$items = $this->findByQuery($query);
if (count($items)) {
foreach ($items as $item) {
$this->getRegistry()->set($item->{$pk}, $item);
$return[$item->{$pk}] = $item;
}
}
}
}
return $return;
} | [
"public",
"function",
"findByPrimary",
"(",
"$",
"pk_list",
"=",
"[",
"]",
")",
"{",
"$",
"pk",
"=",
"$",
"this",
"->",
"getPrimaryKey",
"(",
")",
";",
"$",
"return",
"=",
"$",
"this",
"->",
"newCollection",
"(",
")",
";",
"if",
"(",
"$",
"pk_list",
")",
"{",
"$",
"pk_list",
"=",
"array_unique",
"(",
"$",
"pk_list",
")",
";",
"foreach",
"(",
"$",
"pk_list",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"item",
"=",
"$",
"this",
"->",
"getRegistry",
"(",
")",
"->",
"get",
"(",
"$",
"value",
")",
";",
"if",
"(",
"$",
"item",
")",
"{",
"unset",
"(",
"$",
"pk_list",
"[",
"$",
"key",
"]",
")",
";",
"$",
"return",
"[",
"$",
"item",
"->",
"{",
"$",
"pk",
"}",
"]",
"=",
"$",
"item",
";",
"}",
"}",
"if",
"(",
"$",
"pk_list",
")",
"{",
"$",
"query",
"=",
"$",
"this",
"->",
"paramsToQuery",
"(",
")",
";",
"$",
"query",
"->",
"where",
"(",
"\"$pk IN ?\"",
",",
"$",
"pk_list",
")",
";",
"$",
"items",
"=",
"$",
"this",
"->",
"findByQuery",
"(",
"$",
"query",
")",
";",
"if",
"(",
"count",
"(",
"$",
"items",
")",
")",
"{",
"foreach",
"(",
"$",
"items",
"as",
"$",
"item",
")",
"{",
"$",
"this",
"->",
"getRegistry",
"(",
")",
"->",
"set",
"(",
"$",
"item",
"->",
"{",
"$",
"pk",
"}",
",",
"$",
"item",
")",
";",
"$",
"return",
"[",
"$",
"item",
"->",
"{",
"$",
"pk",
"}",
"]",
"=",
"$",
"item",
";",
"}",
"}",
"}",
"}",
"return",
"$",
"return",
";",
"}"
] | When searching by primary key, look for items in current registry before
fetching them from the database
@param array $pk_list
@return RecordCollection | [
"When",
"searching",
"by",
"primary",
"key",
"look",
"for",
"items",
"in",
"current",
"registry",
"before",
"fetching",
"them",
"from",
"the",
"database"
] | 8d9a79b47761af0bfd9b8d1d28c83221dcac0de0 | https://github.com/bytic/orm/blob/8d9a79b47761af0bfd9b8d1d28c83221dcac0de0/src/Traits/Searchable/SearchableRecordsTrait.php#L100-L129 | train |
bytic/orm | src/Traits/Searchable/SearchableRecordsTrait.php | SearchableRecordsTrait.findOneByParams | public function findOneByParams(array $params = [])
{
$params['limit'] = 1;
$records = $this->findByParams($params);
if (count($records) > 0) {
return $records->rewind();
}
return null;
} | php | public function findOneByParams(array $params = [])
{
$params['limit'] = 1;
$records = $this->findByParams($params);
if (count($records) > 0) {
return $records->rewind();
}
return null;
} | [
"public",
"function",
"findOneByParams",
"(",
"array",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"params",
"[",
"'limit'",
"]",
"=",
"1",
";",
"$",
"records",
"=",
"$",
"this",
"->",
"findByParams",
"(",
"$",
"params",
")",
";",
"if",
"(",
"count",
"(",
"$",
"records",
")",
">",
"0",
")",
"{",
"return",
"$",
"records",
"->",
"rewind",
"(",
")",
";",
"}",
"return",
"null",
";",
"}"
] | Finds one Record using params array
@param array $params
@return Record|null | [
"Finds",
"one",
"Record",
"using",
"params",
"array"
] | 8d9a79b47761af0bfd9b8d1d28c83221dcac0de0 | https://github.com/bytic/orm/blob/8d9a79b47761af0bfd9b8d1d28c83221dcac0de0/src/Traits/Searchable/SearchableRecordsTrait.php#L138-L147 | train |
bytic/orm | src/Traits/Searchable/SearchableRecordsTrait.php | SearchableRecordsTrait.findByParams | public function findByParams($params = [])
{
$query = $this->paramsToQuery($params);
return $this->findByQuery($query, $params);
} | php | public function findByParams($params = [])
{
$query = $this->paramsToQuery($params);
return $this->findByQuery($query, $params);
} | [
"public",
"function",
"findByParams",
"(",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"query",
"=",
"$",
"this",
"->",
"paramsToQuery",
"(",
"$",
"params",
")",
";",
"return",
"$",
"this",
"->",
"findByQuery",
"(",
"$",
"query",
",",
"$",
"params",
")",
";",
"}"
] | Finds Records using params array
@param array $params
@return RecordCollection | [
"Finds",
"Records",
"using",
"params",
"array"
] | 8d9a79b47761af0bfd9b8d1d28c83221dcac0de0 | https://github.com/bytic/orm/blob/8d9a79b47761af0bfd9b8d1d28c83221dcac0de0/src/Traits/Searchable/SearchableRecordsTrait.php#L155-L160 | train |
koolkode/context | src/Locator/InstanceServiceLocator.php | InstanceServiceLocator.registerService | public function registerService($object, $name = NULL)
{
if(!is_object($object))
{
throw new \InvalidArgumentException(sprintf('Expecting an object, given %s', gettype($object)));
}
$key = ($name === NULL) ? get_class($object) : (string)$name;
if(isset($this->services[$key]))
{
throw new DuplicateServiceRegistrationException(sprintf('Service "%s" is already registered', $key));
}
$this->services[$key] = $object;
} | php | public function registerService($object, $name = NULL)
{
if(!is_object($object))
{
throw new \InvalidArgumentException(sprintf('Expecting an object, given %s', gettype($object)));
}
$key = ($name === NULL) ? get_class($object) : (string)$name;
if(isset($this->services[$key]))
{
throw new DuplicateServiceRegistrationException(sprintf('Service "%s" is already registered', $key));
}
$this->services[$key] = $object;
} | [
"public",
"function",
"registerService",
"(",
"$",
"object",
",",
"$",
"name",
"=",
"NULL",
")",
"{",
"if",
"(",
"!",
"is_object",
"(",
"$",
"object",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Expecting an object, given %s'",
",",
"gettype",
"(",
"$",
"object",
")",
")",
")",
";",
"}",
"$",
"key",
"=",
"(",
"$",
"name",
"===",
"NULL",
")",
"?",
"get_class",
"(",
"$",
"object",
")",
":",
"(",
"string",
")",
"$",
"name",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"services",
"[",
"$",
"key",
"]",
")",
")",
"{",
"throw",
"new",
"DuplicateServiceRegistrationException",
"(",
"sprintf",
"(",
"'Service \"%s\" is already registered'",
",",
"$",
"key",
")",
")",
";",
"}",
"$",
"this",
"->",
"services",
"[",
"$",
"key",
"]",
"=",
"$",
"object",
";",
"}"
] | Register the given object instance under the given name, defaults to the fully-qualified
type name of the object instance when no name is given.
@param object $object The object instance to be registered.
@param string $name An optional name for the service.
@throws \InvalidArgumentException When no object instance has been given.
@throws DuplicateServiceRegistrationException | [
"Register",
"the",
"given",
"object",
"instance",
"under",
"the",
"given",
"name",
"defaults",
"to",
"the",
"fully",
"-",
"qualified",
"type",
"name",
"of",
"the",
"object",
"instance",
"when",
"no",
"name",
"is",
"given",
"."
] | f4aa614eb4ca1080bd89c7a2a54c9467c5b17a36 | https://github.com/koolkode/context/blob/f4aa614eb4ca1080bd89c7a2a54c9467c5b17a36/src/Locator/InstanceServiceLocator.php#L74-L89 | train |
gianarb/GaGooGl | src/GaGooGl/Http/Request.php | Request.genereteShortLink | public function genereteShortLink($longLink)
{
$this->client->setMethod('POST');
$this->client->setUri('https://www.googleapis.com/urlshortener/v1/url');
$data = array('longUrl' => $longLink);
$this->client->setRawBody(json_encode($data));
$contentJson = $this->client->send()->getContent();
$responseArray = json_decode($contentJson, true);
if (!empty($responseArray['error'])) {
$response = new Response();
return $response->setError($responseArray['error']['errors']);
} else {
$response = new Response();
$response->setId($responseArray['id'])
->setKind($responseArray['kind'])
->setLongUrl($responseArray['longUrl']);
return $response;
}
} | php | public function genereteShortLink($longLink)
{
$this->client->setMethod('POST');
$this->client->setUri('https://www.googleapis.com/urlshortener/v1/url');
$data = array('longUrl' => $longLink);
$this->client->setRawBody(json_encode($data));
$contentJson = $this->client->send()->getContent();
$responseArray = json_decode($contentJson, true);
if (!empty($responseArray['error'])) {
$response = new Response();
return $response->setError($responseArray['error']['errors']);
} else {
$response = new Response();
$response->setId($responseArray['id'])
->setKind($responseArray['kind'])
->setLongUrl($responseArray['longUrl']);
return $response;
}
} | [
"public",
"function",
"genereteShortLink",
"(",
"$",
"longLink",
")",
"{",
"$",
"this",
"->",
"client",
"->",
"setMethod",
"(",
"'POST'",
")",
";",
"$",
"this",
"->",
"client",
"->",
"setUri",
"(",
"'https://www.googleapis.com/urlshortener/v1/url'",
")",
";",
"$",
"data",
"=",
"array",
"(",
"'longUrl'",
"=>",
"$",
"longLink",
")",
";",
"$",
"this",
"->",
"client",
"->",
"setRawBody",
"(",
"json_encode",
"(",
"$",
"data",
")",
")",
";",
"$",
"contentJson",
"=",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
")",
"->",
"getContent",
"(",
")",
";",
"$",
"responseArray",
"=",
"json_decode",
"(",
"$",
"contentJson",
",",
"true",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"responseArray",
"[",
"'error'",
"]",
")",
")",
"{",
"$",
"response",
"=",
"new",
"Response",
"(",
")",
";",
"return",
"$",
"response",
"->",
"setError",
"(",
"$",
"responseArray",
"[",
"'error'",
"]",
"[",
"'errors'",
"]",
")",
";",
"}",
"else",
"{",
"$",
"response",
"=",
"new",
"Response",
"(",
")",
";",
"$",
"response",
"->",
"setId",
"(",
"$",
"responseArray",
"[",
"'id'",
"]",
")",
"->",
"setKind",
"(",
"$",
"responseArray",
"[",
"'kind'",
"]",
")",
"->",
"setLongUrl",
"(",
"$",
"responseArray",
"[",
"'longUrl'",
"]",
")",
";",
"return",
"$",
"response",
";",
"}",
"}"
] | Generate a Short Link by Long link
@param $longLink
@return Response | [
"Generate",
"a",
"Short",
"Link",
"by",
"Long",
"link"
] | d7ebd3a74edb44a65d32b1b19d54eda55f638eaa | https://github.com/gianarb/GaGooGl/blob/d7ebd3a74edb44a65d32b1b19d54eda55f638eaa/src/GaGooGl/Http/Request.php#L30-L48 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.