id
int32 0
241k
| 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
|
---|---|---|---|---|---|---|---|---|---|---|---|
7,900 | shov/wpci-core | Wordpress/WpProvider.php | WpProvider.registerRestRoute | public function registerRestRoute($namespace, $route, $args = [], $override = false)
{
return $this->callGlobalFunction('register_rest_route', [$namespace, $route, $args, $override]);
} | php | public function registerRestRoute($namespace, $route, $args = [], $override = false)
{
return $this->callGlobalFunction('register_rest_route', [$namespace, $route, $args, $override]);
} | [
"public",
"function",
"registerRestRoute",
"(",
"$",
"namespace",
",",
"$",
"route",
",",
"$",
"args",
"=",
"[",
"]",
",",
"$",
"override",
"=",
"false",
")",
"{",
"return",
"$",
"this",
"->",
"callGlobalFunction",
"(",
"'register_rest_route'",
",",
"[",
"$",
"namespace",
",",
"$",
"route",
",",
"$",
"args",
",",
"$",
"override",
"]",
")",
";",
"}"
] | Registers a REST API route
@param $namespace
@param $route
@param array $args
@param bool $override
@return mixed
@throws \ErrorException | [
"Registers",
"a",
"REST",
"API",
"route"
] | e31084cbc2f310882df2b9b0548330ea5fdb4f26 | https://github.com/shov/wpci-core/blob/e31084cbc2f310882df2b9b0548330ea5fdb4f26/Wordpress/WpProvider.php#L431-L434 |
7,901 | shov/wpci-core | Wordpress/WpProvider.php | WpProvider.getFromGlobal | protected function getFromGlobal(string $name)
{
if (isset($GLOBALS[$name])) {
return $GLOBALS[$name];
}
throw new \ErrorException(
sprintf("Undefined global variable (%s) called!", $name));
} | php | protected function getFromGlobal(string $name)
{
if (isset($GLOBALS[$name])) {
return $GLOBALS[$name];
}
throw new \ErrorException(
sprintf("Undefined global variable (%s) called!", $name));
} | [
"protected",
"function",
"getFromGlobal",
"(",
"string",
"$",
"name",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"GLOBALS",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"$",
"GLOBALS",
"[",
"$",
"name",
"]",
";",
"}",
"throw",
"new",
"\\",
"ErrorException",
"(",
"sprintf",
"(",
"\"Undefined global variable (%s) called!\"",
",",
"$",
"name",
")",
")",
";",
"}"
] | Get global namespace variable
@param string $name
@return mixed
@throws \ErrorException | [
"Get",
"global",
"namespace",
"variable"
] | e31084cbc2f310882df2b9b0548330ea5fdb4f26 | https://github.com/shov/wpci-core/blob/e31084cbc2f310882df2b9b0548330ea5fdb4f26/Wordpress/WpProvider.php#L448-L456 |
7,902 | shov/wpci-core | Wordpress/WpProvider.php | WpProvider.callGlobalFunction | protected function callGlobalFunction(string $name, ?array $arguments = null)
{
if (function_exists($name)) {
return call_user_func_array($name, $arguments ?? []);
}
throw new \ErrorException(
sprintf("Undefined global function (%s) called!", $name));
} | php | protected function callGlobalFunction(string $name, ?array $arguments = null)
{
if (function_exists($name)) {
return call_user_func_array($name, $arguments ?? []);
}
throw new \ErrorException(
sprintf("Undefined global function (%s) called!", $name));
} | [
"protected",
"function",
"callGlobalFunction",
"(",
"string",
"$",
"name",
",",
"?",
"array",
"$",
"arguments",
"=",
"null",
")",
"{",
"if",
"(",
"function_exists",
"(",
"$",
"name",
")",
")",
"{",
"return",
"call_user_func_array",
"(",
"$",
"name",
",",
"$",
"arguments",
"??",
"[",
"]",
")",
";",
"}",
"throw",
"new",
"\\",
"ErrorException",
"(",
"sprintf",
"(",
"\"Undefined global function (%s) called!\"",
",",
"$",
"name",
")",
")",
";",
"}"
] | Call global namespace function
@param string $name
@param array|null $arguments
@return mixed
@throws \ErrorException | [
"Call",
"global",
"namespace",
"function"
] | e31084cbc2f310882df2b9b0548330ea5fdb4f26 | https://github.com/shov/wpci-core/blob/e31084cbc2f310882df2b9b0548330ea5fdb4f26/Wordpress/WpProvider.php#L475-L483 |
7,903 | ehough/shortstop | src/main/php/ehough/shortstop/impl/decoding/AbstractDecodingChain.php | ehough_shortstop_impl_decoding_AbstractDecodingChain.decode | public final function decode(ehough_shortstop_api_HttpResponse $response)
{
$context = new ehough_chaingang_impl_StandardContext();
$context->put('response', $response);
$status = $this->_chain->execute($context);
if ($status === false) {
return;
}
$entity = $response->getEntity();
$decoded = $context->get('response');
$entity->setContent($decoded);
$entity->setContentLength(strlen($decoded));
$contentType = $response->getHeaderValue(ehough_shortstop_api_HttpMessage::HTTP_HEADER_CONTENT_TYPE);
if ($contentType !== null) {
$entity->setContentType($contentType);
}
$response->setEntity($entity);
} | php | public final function decode(ehough_shortstop_api_HttpResponse $response)
{
$context = new ehough_chaingang_impl_StandardContext();
$context->put('response', $response);
$status = $this->_chain->execute($context);
if ($status === false) {
return;
}
$entity = $response->getEntity();
$decoded = $context->get('response');
$entity->setContent($decoded);
$entity->setContentLength(strlen($decoded));
$contentType = $response->getHeaderValue(ehough_shortstop_api_HttpMessage::HTTP_HEADER_CONTENT_TYPE);
if ($contentType !== null) {
$entity->setContentType($contentType);
}
$response->setEntity($entity);
} | [
"public",
"final",
"function",
"decode",
"(",
"ehough_shortstop_api_HttpResponse",
"$",
"response",
")",
"{",
"$",
"context",
"=",
"new",
"ehough_chaingang_impl_StandardContext",
"(",
")",
";",
"$",
"context",
"->",
"put",
"(",
"'response'",
",",
"$",
"response",
")",
";",
"$",
"status",
"=",
"$",
"this",
"->",
"_chain",
"->",
"execute",
"(",
"$",
"context",
")",
";",
"if",
"(",
"$",
"status",
"===",
"false",
")",
"{",
"return",
";",
"}",
"$",
"entity",
"=",
"$",
"response",
"->",
"getEntity",
"(",
")",
";",
"$",
"decoded",
"=",
"$",
"context",
"->",
"get",
"(",
"'response'",
")",
";",
"$",
"entity",
"->",
"setContent",
"(",
"$",
"decoded",
")",
";",
"$",
"entity",
"->",
"setContentLength",
"(",
"strlen",
"(",
"$",
"decoded",
")",
")",
";",
"$",
"contentType",
"=",
"$",
"response",
"->",
"getHeaderValue",
"(",
"ehough_shortstop_api_HttpMessage",
"::",
"HTTP_HEADER_CONTENT_TYPE",
")",
";",
"if",
"(",
"$",
"contentType",
"!==",
"null",
")",
"{",
"$",
"entity",
"->",
"setContentType",
"(",
"$",
"contentType",
")",
";",
"}",
"$",
"response",
"->",
"setEntity",
"(",
"$",
"entity",
")",
";",
"}"
] | Decodes an HTTP response.
@param ehough_shortstop_api_HttpResponse $response The HTTP response.
@return void | [
"Decodes",
"an",
"HTTP",
"response",
"."
] | 4cef21457741347546c70e8e5c0cef6d3162b257 | https://github.com/ehough/shortstop/blob/4cef21457741347546c70e8e5c0cef6d3162b257/src/main/php/ehough/shortstop/impl/decoding/AbstractDecodingChain.php#L36-L62 |
7,904 | ehough/shortstop | src/main/php/ehough/shortstop/impl/decoding/AbstractDecodingChain.php | ehough_shortstop_impl_decoding_AbstractDecodingChain.needsToBeDecoded | public final function needsToBeDecoded(ehough_shortstop_api_HttpResponse $response)
{
$entity = $response->getEntity();
$isDebugEnabled = $this->_logger->isHandling(ehough_epilog_Logger::DEBUG);
if ($entity === null) {
if ($isDebugEnabled) {
$this->_logger->debug('Response contains no entity');
}
return false;
}
$content = $entity->getContent();
if ($content == '' || $content == null) {
if ($isDebugEnabled) {
$this->_logger->debug('Response entity contains no content');
}
return false;
}
$expectedHeaderName = $this->getHeaderName();
$actualHeaderValue = $response->getHeaderValue($expectedHeaderName);
if ($actualHeaderValue === null) {
if ($isDebugEnabled) {
$this->_logger->debug(sprintf('Response does not contain %s header. No need to decode.', $expectedHeaderName));
}
return false;
}
if ($isDebugEnabled) {
$this->_logger->debug(sprintf('Response contains %s header. Will attempt decode.', $expectedHeaderName));
}
return true;
} | php | public final function needsToBeDecoded(ehough_shortstop_api_HttpResponse $response)
{
$entity = $response->getEntity();
$isDebugEnabled = $this->_logger->isHandling(ehough_epilog_Logger::DEBUG);
if ($entity === null) {
if ($isDebugEnabled) {
$this->_logger->debug('Response contains no entity');
}
return false;
}
$content = $entity->getContent();
if ($content == '' || $content == null) {
if ($isDebugEnabled) {
$this->_logger->debug('Response entity contains no content');
}
return false;
}
$expectedHeaderName = $this->getHeaderName();
$actualHeaderValue = $response->getHeaderValue($expectedHeaderName);
if ($actualHeaderValue === null) {
if ($isDebugEnabled) {
$this->_logger->debug(sprintf('Response does not contain %s header. No need to decode.', $expectedHeaderName));
}
return false;
}
if ($isDebugEnabled) {
$this->_logger->debug(sprintf('Response contains %s header. Will attempt decode.', $expectedHeaderName));
}
return true;
} | [
"public",
"final",
"function",
"needsToBeDecoded",
"(",
"ehough_shortstop_api_HttpResponse",
"$",
"response",
")",
"{",
"$",
"entity",
"=",
"$",
"response",
"->",
"getEntity",
"(",
")",
";",
"$",
"isDebugEnabled",
"=",
"$",
"this",
"->",
"_logger",
"->",
"isHandling",
"(",
"ehough_epilog_Logger",
"::",
"DEBUG",
")",
";",
"if",
"(",
"$",
"entity",
"===",
"null",
")",
"{",
"if",
"(",
"$",
"isDebugEnabled",
")",
"{",
"$",
"this",
"->",
"_logger",
"->",
"debug",
"(",
"'Response contains no entity'",
")",
";",
"}",
"return",
"false",
";",
"}",
"$",
"content",
"=",
"$",
"entity",
"->",
"getContent",
"(",
")",
";",
"if",
"(",
"$",
"content",
"==",
"''",
"||",
"$",
"content",
"==",
"null",
")",
"{",
"if",
"(",
"$",
"isDebugEnabled",
")",
"{",
"$",
"this",
"->",
"_logger",
"->",
"debug",
"(",
"'Response entity contains no content'",
")",
";",
"}",
"return",
"false",
";",
"}",
"$",
"expectedHeaderName",
"=",
"$",
"this",
"->",
"getHeaderName",
"(",
")",
";",
"$",
"actualHeaderValue",
"=",
"$",
"response",
"->",
"getHeaderValue",
"(",
"$",
"expectedHeaderName",
")",
";",
"if",
"(",
"$",
"actualHeaderValue",
"===",
"null",
")",
"{",
"if",
"(",
"$",
"isDebugEnabled",
")",
"{",
"$",
"this",
"->",
"_logger",
"->",
"debug",
"(",
"sprintf",
"(",
"'Response does not contain %s header. No need to decode.'",
",",
"$",
"expectedHeaderName",
")",
")",
";",
"}",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"isDebugEnabled",
")",
"{",
"$",
"this",
"->",
"_logger",
"->",
"debug",
"(",
"sprintf",
"(",
"'Response contains %s header. Will attempt decode.'",
",",
"$",
"expectedHeaderName",
")",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Determines if this response needs to be decoded.
@param ehough_shortstop_api_HttpResponse $response The HTTP response.
@return boolean True if this response should be decoded. False otherwise. | [
"Determines",
"if",
"this",
"response",
"needs",
"to",
"be",
"decoded",
"."
] | 4cef21457741347546c70e8e5c0cef6d3162b257 | https://github.com/ehough/shortstop/blob/4cef21457741347546c70e8e5c0cef6d3162b257/src/main/php/ehough/shortstop/impl/decoding/AbstractDecodingChain.php#L71-L117 |
7,905 | Sowapps/orpheus-inputcontroller | src/InputController/ControllerRoute.php | ControllerRoute.mergeRoutes | protected static function mergeRoutes(&$routes, $added) {
// First level (only) is merged
foreach( $added as $type => $typeRoutes ) {
if( isset($routes[$type]) ) {
$routes[$type] = array_merge($typeRoutes, $routes[$type]);
} else {
$routes[$type] = $typeRoutes;
}
}
} | php | protected static function mergeRoutes(&$routes, $added) {
// First level (only) is merged
foreach( $added as $type => $typeRoutes ) {
if( isset($routes[$type]) ) {
$routes[$type] = array_merge($typeRoutes, $routes[$type]);
} else {
$routes[$type] = $typeRoutes;
}
}
} | [
"protected",
"static",
"function",
"mergeRoutes",
"(",
"&",
"$",
"routes",
",",
"$",
"added",
")",
"{",
"// First level (only) is merged",
"foreach",
"(",
"$",
"added",
"as",
"$",
"type",
"=>",
"$",
"typeRoutes",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"routes",
"[",
"$",
"type",
"]",
")",
")",
"{",
"$",
"routes",
"[",
"$",
"type",
"]",
"=",
"array_merge",
"(",
"$",
"typeRoutes",
",",
"$",
"routes",
"[",
"$",
"type",
"]",
")",
";",
"}",
"else",
"{",
"$",
"routes",
"[",
"$",
"type",
"]",
"=",
"$",
"typeRoutes",
";",
"}",
"}",
"}"
] | Merge routes array with routes' logic
@param array $routes
@param array $added | [
"Merge",
"routes",
"array",
"with",
"routes",
"logic"
] | 91f848a42ac02ae4009ffb3e9a9b4e8c0731455e | https://github.com/Sowapps/orpheus-inputcontroller/blob/91f848a42ac02ae4009ffb3e9a9b4e8c0731455e/src/InputController/ControllerRoute.php#L303-L312 |
7,906 | Sowapps/orpheus-inputcontroller | src/InputController/ControllerRoute.php | ControllerRoute.instanciateController | public function instanciateController() {
$class = $this->controllerClass;
/* @var Controller $controller */
$controller = new $class();
if( !($controller instanceof Controller) ) {
throw new NotFoundException('The controller "'.$this->controllerClass.'" is not a valid controller, the class must inherit from "'.get_class().'"');
}
$controller->setRoute($this);
return $controller;
} | php | public function instanciateController() {
$class = $this->controllerClass;
/* @var Controller $controller */
$controller = new $class();
if( !($controller instanceof Controller) ) {
throw new NotFoundException('The controller "'.$this->controllerClass.'" is not a valid controller, the class must inherit from "'.get_class().'"');
}
$controller->setRoute($this);
return $controller;
} | [
"public",
"function",
"instanciateController",
"(",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"controllerClass",
";",
"/* @var Controller $controller */",
"$",
"controller",
"=",
"new",
"$",
"class",
"(",
")",
";",
"if",
"(",
"!",
"(",
"$",
"controller",
"instanceof",
"Controller",
")",
")",
"{",
"throw",
"new",
"NotFoundException",
"(",
"'The controller \"'",
".",
"$",
"this",
"->",
"controllerClass",
".",
"'\" is not a valid controller, the class must inherit from \"'",
".",
"get_class",
"(",
")",
".",
"'\"'",
")",
";",
"}",
"$",
"controller",
"->",
"setRoute",
"(",
"$",
"this",
")",
";",
"return",
"$",
"controller",
";",
"}"
] | Instanciate the controller and return it
@return \Orpheus\InputController\Controller | [
"Instanciate",
"the",
"controller",
"and",
"return",
"it"
] | 91f848a42ac02ae4009ffb3e9a9b4e8c0731455e | https://github.com/Sowapps/orpheus-inputcontroller/blob/91f848a42ac02ae4009ffb3e9a9b4e8c0731455e/src/InputController/ControllerRoute.php#L355-L364 |
7,907 | elastification/php-client | src/Serializer/NativeJsonSerializer.php | NativeJsonSerializer.useAssoc | private function useAssoc($params)
{
$assoc = true;
if (isset($params['assoc']) && is_bool($params['assoc'])) {
$assoc = $params['assoc'];
}
return $assoc;
} | php | private function useAssoc($params)
{
$assoc = true;
if (isset($params['assoc']) && is_bool($params['assoc'])) {
$assoc = $params['assoc'];
}
return $assoc;
} | [
"private",
"function",
"useAssoc",
"(",
"$",
"params",
")",
"{",
"$",
"assoc",
"=",
"true",
";",
"if",
"(",
"isset",
"(",
"$",
"params",
"[",
"'assoc'",
"]",
")",
"&&",
"is_bool",
"(",
"$",
"params",
"[",
"'assoc'",
"]",
")",
")",
"{",
"$",
"assoc",
"=",
"$",
"params",
"[",
"'assoc'",
"]",
";",
"}",
"return",
"$",
"assoc",
";",
"}"
] | Decides whether to use assoc or stdClass.
@param array $params The array of params.
@return boolean
@author Mario Mueller | [
"Decides",
"whether",
"to",
"use",
"assoc",
"or",
"stdClass",
"."
] | eb01be0905dd1eba7baa62f84492d82e4b3cae61 | https://github.com/elastification/php-client/blob/eb01be0905dd1eba7baa62f84492d82e4b3cae61/src/Serializer/NativeJsonSerializer.php#L88-L96 |
7,908 | elastification/php-client | src/Serializer/NativeJsonSerializer.php | NativeJsonSerializer.forceObject | private function forceObject($params)
{
$forceObject = false;
if (isset($params['force_object']) && is_bool($params['force_object']) && true === $params['force_object']) {
$forceObject = JSON_FORCE_OBJECT;
}
return $forceObject;
} | php | private function forceObject($params)
{
$forceObject = false;
if (isset($params['force_object']) && is_bool($params['force_object']) && true === $params['force_object']) {
$forceObject = JSON_FORCE_OBJECT;
}
return $forceObject;
} | [
"private",
"function",
"forceObject",
"(",
"$",
"params",
")",
"{",
"$",
"forceObject",
"=",
"false",
";",
"if",
"(",
"isset",
"(",
"$",
"params",
"[",
"'force_object'",
"]",
")",
"&&",
"is_bool",
"(",
"$",
"params",
"[",
"'force_object'",
"]",
")",
"&&",
"true",
"===",
"$",
"params",
"[",
"'force_object'",
"]",
")",
"{",
"$",
"forceObject",
"=",
"JSON_FORCE_OBJECT",
";",
"}",
"return",
"$",
"forceObject",
";",
"}"
] | Decides whether to force objects.
@param array $params The array of params.
@return integer
@author Patrick Pokatilo <[email protected]> | [
"Decides",
"whether",
"to",
"force",
"objects",
"."
] | eb01be0905dd1eba7baa62f84492d82e4b3cae61 | https://github.com/elastification/php-client/blob/eb01be0905dd1eba7baa62f84492d82e4b3cae61/src/Serializer/NativeJsonSerializer.php#L106-L114 |
7,909 | elastification/php-client | src/Serializer/NativeJsonSerializer.php | NativeJsonSerializer.createGateway | private function createGateway($assoc, $decodedJson)
{
if ($assoc === true) {
$instance = new NativeArrayGateway($decodedJson);
} else {
$instance = new NativeObjectGateway($decodedJson);
}
return $instance;
} | php | private function createGateway($assoc, $decodedJson)
{
if ($assoc === true) {
$instance = new NativeArrayGateway($decodedJson);
} else {
$instance = new NativeObjectGateway($decodedJson);
}
return $instance;
} | [
"private",
"function",
"createGateway",
"(",
"$",
"assoc",
",",
"$",
"decodedJson",
")",
"{",
"if",
"(",
"$",
"assoc",
"===",
"true",
")",
"{",
"$",
"instance",
"=",
"new",
"NativeArrayGateway",
"(",
"$",
"decodedJson",
")",
";",
"}",
"else",
"{",
"$",
"instance",
"=",
"new",
"NativeObjectGateway",
"(",
"$",
"decodedJson",
")",
";",
"}",
"return",
"$",
"instance",
";",
"}"
] | Creates the correct gateway based on assoc being true or false.
The information if we need assoc could also be determined by looking
at the type of $decodedJson, but we thing a boolean is faster and the
decision has already been made before.
@author Mario Mueller
@param boolean $assoc Should we use assoc?
@param array|\stdClass $decodedJson
@return \Elastification\Client\Serializer\Gateway\GatewayInterface | [
"Creates",
"the",
"correct",
"gateway",
"based",
"on",
"assoc",
"being",
"true",
"or",
"false",
"."
] | eb01be0905dd1eba7baa62f84492d82e4b3cae61 | https://github.com/elastification/php-client/blob/eb01be0905dd1eba7baa62f84492d82e4b3cae61/src/Serializer/NativeJsonSerializer.php#L130-L139 |
7,910 | Sowapps/orpheus-publisher | src/Publisher/Transaction/TransactionOperation.php | TransactionOperation.getSQLAdapter | public function getSQLAdapter() {
return $this->sqlAdapter ? $this->sqlAdapter :
($this->transactionOperationSet ? $this->transactionOperationSet->getSQLAdapter() : null);
} | php | public function getSQLAdapter() {
return $this->sqlAdapter ? $this->sqlAdapter :
($this->transactionOperationSet ? $this->transactionOperationSet->getSQLAdapter() : null);
} | [
"public",
"function",
"getSQLAdapter",
"(",
")",
"{",
"return",
"$",
"this",
"->",
"sqlAdapter",
"?",
"$",
"this",
"->",
"sqlAdapter",
":",
"(",
"$",
"this",
"->",
"transactionOperationSet",
"?",
"$",
"this",
"->",
"transactionOperationSet",
"->",
"getSQLAdapter",
"(",
")",
":",
"null",
")",
";",
"}"
] | Get the SQL Adapter
@return \Orpheus\SQLAdapter\SQLAdapter|NULL | [
"Get",
"the",
"SQL",
"Adapter"
] | e33508538a0aa6f7491d724ca1cb09893203bfba | https://github.com/Sowapps/orpheus-publisher/blob/e33508538a0aa6f7491d724ca1cb09893203bfba/src/Publisher/Transaction/TransactionOperation.php#L122-L125 |
7,911 | tenside/core-bundle | src/Controller/TaskRunnerController.php | TaskRunnerController.getTasksAction | public function getTasksAction()
{
$tasks = [];
$list = $this->getTensideTasks();
foreach ($list->getIds() as $taskId) {
$tasks[$taskId] = $this->convertTaskToArray($list->getTask($taskId));
}
return $this->createJsonResponse($tasks, true);
} | php | public function getTasksAction()
{
$tasks = [];
$list = $this->getTensideTasks();
foreach ($list->getIds() as $taskId) {
$tasks[$taskId] = $this->convertTaskToArray($list->getTask($taskId));
}
return $this->createJsonResponse($tasks, true);
} | [
"public",
"function",
"getTasksAction",
"(",
")",
"{",
"$",
"tasks",
"=",
"[",
"]",
";",
"$",
"list",
"=",
"$",
"this",
"->",
"getTensideTasks",
"(",
")",
";",
"foreach",
"(",
"$",
"list",
"->",
"getIds",
"(",
")",
"as",
"$",
"taskId",
")",
"{",
"$",
"tasks",
"[",
"$",
"taskId",
"]",
"=",
"$",
"this",
"->",
"convertTaskToArray",
"(",
"$",
"list",
"->",
"getTask",
"(",
"$",
"taskId",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"createJsonResponse",
"(",
"$",
"tasks",
",",
"true",
")",
";",
"}"
] | Retrieve the task list.
@return JsonResponse
@ApiDoc(
section="tasks",
statusCodes = {
200 = "When everything worked out ok"
},
authentication = true,
authenticationRoles = {
"ROLE_MANIPULATE_REQUIREMENTS"
},
)
@ApiDescription(
response={
"status" = {
"dataType" = "string",
"description" = "OK on success"
},
"tasks" = {
"id" = {
"dataType" = "string",
"description" = "The task id."
},
"status" = {
"dataType" = "string",
"description" = "The task status."
},
"type" = {
"dataType" = "string",
"description" = "The type of the task."
},
"created_at" = {
"dataType" = "string",
"description" = "The date the task was created in ISO 8601 format."
},
"user_data" = {
"dataType" = "object",
"description" = "The user submitted additional data."
}
}
}
) | [
"Retrieve",
"the",
"task",
"list",
"."
] | a7ffad3649cddac1e5594b4f8b65a5504363fccd | https://github.com/tenside/core-bundle/blob/a7ffad3649cddac1e5594b4f8b65a5504363fccd/src/Controller/TaskRunnerController.php#L87-L96 |
7,912 | tenside/core-bundle | src/Controller/TaskRunnerController.php | TaskRunnerController.getTaskAction | public function getTaskAction($taskId, Request $request)
{
// Retrieve the status file of the task.
$task = $this->getTensideTasks()->getTask($taskId);
$offset = null;
if (!$task) {
throw new NotFoundHttpException('No such task.');
}
if ($request->query->has('offset')) {
$offset = (int) $request->query->get('offset');
}
return $this->createJsonResponse([$this->convertTaskToArray($task, true, $offset)]);
} | php | public function getTaskAction($taskId, Request $request)
{
// Retrieve the status file of the task.
$task = $this->getTensideTasks()->getTask($taskId);
$offset = null;
if (!$task) {
throw new NotFoundHttpException('No such task.');
}
if ($request->query->has('offset')) {
$offset = (int) $request->query->get('offset');
}
return $this->createJsonResponse([$this->convertTaskToArray($task, true, $offset)]);
} | [
"public",
"function",
"getTaskAction",
"(",
"$",
"taskId",
",",
"Request",
"$",
"request",
")",
"{",
"// Retrieve the status file of the task.",
"$",
"task",
"=",
"$",
"this",
"->",
"getTensideTasks",
"(",
")",
"->",
"getTask",
"(",
"$",
"taskId",
")",
";",
"$",
"offset",
"=",
"null",
";",
"if",
"(",
"!",
"$",
"task",
")",
"{",
"throw",
"new",
"NotFoundHttpException",
"(",
"'No such task.'",
")",
";",
"}",
"if",
"(",
"$",
"request",
"->",
"query",
"->",
"has",
"(",
"'offset'",
")",
")",
"{",
"$",
"offset",
"=",
"(",
"int",
")",
"$",
"request",
"->",
"query",
"->",
"get",
"(",
"'offset'",
")",
";",
"}",
"return",
"$",
"this",
"->",
"createJsonResponse",
"(",
"[",
"$",
"this",
"->",
"convertTaskToArray",
"(",
"$",
"task",
",",
"true",
",",
"$",
"offset",
")",
"]",
")",
";",
"}"
] | Retrieve the given task task.
@param string $taskId The id of the task to retrieve.
@param Request $request The request.
@return JsonResponse
@throws NotFoundHttpException When the task could not be found.
@ApiDoc(
section="tasks",
statusCodes = {
200 = "When everything worked out ok"
},
authentication = true,
authenticationRoles = {
"ROLE_MANIPULATE_REQUIREMENTS"
},
filters = {
{
"name"="offset",
"dataType" = "int",
"description"="If present, the output will be returned from the given byte offset."
}
}
)
@ApiDescription(
response={
"status" = {
"dataType" = "string",
"description" = "OK on success"
},
"task" = {
"id" = {
"dataType" = "string",
"description" = "The task id."
},
"status" = {
"dataType" = "string",
"description" = "The task status."
},
"type" = {
"dataType" = "string",
"description" = "The type of the task."
},
"created_at" = {
"dataType" = "string",
"description" = "The date the task was created in ISO 8601 format."
},
"user_data" = {
"dataType" = "object",
"description" = "The user submitted additional data."
},
"output" = {
"dataType" = "string",
"description" = "The command line output of the task."
}
}
}
) | [
"Retrieve",
"the",
"given",
"task",
"task",
"."
] | a7ffad3649cddac1e5594b4f8b65a5504363fccd | https://github.com/tenside/core-bundle/blob/a7ffad3649cddac1e5594b4f8b65a5504363fccd/src/Controller/TaskRunnerController.php#L161-L176 |
7,913 | tenside/core-bundle | src/Controller/TaskRunnerController.php | TaskRunnerController.addTaskAction | public function addTaskAction(Request $request)
{
$metaData = null;
$content = $request->getContent();
if (empty($content)) {
throw new NotAcceptableHttpException('Invalid payload');
}
$metaData = new JsonArray($content);
if (!$metaData->has('type')) {
throw new NotAcceptableHttpException('Invalid payload');
}
try {
$taskId = $this->getTensideTasks()->queue($metaData->get('type'), $metaData);
} catch (\InvalidArgumentException $exception) {
throw new NotAcceptableHttpException($exception->getMessage());
}
return $this->createJsonResponse(
[$this->convertTaskToArray($this->getTensideTasks()->getTask($taskId))],
false,
'OK',
JsonResponse::HTTP_CREATED
);
} | php | public function addTaskAction(Request $request)
{
$metaData = null;
$content = $request->getContent();
if (empty($content)) {
throw new NotAcceptableHttpException('Invalid payload');
}
$metaData = new JsonArray($content);
if (!$metaData->has('type')) {
throw new NotAcceptableHttpException('Invalid payload');
}
try {
$taskId = $this->getTensideTasks()->queue($metaData->get('type'), $metaData);
} catch (\InvalidArgumentException $exception) {
throw new NotAcceptableHttpException($exception->getMessage());
}
return $this->createJsonResponse(
[$this->convertTaskToArray($this->getTensideTasks()->getTask($taskId))],
false,
'OK',
JsonResponse::HTTP_CREATED
);
} | [
"public",
"function",
"addTaskAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"metaData",
"=",
"null",
";",
"$",
"content",
"=",
"$",
"request",
"->",
"getContent",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"content",
")",
")",
"{",
"throw",
"new",
"NotAcceptableHttpException",
"(",
"'Invalid payload'",
")",
";",
"}",
"$",
"metaData",
"=",
"new",
"JsonArray",
"(",
"$",
"content",
")",
";",
"if",
"(",
"!",
"$",
"metaData",
"->",
"has",
"(",
"'type'",
")",
")",
"{",
"throw",
"new",
"NotAcceptableHttpException",
"(",
"'Invalid payload'",
")",
";",
"}",
"try",
"{",
"$",
"taskId",
"=",
"$",
"this",
"->",
"getTensideTasks",
"(",
")",
"->",
"queue",
"(",
"$",
"metaData",
"->",
"get",
"(",
"'type'",
")",
",",
"$",
"metaData",
")",
";",
"}",
"catch",
"(",
"\\",
"InvalidArgumentException",
"$",
"exception",
")",
"{",
"throw",
"new",
"NotAcceptableHttpException",
"(",
"$",
"exception",
"->",
"getMessage",
"(",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"createJsonResponse",
"(",
"[",
"$",
"this",
"->",
"convertTaskToArray",
"(",
"$",
"this",
"->",
"getTensideTasks",
"(",
")",
"->",
"getTask",
"(",
"$",
"taskId",
")",
")",
"]",
",",
"false",
",",
"'OK'",
",",
"JsonResponse",
"::",
"HTTP_CREATED",
")",
";",
"}"
] | Queue a task in the list.
@param Request $request The request.
@return JsonResponse
@throws NotAcceptableHttpException When the payload is invalid.
@ApiDoc(
section="tasks",
statusCodes = {
201 = "When everything worked out ok",
406 = "When the payload is invalid"
},
authentication = true,
authenticationRoles = {
"ROLE_MANIPULATE_REQUIREMENTS"
},
)
@ApiDescription(
response={
"status" = {
"dataType" = "string",
"description" = "OK on success"
},
"task" = {
"id" = {
"dataType" = "string",
"description" = "The task id."
},
"status" = {
"dataType" = "string",
"description" = "The task status."
},
"type" = {
"dataType" = "string",
"description" = "The type of the task."
},
"user_data" = {
"dataType" = "object",
"description" = "The user submitted additional data."
},
"created_at" = {
"dataType" = "string",
"description" = "The date the task was created in ISO 8601 format."
}
}
}
) | [
"Queue",
"a",
"task",
"in",
"the",
"list",
"."
] | a7ffad3649cddac1e5594b4f8b65a5504363fccd | https://github.com/tenside/core-bundle/blob/a7ffad3649cddac1e5594b4f8b65a5504363fccd/src/Controller/TaskRunnerController.php#L229-L253 |
7,914 | tenside/core-bundle | src/Controller/TaskRunnerController.php | TaskRunnerController.deleteTaskAction | public function deleteTaskAction($taskId)
{
$list = $this->getTensideTasks();
$task = $list->getTask($taskId);
if (!$task) {
throw new NotFoundHttpException('Task id ' . $taskId . ' not found');
}
if ($task->getStatus() === Task::STATE_RUNNING) {
throw new NotAcceptableHttpException('Task id ' . $taskId . ' is running and can not be deleted');
}
$task->removeAssets();
$list->remove($task->getId());
return JsonResponse::create(
[
'status' => 'OK'
]
);
} | php | public function deleteTaskAction($taskId)
{
$list = $this->getTensideTasks();
$task = $list->getTask($taskId);
if (!$task) {
throw new NotFoundHttpException('Task id ' . $taskId . ' not found');
}
if ($task->getStatus() === Task::STATE_RUNNING) {
throw new NotAcceptableHttpException('Task id ' . $taskId . ' is running and can not be deleted');
}
$task->removeAssets();
$list->remove($task->getId());
return JsonResponse::create(
[
'status' => 'OK'
]
);
} | [
"public",
"function",
"deleteTaskAction",
"(",
"$",
"taskId",
")",
"{",
"$",
"list",
"=",
"$",
"this",
"->",
"getTensideTasks",
"(",
")",
";",
"$",
"task",
"=",
"$",
"list",
"->",
"getTask",
"(",
"$",
"taskId",
")",
";",
"if",
"(",
"!",
"$",
"task",
")",
"{",
"throw",
"new",
"NotFoundHttpException",
"(",
"'Task id '",
".",
"$",
"taskId",
".",
"' not found'",
")",
";",
"}",
"if",
"(",
"$",
"task",
"->",
"getStatus",
"(",
")",
"===",
"Task",
"::",
"STATE_RUNNING",
")",
"{",
"throw",
"new",
"NotAcceptableHttpException",
"(",
"'Task id '",
".",
"$",
"taskId",
".",
"' is running and can not be deleted'",
")",
";",
"}",
"$",
"task",
"->",
"removeAssets",
"(",
")",
";",
"$",
"list",
"->",
"remove",
"(",
"$",
"task",
"->",
"getId",
"(",
")",
")",
";",
"return",
"JsonResponse",
"::",
"create",
"(",
"[",
"'status'",
"=>",
"'OK'",
"]",
")",
";",
"}"
] | Remove a task from the list.
@param string $taskId The id of the task to remove.
@return JsonResponse
@throws NotFoundHttpException When the given task could not be found.
@throws NotAcceptableHttpException When trying to delete a running task.
@ApiDoc(
section="tasks",
statusCodes = {
200 = "When everything worked out ok"
},
authentication = true,
authenticationRoles = {
"ROLE_MANIPULATE_REQUIREMENTS"
},
)
@ApiDescription(
response={
"status" = {
"dataType" = "string",
"description" = "OK on success"
}
}
) | [
"Remove",
"a",
"task",
"from",
"the",
"list",
"."
] | a7ffad3649cddac1e5594b4f8b65a5504363fccd | https://github.com/tenside/core-bundle/blob/a7ffad3649cddac1e5594b4f8b65a5504363fccd/src/Controller/TaskRunnerController.php#L284-L305 |
7,915 | tenside/core-bundle | src/Controller/TaskRunnerController.php | TaskRunnerController.runAction | public function runAction()
{
$lock = $this->container->get('tenside.taskrun_lock');
if ($this->getTensideConfig()->isForkingAvailable() && !$lock->lock()) {
throw new NotAcceptableHttpException('Task already running');
}
// Fetch the next queued task.
$task = $this->getTensideTasks()->getNext();
if (!$task) {
throw new NotFoundHttpException('Task not found');
}
if ($task::STATE_PENDING !== $task->getStatus()) {
return $this->createJsonResponse([$this->convertTaskToArray($task)]);
}
// Now spawn a runner.
try {
$this->spawn($task);
} finally {
if ($this->getTensideConfig()->isForkingAvailable()) {
$lock->release();
}
}
return $this->createJsonResponse([$this->convertTaskToArray($task)]);
} | php | public function runAction()
{
$lock = $this->container->get('tenside.taskrun_lock');
if ($this->getTensideConfig()->isForkingAvailable() && !$lock->lock()) {
throw new NotAcceptableHttpException('Task already running');
}
// Fetch the next queued task.
$task = $this->getTensideTasks()->getNext();
if (!$task) {
throw new NotFoundHttpException('Task not found');
}
if ($task::STATE_PENDING !== $task->getStatus()) {
return $this->createJsonResponse([$this->convertTaskToArray($task)]);
}
// Now spawn a runner.
try {
$this->spawn($task);
} finally {
if ($this->getTensideConfig()->isForkingAvailable()) {
$lock->release();
}
}
return $this->createJsonResponse([$this->convertTaskToArray($task)]);
} | [
"public",
"function",
"runAction",
"(",
")",
"{",
"$",
"lock",
"=",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'tenside.taskrun_lock'",
")",
";",
"if",
"(",
"$",
"this",
"->",
"getTensideConfig",
"(",
")",
"->",
"isForkingAvailable",
"(",
")",
"&&",
"!",
"$",
"lock",
"->",
"lock",
"(",
")",
")",
"{",
"throw",
"new",
"NotAcceptableHttpException",
"(",
"'Task already running'",
")",
";",
"}",
"// Fetch the next queued task.",
"$",
"task",
"=",
"$",
"this",
"->",
"getTensideTasks",
"(",
")",
"->",
"getNext",
"(",
")",
";",
"if",
"(",
"!",
"$",
"task",
")",
"{",
"throw",
"new",
"NotFoundHttpException",
"(",
"'Task not found'",
")",
";",
"}",
"if",
"(",
"$",
"task",
"::",
"STATE_PENDING",
"!==",
"$",
"task",
"->",
"getStatus",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"createJsonResponse",
"(",
"[",
"$",
"this",
"->",
"convertTaskToArray",
"(",
"$",
"task",
")",
"]",
")",
";",
"}",
"// Now spawn a runner.",
"try",
"{",
"$",
"this",
"->",
"spawn",
"(",
"$",
"task",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"$",
"this",
"->",
"getTensideConfig",
"(",
")",
"->",
"isForkingAvailable",
"(",
")",
")",
"{",
"$",
"lock",
"->",
"release",
"(",
")",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"createJsonResponse",
"(",
"[",
"$",
"this",
"->",
"convertTaskToArray",
"(",
"$",
"task",
")",
"]",
")",
";",
"}"
] | Starts the next pending task if any.
@return JsonResponse
@throws NotFoundHttpException When no task could be found.
@throws NotAcceptableHttpException When a task is already running and holds the lock.
@ApiDoc(
section="tasks",
statusCodes = {
200 = "When everything worked out ok",
404 = "When no pending task has been found",
406 = "When another task is still running"
},
authentication = true,
authenticationRoles = {
"ROLE_MANIPULATE_REQUIREMENTS"
},
)
@ApiDescription(
response={
"status" = {
"dataType" = "string",
"description" = "OK on success"
},
"task" = {
"id" = {
"dataType" = "string",
"description" = "The task id."
},
"status" = {
"dataType" = "string",
"description" = "The task status."
},
"type" = {
"dataType" = "string",
"description" = "The type of the task."
},
"created_at" = {
"dataType" = "string",
"description" = "The date the task was created in ISO 8601 format."
},
"user_data" = {
"dataType" = "object",
"description" = "The user submitted additional data."
}
}
}
) | [
"Starts",
"the",
"next",
"pending",
"task",
"if",
"any",
"."
] | a7ffad3649cddac1e5594b4f8b65a5504363fccd | https://github.com/tenside/core-bundle/blob/a7ffad3649cddac1e5594b4f8b65a5504363fccd/src/Controller/TaskRunnerController.php#L358-L387 |
7,916 | tenside/core-bundle | src/Controller/TaskRunnerController.php | TaskRunnerController.spawn | private function spawn(Task $task)
{
$config = $this->getTensideConfig();
$home = $this->getTensideHome();
$commandline = PhpProcessSpawner::create($config, $home)->spawn(
[
$this->get('tenside.cli_script')->cliExecutable(),
'tenside:runtask',
$task->getId(),
'-v',
'--no-interaction'
]
);
$this->get('logger')->debug('SPAWN CLI: ' . $commandline->getCommandLine());
$commandline->setTimeout(0);
$commandline->start();
if (!$commandline->isRunning()) {
// We might end up here when the process has been forked.
// If exit code is neither 0 nor null, we have a problem here.
if ($exitCode = $commandline->getExitCode()) {
/** @var LoggerInterface $logger */
$logger = $this->get('logger');
$logger->error('Failed to execute "' . $commandline->getCommandLine() . '"');
$logger->error('Exit code: ' . $commandline->getExitCode());
$logger->error('Output: ' . $commandline->getOutput());
$logger->error('Error output: ' . $commandline->getErrorOutput());
throw new \RuntimeException(
sprintf(
'Spawning process task %s resulted in exit code %s',
$task->getId(),
$exitCode
)
);
}
}
$commandline->wait();
} | php | private function spawn(Task $task)
{
$config = $this->getTensideConfig();
$home = $this->getTensideHome();
$commandline = PhpProcessSpawner::create($config, $home)->spawn(
[
$this->get('tenside.cli_script')->cliExecutable(),
'tenside:runtask',
$task->getId(),
'-v',
'--no-interaction'
]
);
$this->get('logger')->debug('SPAWN CLI: ' . $commandline->getCommandLine());
$commandline->setTimeout(0);
$commandline->start();
if (!$commandline->isRunning()) {
// We might end up here when the process has been forked.
// If exit code is neither 0 nor null, we have a problem here.
if ($exitCode = $commandline->getExitCode()) {
/** @var LoggerInterface $logger */
$logger = $this->get('logger');
$logger->error('Failed to execute "' . $commandline->getCommandLine() . '"');
$logger->error('Exit code: ' . $commandline->getExitCode());
$logger->error('Output: ' . $commandline->getOutput());
$logger->error('Error output: ' . $commandline->getErrorOutput());
throw new \RuntimeException(
sprintf(
'Spawning process task %s resulted in exit code %s',
$task->getId(),
$exitCode
)
);
}
}
$commandline->wait();
} | [
"private",
"function",
"spawn",
"(",
"Task",
"$",
"task",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"getTensideConfig",
"(",
")",
";",
"$",
"home",
"=",
"$",
"this",
"->",
"getTensideHome",
"(",
")",
";",
"$",
"commandline",
"=",
"PhpProcessSpawner",
"::",
"create",
"(",
"$",
"config",
",",
"$",
"home",
")",
"->",
"spawn",
"(",
"[",
"$",
"this",
"->",
"get",
"(",
"'tenside.cli_script'",
")",
"->",
"cliExecutable",
"(",
")",
",",
"'tenside:runtask'",
",",
"$",
"task",
"->",
"getId",
"(",
")",
",",
"'-v'",
",",
"'--no-interaction'",
"]",
")",
";",
"$",
"this",
"->",
"get",
"(",
"'logger'",
")",
"->",
"debug",
"(",
"'SPAWN CLI: '",
".",
"$",
"commandline",
"->",
"getCommandLine",
"(",
")",
")",
";",
"$",
"commandline",
"->",
"setTimeout",
"(",
"0",
")",
";",
"$",
"commandline",
"->",
"start",
"(",
")",
";",
"if",
"(",
"!",
"$",
"commandline",
"->",
"isRunning",
"(",
")",
")",
"{",
"// We might end up here when the process has been forked.",
"// If exit code is neither 0 nor null, we have a problem here.",
"if",
"(",
"$",
"exitCode",
"=",
"$",
"commandline",
"->",
"getExitCode",
"(",
")",
")",
"{",
"/** @var LoggerInterface $logger */",
"$",
"logger",
"=",
"$",
"this",
"->",
"get",
"(",
"'logger'",
")",
";",
"$",
"logger",
"->",
"error",
"(",
"'Failed to execute \"'",
".",
"$",
"commandline",
"->",
"getCommandLine",
"(",
")",
".",
"'\"'",
")",
";",
"$",
"logger",
"->",
"error",
"(",
"'Exit code: '",
".",
"$",
"commandline",
"->",
"getExitCode",
"(",
")",
")",
";",
"$",
"logger",
"->",
"error",
"(",
"'Output: '",
".",
"$",
"commandline",
"->",
"getOutput",
"(",
")",
")",
";",
"$",
"logger",
"->",
"error",
"(",
"'Error output: '",
".",
"$",
"commandline",
"->",
"getErrorOutput",
"(",
")",
")",
";",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"sprintf",
"(",
"'Spawning process task %s resulted in exit code %s'",
",",
"$",
"task",
"->",
"getId",
"(",
")",
",",
"$",
"exitCode",
")",
")",
";",
"}",
"}",
"$",
"commandline",
"->",
"wait",
"(",
")",
";",
"}"
] | Spawn a detached process for a task.
@param Task $task The task to spawn a process for.
@return void
@throws \RuntimeException When the task could not be started. | [
"Spawn",
"a",
"detached",
"process",
"for",
"a",
"task",
"."
] | a7ffad3649cddac1e5594b4f8b65a5504363fccd | https://github.com/tenside/core-bundle/blob/a7ffad3649cddac1e5594b4f8b65a5504363fccd/src/Controller/TaskRunnerController.php#L398-L436 |
7,917 | tenside/core-bundle | src/Controller/TaskRunnerController.php | TaskRunnerController.convertTaskToArray | private function convertTaskToArray(Task $task, $addOutput = false, $outputOffset = null)
{
$data = [
'id' => $task->getId(),
'status' => $task->getStatus(),
'type' => $task->getType(),
'created_at' => $task->getCreatedAt()->format(\DateTime::ISO8601),
'user_data' => $task->getUserData()
];
if (true === $addOutput) {
$data['output'] = $task->getOutput($outputOffset);
}
return $data;
} | php | private function convertTaskToArray(Task $task, $addOutput = false, $outputOffset = null)
{
$data = [
'id' => $task->getId(),
'status' => $task->getStatus(),
'type' => $task->getType(),
'created_at' => $task->getCreatedAt()->format(\DateTime::ISO8601),
'user_data' => $task->getUserData()
];
if (true === $addOutput) {
$data['output'] = $task->getOutput($outputOffset);
}
return $data;
} | [
"private",
"function",
"convertTaskToArray",
"(",
"Task",
"$",
"task",
",",
"$",
"addOutput",
"=",
"false",
",",
"$",
"outputOffset",
"=",
"null",
")",
"{",
"$",
"data",
"=",
"[",
"'id'",
"=>",
"$",
"task",
"->",
"getId",
"(",
")",
",",
"'status'",
"=>",
"$",
"task",
"->",
"getStatus",
"(",
")",
",",
"'type'",
"=>",
"$",
"task",
"->",
"getType",
"(",
")",
",",
"'created_at'",
"=>",
"$",
"task",
"->",
"getCreatedAt",
"(",
")",
"->",
"format",
"(",
"\\",
"DateTime",
"::",
"ISO8601",
")",
",",
"'user_data'",
"=>",
"$",
"task",
"->",
"getUserData",
"(",
")",
"]",
";",
"if",
"(",
"true",
"===",
"$",
"addOutput",
")",
"{",
"$",
"data",
"[",
"'output'",
"]",
"=",
"$",
"task",
"->",
"getOutput",
"(",
"$",
"outputOffset",
")",
";",
"}",
"return",
"$",
"data",
";",
"}"
] | Convert a task to an array.
@param Task $task The task to convert.
@param bool $addOutput Flag determining if the output shall get added or not.
@param null $outputOffset The output offset to use.
@return array | [
"Convert",
"a",
"task",
"to",
"an",
"array",
"."
] | a7ffad3649cddac1e5594b4f8b65a5504363fccd | https://github.com/tenside/core-bundle/blob/a7ffad3649cddac1e5594b4f8b65a5504363fccd/src/Controller/TaskRunnerController.php#L449-L464 |
7,918 | tenside/core-bundle | src/Controller/TaskRunnerController.php | TaskRunnerController.createJsonResponse | private function createJsonResponse(
array $tasks,
$isCollection = false,
$status = 'OK',
$httpStatus = JsonResponse::HTTP_OK
) {
$data = ['status' => $status];
$key = $isCollection ? 'tasks' : 'task';
$data[$key] = $isCollection ? $tasks : $tasks[0];
return JsonResponse::create($data, $httpStatus)
->setEncodingOptions((JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_FORCE_OBJECT));
} | php | private function createJsonResponse(
array $tasks,
$isCollection = false,
$status = 'OK',
$httpStatus = JsonResponse::HTTP_OK
) {
$data = ['status' => $status];
$key = $isCollection ? 'tasks' : 'task';
$data[$key] = $isCollection ? $tasks : $tasks[0];
return JsonResponse::create($data, $httpStatus)
->setEncodingOptions((JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_FORCE_OBJECT));
} | [
"private",
"function",
"createJsonResponse",
"(",
"array",
"$",
"tasks",
",",
"$",
"isCollection",
"=",
"false",
",",
"$",
"status",
"=",
"'OK'",
",",
"$",
"httpStatus",
"=",
"JsonResponse",
"::",
"HTTP_OK",
")",
"{",
"$",
"data",
"=",
"[",
"'status'",
"=>",
"$",
"status",
"]",
";",
"$",
"key",
"=",
"$",
"isCollection",
"?",
"'tasks'",
":",
"'task'",
";",
"$",
"data",
"[",
"$",
"key",
"]",
"=",
"$",
"isCollection",
"?",
"$",
"tasks",
":",
"$",
"tasks",
"[",
"0",
"]",
";",
"return",
"JsonResponse",
"::",
"create",
"(",
"$",
"data",
",",
"$",
"httpStatus",
")",
"->",
"setEncodingOptions",
"(",
"(",
"JSON_HEX_TAG",
"|",
"JSON_HEX_APOS",
"|",
"JSON_HEX_AMP",
"|",
"JSON_HEX_QUOT",
"|",
"JSON_FORCE_OBJECT",
")",
")",
";",
"}"
] | Create a JsonResponse based on an array of tasks.
@param array[] $tasks The task data.
@param bool $isCollection Flag if the data is a task collection.
@param string $status Status code string.
@param int $httpStatus HTTP Status to send.
@return JsonResponse | [
"Create",
"a",
"JsonResponse",
"based",
"on",
"an",
"array",
"of",
"tasks",
"."
] | a7ffad3649cddac1e5594b4f8b65a5504363fccd | https://github.com/tenside/core-bundle/blob/a7ffad3649cddac1e5594b4f8b65a5504363fccd/src/Controller/TaskRunnerController.php#L479-L491 |
7,919 | phlexible/phlexible | src/Phlexible/Bundle/SiterootBundle/Controller/SiterootController.php | SiterootController.listAction | public function listAction()
{
$siterootManager = $this->get('phlexible_siteroot.siteroot_manager');
$siteroots = [];
foreach ($siterootManager->findAll() as $siteroot) {
$siteroots[] = [
'id' => $siteroot->getId(),
'title' => $siteroot->getTitle(),
];
}
return new JsonResponse([
'siteroots' => $siteroots,
'count' => count($siteroots),
]);
} | php | public function listAction()
{
$siterootManager = $this->get('phlexible_siteroot.siteroot_manager');
$siteroots = [];
foreach ($siterootManager->findAll() as $siteroot) {
$siteroots[] = [
'id' => $siteroot->getId(),
'title' => $siteroot->getTitle(),
];
}
return new JsonResponse([
'siteroots' => $siteroots,
'count' => count($siteroots),
]);
} | [
"public",
"function",
"listAction",
"(",
")",
"{",
"$",
"siterootManager",
"=",
"$",
"this",
"->",
"get",
"(",
"'phlexible_siteroot.siteroot_manager'",
")",
";",
"$",
"siteroots",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"siterootManager",
"->",
"findAll",
"(",
")",
"as",
"$",
"siteroot",
")",
"{",
"$",
"siteroots",
"[",
"]",
"=",
"[",
"'id'",
"=>",
"$",
"siteroot",
"->",
"getId",
"(",
")",
",",
"'title'",
"=>",
"$",
"siteroot",
"->",
"getTitle",
"(",
")",
",",
"]",
";",
"}",
"return",
"new",
"JsonResponse",
"(",
"[",
"'siteroots'",
"=>",
"$",
"siteroots",
",",
"'count'",
"=>",
"count",
"(",
"$",
"siteroots",
")",
",",
"]",
")",
";",
"}"
] | List siteroots.
@return JsonResponse
@Route("/list", name="siteroots_siteroot_list") | [
"List",
"siteroots",
"."
] | 132f24924c9bb0dbb6c1ea84db0a463f97fa3893 | https://github.com/phlexible/phlexible/blob/132f24924c9bb0dbb6c1ea84db0a463f97fa3893/src/Phlexible/Bundle/SiterootBundle/Controller/SiterootController.php#L37-L53 |
7,920 | phlexible/phlexible | src/Phlexible/Bundle/SiterootBundle/Controller/SiterootController.php | SiterootController.createAction | public function createAction(Request $request)
{
$title = $request->get('title', null);
$siterootManager = $this->get('phlexible_siteroot.siteroot_manager');
$siteroot = new Siteroot();
foreach (explode(',', $this->container->getParameter('phlexible_gui.languages.available')) as $language) {
$siteroot->setTitle($language, $title);
}
$siteroot
->setCreateUserId($this->getUser()->getId())
->setCreatedAt(new \DateTime())
->setModifyUserId($siteroot->getCreateUserId())
->setModifiedAt($siteroot->getCreatedAt());
$siterootManager->updateSiteroot($siteroot);
return new ResultResponse(true, 'New Siteroot created.');
} | php | public function createAction(Request $request)
{
$title = $request->get('title', null);
$siterootManager = $this->get('phlexible_siteroot.siteroot_manager');
$siteroot = new Siteroot();
foreach (explode(',', $this->container->getParameter('phlexible_gui.languages.available')) as $language) {
$siteroot->setTitle($language, $title);
}
$siteroot
->setCreateUserId($this->getUser()->getId())
->setCreatedAt(new \DateTime())
->setModifyUserId($siteroot->getCreateUserId())
->setModifiedAt($siteroot->getCreatedAt());
$siterootManager->updateSiteroot($siteroot);
return new ResultResponse(true, 'New Siteroot created.');
} | [
"public",
"function",
"createAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"title",
"=",
"$",
"request",
"->",
"get",
"(",
"'title'",
",",
"null",
")",
";",
"$",
"siterootManager",
"=",
"$",
"this",
"->",
"get",
"(",
"'phlexible_siteroot.siteroot_manager'",
")",
";",
"$",
"siteroot",
"=",
"new",
"Siteroot",
"(",
")",
";",
"foreach",
"(",
"explode",
"(",
"','",
",",
"$",
"this",
"->",
"container",
"->",
"getParameter",
"(",
"'phlexible_gui.languages.available'",
")",
")",
"as",
"$",
"language",
")",
"{",
"$",
"siteroot",
"->",
"setTitle",
"(",
"$",
"language",
",",
"$",
"title",
")",
";",
"}",
"$",
"siteroot",
"->",
"setCreateUserId",
"(",
"$",
"this",
"->",
"getUser",
"(",
")",
"->",
"getId",
"(",
")",
")",
"->",
"setCreatedAt",
"(",
"new",
"\\",
"DateTime",
"(",
")",
")",
"->",
"setModifyUserId",
"(",
"$",
"siteroot",
"->",
"getCreateUserId",
"(",
")",
")",
"->",
"setModifiedAt",
"(",
"$",
"siteroot",
"->",
"getCreatedAt",
"(",
")",
")",
";",
"$",
"siterootManager",
"->",
"updateSiteroot",
"(",
"$",
"siteroot",
")",
";",
"return",
"new",
"ResultResponse",
"(",
"true",
",",
"'New Siteroot created.'",
")",
";",
"}"
] | Create siteroot.
@param Request $request
@return ResultResponse
@Route("/create", name="siteroots_siteroot_create") | [
"Create",
"siteroot",
"."
] | 132f24924c9bb0dbb6c1ea84db0a463f97fa3893 | https://github.com/phlexible/phlexible/blob/132f24924c9bb0dbb6c1ea84db0a463f97fa3893/src/Phlexible/Bundle/SiterootBundle/Controller/SiterootController.php#L63-L82 |
7,921 | phlexible/phlexible | src/Phlexible/Bundle/SiterootBundle/Controller/SiterootController.php | SiterootController.deleteAction | public function deleteAction(Request $request)
{
$siterootId = $request->get('id');
$siterootManager = $this->get('phlexible_siteroot.siteroot_manager');
$siteroot = $siterootManager->find($siterootId);
$siterootManager->deleteSiteroot($siteroot);
return new ResultResponse(true, 'Siteroot deleted.');
} | php | public function deleteAction(Request $request)
{
$siterootId = $request->get('id');
$siterootManager = $this->get('phlexible_siteroot.siteroot_manager');
$siteroot = $siterootManager->find($siterootId);
$siterootManager->deleteSiteroot($siteroot);
return new ResultResponse(true, 'Siteroot deleted.');
} | [
"public",
"function",
"deleteAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"siterootId",
"=",
"$",
"request",
"->",
"get",
"(",
"'id'",
")",
";",
"$",
"siterootManager",
"=",
"$",
"this",
"->",
"get",
"(",
"'phlexible_siteroot.siteroot_manager'",
")",
";",
"$",
"siteroot",
"=",
"$",
"siterootManager",
"->",
"find",
"(",
"$",
"siterootId",
")",
";",
"$",
"siterootManager",
"->",
"deleteSiteroot",
"(",
"$",
"siteroot",
")",
";",
"return",
"new",
"ResultResponse",
"(",
"true",
",",
"'Siteroot deleted.'",
")",
";",
"}"
] | Delete siteroot.
@param Request $request
@return ResultResponse
@Route("/delete", name="siteroots_siteroot_delete") | [
"Delete",
"siteroot",
"."
] | 132f24924c9bb0dbb6c1ea84db0a463f97fa3893 | https://github.com/phlexible/phlexible/blob/132f24924c9bb0dbb6c1ea84db0a463f97fa3893/src/Phlexible/Bundle/SiterootBundle/Controller/SiterootController.php#L92-L102 |
7,922 | FiveLab/ResourceBundle | src/EventListener/LoggingExceptionListener.php | LoggingExceptionListener.onKernelException | public function onKernelException(GetResponseForExceptionEvent $event): void
{
$this->originListener->onKernelException($event);
if (!$event->hasResponse()) {
// The origin listener not processed.
return;
}
$this->logException($event->getException());
} | php | public function onKernelException(GetResponseForExceptionEvent $event): void
{
$this->originListener->onKernelException($event);
if (!$event->hasResponse()) {
// The origin listener not processed.
return;
}
$this->logException($event->getException());
} | [
"public",
"function",
"onKernelException",
"(",
"GetResponseForExceptionEvent",
"$",
"event",
")",
":",
"void",
"{",
"$",
"this",
"->",
"originListener",
"->",
"onKernelException",
"(",
"$",
"event",
")",
";",
"if",
"(",
"!",
"$",
"event",
"->",
"hasResponse",
"(",
")",
")",
"{",
"// The origin listener not processed.",
"return",
";",
"}",
"$",
"this",
"->",
"logException",
"(",
"$",
"event",
"->",
"getException",
"(",
")",
")",
";",
"}"
] | Handle the exception and log message.
@param GetResponseForExceptionEvent $event | [
"Handle",
"the",
"exception",
"and",
"log",
"message",
"."
] | 048fce7be5357dc23fef1402ef8ca213489e8154 | https://github.com/FiveLab/ResourceBundle/blob/048fce7be5357dc23fef1402ef8ca213489e8154/src/EventListener/LoggingExceptionListener.php#L64-L74 |
7,923 | cobonto/module | src/Classes/Translation/ModuleTranslator.php | ModuleTranslator.moduleLoad | public function moduleLoad($author, $name, $locale)
{
if ($this->isModuleLoaded($author, $name, $locale))
{
return;
}
// The loader is responsible for returning the array of language lines for the
// given namespace, group, and locale. We'll set the lines in this array of
// lines that have already been loaded so that we can easily access them.
$lines = $this->loader->loadModule($locale, $name, $author);
$this->loaded['Modules'][$author][$name][$locale] = $lines;
} | php | public function moduleLoad($author, $name, $locale)
{
if ($this->isModuleLoaded($author, $name, $locale))
{
return;
}
// The loader is responsible for returning the array of language lines for the
// given namespace, group, and locale. We'll set the lines in this array of
// lines that have already been loaded so that we can easily access them.
$lines = $this->loader->loadModule($locale, $name, $author);
$this->loaded['Modules'][$author][$name][$locale] = $lines;
} | [
"public",
"function",
"moduleLoad",
"(",
"$",
"author",
",",
"$",
"name",
",",
"$",
"locale",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isModuleLoaded",
"(",
"$",
"author",
",",
"$",
"name",
",",
"$",
"locale",
")",
")",
"{",
"return",
";",
"}",
"// The loader is responsible for returning the array of language lines for the",
"// given namespace, group, and locale. We'll set the lines in this array of",
"// lines that have already been loaded so that we can easily access them.",
"$",
"lines",
"=",
"$",
"this",
"->",
"loader",
"->",
"loadModule",
"(",
"$",
"locale",
",",
"$",
"name",
",",
"$",
"author",
")",
";",
"$",
"this",
"->",
"loaded",
"[",
"'Modules'",
"]",
"[",
"$",
"author",
"]",
"[",
"$",
"name",
"]",
"[",
"$",
"locale",
"]",
"=",
"$",
"lines",
";",
"}"
] | Load the specified language group for modules.
@param string $author
@param string $name
@param string $locale
@return void | [
"Load",
"the",
"specified",
"language",
"group",
"for",
"modules",
"."
] | 0978b5305c3d6f13ef7e0e5297855bd09eee6b76 | https://github.com/cobonto/module/blob/0978b5305c3d6f13ef7e0e5297855bd09eee6b76/src/Classes/Translation/ModuleTranslator.php#L101-L113 |
7,924 | cobonto/module | src/Classes/Translation/ModuleTranslator.php | ModuleTranslator.isModuleLoaded | protected function isModuleLoaded($author, $name, $locale)
{
return isset($this->loaded['Modules'][$author][$name][$locale]);
} | php | protected function isModuleLoaded($author, $name, $locale)
{
return isset($this->loaded['Modules'][$author][$name][$locale]);
} | [
"protected",
"function",
"isModuleLoaded",
"(",
"$",
"author",
",",
"$",
"name",
",",
"$",
"locale",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"loaded",
"[",
"'Modules'",
"]",
"[",
"$",
"author",
"]",
"[",
"$",
"name",
"]",
"[",
"$",
"locale",
"]",
")",
";",
"}"
] | Determine if the given module has been loaded.
@param string $namespace
@param string $group
@param string $locale
@return bool | [
"Determine",
"if",
"the",
"given",
"module",
"has",
"been",
"loaded",
"."
] | 0978b5305c3d6f13ef7e0e5297855bd09eee6b76 | https://github.com/cobonto/module/blob/0978b5305c3d6f13ef7e0e5297855bd09eee6b76/src/Classes/Translation/ModuleTranslator.php#L123-L126 |
7,925 | ferguson-mr/yii2-base | widgets/emailCaptcha/EmailCaptchaValidator.php | EmailCaptchaValidator.validateAttribute | public function validateAttribute($model, $attribute)
{
$value = $model->$attribute;
$captcha = $this->createCaptchaAction($model);
$valid = !is_array($value) && $captcha->validate($value);
$isExpired = $captcha->isExpired();
$result = $isExpired ? [$this->getMessageForExpiredCaptcha(), []] : ($valid ? null : [$this->message, []]);
// $result = $this->validateValue($model->$attribute, $model);
if (!empty($result)) {
$this->addError($model, $attribute, $result[0], $result[1]);
}
} | php | public function validateAttribute($model, $attribute)
{
$value = $model->$attribute;
$captcha = $this->createCaptchaAction($model);
$valid = !is_array($value) && $captcha->validate($value);
$isExpired = $captcha->isExpired();
$result = $isExpired ? [$this->getMessageForExpiredCaptcha(), []] : ($valid ? null : [$this->message, []]);
// $result = $this->validateValue($model->$attribute, $model);
if (!empty($result)) {
$this->addError($model, $attribute, $result[0], $result[1]);
}
} | [
"public",
"function",
"validateAttribute",
"(",
"$",
"model",
",",
"$",
"attribute",
")",
"{",
"$",
"value",
"=",
"$",
"model",
"->",
"$",
"attribute",
";",
"$",
"captcha",
"=",
"$",
"this",
"->",
"createCaptchaAction",
"(",
"$",
"model",
")",
";",
"$",
"valid",
"=",
"!",
"is_array",
"(",
"$",
"value",
")",
"&&",
"$",
"captcha",
"->",
"validate",
"(",
"$",
"value",
")",
";",
"$",
"isExpired",
"=",
"$",
"captcha",
"->",
"isExpired",
"(",
")",
";",
"$",
"result",
"=",
"$",
"isExpired",
"?",
"[",
"$",
"this",
"->",
"getMessageForExpiredCaptcha",
"(",
")",
",",
"[",
"]",
"]",
":",
"(",
"$",
"valid",
"?",
"null",
":",
"[",
"$",
"this",
"->",
"message",
",",
"[",
"]",
"]",
")",
";",
"// $result = $this->validateValue($model->$attribute, $model);",
"if",
"(",
"!",
"empty",
"(",
"$",
"result",
")",
")",
"{",
"$",
"this",
"->",
"addError",
"(",
"$",
"model",
",",
"$",
"attribute",
",",
"$",
"result",
"[",
"0",
"]",
",",
"$",
"result",
"[",
"1",
"]",
")",
";",
"}",
"}"
] | Validates a single attribute.
Child classes must implement this method to provide the actual validation logic.
@param \yii\base\Model $model the data model to be validated
@param string $attribute the name of the attribute to be validated. | [
"Validates",
"a",
"single",
"attribute",
".",
"Child",
"classes",
"must",
"implement",
"this",
"method",
"to",
"provide",
"the",
"actual",
"validation",
"logic",
"."
] | 627a6907003421d6db48f400d878bce33db79c50 | https://github.com/ferguson-mr/yii2-base/blob/627a6907003421d6db48f400d878bce33db79c50/widgets/emailCaptcha/EmailCaptchaValidator.php#L41-L53 |
7,926 | ARCANESOFT/Tracker | src/ViewComposers/Dashboard/CountriesListComposer.php | CountriesListComposer.getCountriesCountFromSessions | private function getCountriesCountFromSessions(Carbon $start, Carbon $end)
{
return $this->getVisitorsFilteredByDateRange($start, $end)
->transform(function (Visitor $visitor) {
return $visitor->hasGeoip()
? [
'code' => $visitor->geoip->iso_code,
'geoip' => $visitor->geoip,
]
: [
'code' => 'undefined',
'geoip' => null,
];
})
->groupBy('code')
->transform(function (Collection $items, $key) {
return ($key === 'undefined')
? [
'code' => null,
'name' => trans('tracker::generals.undefined'),
'count' => $items->count(),
]
: [
'code' => $key,
'name' => $items->first()['geoip']->country,
'count' => $items->count(),
];
});
} | php | private function getCountriesCountFromSessions(Carbon $start, Carbon $end)
{
return $this->getVisitorsFilteredByDateRange($start, $end)
->transform(function (Visitor $visitor) {
return $visitor->hasGeoip()
? [
'code' => $visitor->geoip->iso_code,
'geoip' => $visitor->geoip,
]
: [
'code' => 'undefined',
'geoip' => null,
];
})
->groupBy('code')
->transform(function (Collection $items, $key) {
return ($key === 'undefined')
? [
'code' => null,
'name' => trans('tracker::generals.undefined'),
'count' => $items->count(),
]
: [
'code' => $key,
'name' => $items->first()['geoip']->country,
'count' => $items->count(),
];
});
} | [
"private",
"function",
"getCountriesCountFromSessions",
"(",
"Carbon",
"$",
"start",
",",
"Carbon",
"$",
"end",
")",
"{",
"return",
"$",
"this",
"->",
"getVisitorsFilteredByDateRange",
"(",
"$",
"start",
",",
"$",
"end",
")",
"->",
"transform",
"(",
"function",
"(",
"Visitor",
"$",
"visitor",
")",
"{",
"return",
"$",
"visitor",
"->",
"hasGeoip",
"(",
")",
"?",
"[",
"'code'",
"=>",
"$",
"visitor",
"->",
"geoip",
"->",
"iso_code",
",",
"'geoip'",
"=>",
"$",
"visitor",
"->",
"geoip",
",",
"]",
":",
"[",
"'code'",
"=>",
"'undefined'",
",",
"'geoip'",
"=>",
"null",
",",
"]",
";",
"}",
")",
"->",
"groupBy",
"(",
"'code'",
")",
"->",
"transform",
"(",
"function",
"(",
"Collection",
"$",
"items",
",",
"$",
"key",
")",
"{",
"return",
"(",
"$",
"key",
"===",
"'undefined'",
")",
"?",
"[",
"'code'",
"=>",
"null",
",",
"'name'",
"=>",
"trans",
"(",
"'tracker::generals.undefined'",
")",
",",
"'count'",
"=>",
"$",
"items",
"->",
"count",
"(",
")",
",",
"]",
":",
"[",
"'code'",
"=>",
"$",
"key",
",",
"'name'",
"=>",
"$",
"items",
"->",
"first",
"(",
")",
"[",
"'geoip'",
"]",
"->",
"country",
",",
"'count'",
"=>",
"$",
"items",
"->",
"count",
"(",
")",
",",
"]",
";",
"}",
")",
";",
"}"
] | Get the countries count from sessions.
@param \Carbon\Carbon $start
@param \Carbon\Carbon $end
@return \Illuminate\Support\Collection | [
"Get",
"the",
"countries",
"count",
"from",
"sessions",
"."
] | d106209b32ddbb192066715f0ef99afccfc22dcb | https://github.com/ARCANESOFT/Tracker/blob/d106209b32ddbb192066715f0ef99afccfc22dcb/src/ViewComposers/Dashboard/CountriesListComposer.php#L62-L90 |
7,927 | ARCANESOFT/Tracker | src/ViewComposers/Dashboard/CountriesListComposer.php | CountriesListComposer.calculateCountriesPercentage | private function calculateCountriesPercentage(Collection $countries)
{
$total = $countries->sum('count');
return $countries->transform(function ($item) use ($total) {
return $item + [
'percentage' => round(($item['count'] / $total) * 100, 2)
];
});
} | php | private function calculateCountriesPercentage(Collection $countries)
{
$total = $countries->sum('count');
return $countries->transform(function ($item) use ($total) {
return $item + [
'percentage' => round(($item['count'] / $total) * 100, 2)
];
});
} | [
"private",
"function",
"calculateCountriesPercentage",
"(",
"Collection",
"$",
"countries",
")",
"{",
"$",
"total",
"=",
"$",
"countries",
"->",
"sum",
"(",
"'count'",
")",
";",
"return",
"$",
"countries",
"->",
"transform",
"(",
"function",
"(",
"$",
"item",
")",
"use",
"(",
"$",
"total",
")",
"{",
"return",
"$",
"item",
"+",
"[",
"'percentage'",
"=>",
"round",
"(",
"(",
"$",
"item",
"[",
"'count'",
"]",
"/",
"$",
"total",
")",
"*",
"100",
",",
"2",
")",
"]",
";",
"}",
")",
";",
"}"
] | Calculate countries percentage.
@param \Illuminate\Support\Collection $countries
@return \Illuminate\Support\Collection | [
"Calculate",
"countries",
"percentage",
"."
] | d106209b32ddbb192066715f0ef99afccfc22dcb | https://github.com/ARCANESOFT/Tracker/blob/d106209b32ddbb192066715f0ef99afccfc22dcb/src/ViewComposers/Dashboard/CountriesListComposer.php#L99-L108 |
7,928 | DivideBV/PHPDivideIQ | src/DivideIQ.php | DivideIQ.request | public function request($serviceName, $payload = [], $method = 'GET')
{
// Setup the connection.
$this->setup();
$path = $this->settings->getPath($serviceName);
switch ($method) {
case 'GET':
// Perform the request with the payload as a query string.
$response = $this->client->get($path, [
'headers' => ['Authentication' => $this->accessToken->getToken()],
'query' => $payload,
]);
break;
case 'POST':
$response = $this->client->post($path, [
'headers' => ['Authentication' => $this->accessToken->getToken()],
'json' => $payload,
]);
break;
}
// Parse the response body.
$json = json_decode($response->getBody());
$body = $json->{'nl.divide.iq'};
// Check if the settings object is outdated. If so, unset it.
if ($this->settings->isOutdated($body->settings_updated)) {
unset($this->settings);
}
// Check if there was an error.
if (!isset($body->response->content)) {
$message = $body->response->answer;
$message .= isset($body->response->message) ? ": {$body->response->message}" : '';
// Throw an exception with the error description from the service.
throw new \Exception($message);
}
// Return only the response content, without the metadata.
return $body->response->content;
} | php | public function request($serviceName, $payload = [], $method = 'GET')
{
// Setup the connection.
$this->setup();
$path = $this->settings->getPath($serviceName);
switch ($method) {
case 'GET':
// Perform the request with the payload as a query string.
$response = $this->client->get($path, [
'headers' => ['Authentication' => $this->accessToken->getToken()],
'query' => $payload,
]);
break;
case 'POST':
$response = $this->client->post($path, [
'headers' => ['Authentication' => $this->accessToken->getToken()],
'json' => $payload,
]);
break;
}
// Parse the response body.
$json = json_decode($response->getBody());
$body = $json->{'nl.divide.iq'};
// Check if the settings object is outdated. If so, unset it.
if ($this->settings->isOutdated($body->settings_updated)) {
unset($this->settings);
}
// Check if there was an error.
if (!isset($body->response->content)) {
$message = $body->response->answer;
$message .= isset($body->response->message) ? ": {$body->response->message}" : '';
// Throw an exception with the error description from the service.
throw new \Exception($message);
}
// Return only the response content, without the metadata.
return $body->response->content;
} | [
"public",
"function",
"request",
"(",
"$",
"serviceName",
",",
"$",
"payload",
"=",
"[",
"]",
",",
"$",
"method",
"=",
"'GET'",
")",
"{",
"// Setup the connection.",
"$",
"this",
"->",
"setup",
"(",
")",
";",
"$",
"path",
"=",
"$",
"this",
"->",
"settings",
"->",
"getPath",
"(",
"$",
"serviceName",
")",
";",
"switch",
"(",
"$",
"method",
")",
"{",
"case",
"'GET'",
":",
"// Perform the request with the payload as a query string.",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"get",
"(",
"$",
"path",
",",
"[",
"'headers'",
"=>",
"[",
"'Authentication'",
"=>",
"$",
"this",
"->",
"accessToken",
"->",
"getToken",
"(",
")",
"]",
",",
"'query'",
"=>",
"$",
"payload",
",",
"]",
")",
";",
"break",
";",
"case",
"'POST'",
":",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"post",
"(",
"$",
"path",
",",
"[",
"'headers'",
"=>",
"[",
"'Authentication'",
"=>",
"$",
"this",
"->",
"accessToken",
"->",
"getToken",
"(",
")",
"]",
",",
"'json'",
"=>",
"$",
"payload",
",",
"]",
")",
";",
"break",
";",
"}",
"// Parse the response body.",
"$",
"json",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
")",
";",
"$",
"body",
"=",
"$",
"json",
"->",
"{",
"'nl.divide.iq'",
"}",
";",
"// Check if the settings object is outdated. If so, unset it.",
"if",
"(",
"$",
"this",
"->",
"settings",
"->",
"isOutdated",
"(",
"$",
"body",
"->",
"settings_updated",
")",
")",
"{",
"unset",
"(",
"$",
"this",
"->",
"settings",
")",
";",
"}",
"// Check if there was an error.",
"if",
"(",
"!",
"isset",
"(",
"$",
"body",
"->",
"response",
"->",
"content",
")",
")",
"{",
"$",
"message",
"=",
"$",
"body",
"->",
"response",
"->",
"answer",
";",
"$",
"message",
".=",
"isset",
"(",
"$",
"body",
"->",
"response",
"->",
"message",
")",
"?",
"\": {$body->response->message}\"",
":",
"''",
";",
"// Throw an exception with the error description from the service.",
"throw",
"new",
"\\",
"Exception",
"(",
"$",
"message",
")",
";",
"}",
"// Return only the response content, without the metadata.",
"return",
"$",
"body",
"->",
"response",
"->",
"content",
";",
"}"
] | Accesses a service provided by Divide.IQ using the stored access token.
@param string $serviceName
The codename of the service to access.
@param array $payload
(optional) The data to send with the request.
@param string $method
(optional) The HTTP method to use to access the service. Defaults to
`GET`.
@see http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods | [
"Accesses",
"a",
"service",
"provided",
"by",
"Divide",
".",
"IQ",
"using",
"the",
"stored",
"access",
"token",
"."
] | bd12e3c226b061d7152f93ab1195fbaaf074b20d | https://github.com/DivideBV/PHPDivideIQ/blob/bd12e3c226b061d7152f93ab1195fbaaf074b20d/src/DivideIQ.php#L164-L209 |
7,929 | DivideBV/PHPDivideIQ | src/DivideIQ.php | DivideIQ.download | public function download($uri, $destination)
{
// Setup the connection.
$this->setup();
$this->client->get($uri, [
'headers' => [
'Content-Type' => null,
'Authentication' => $this->accessToken->getToken(),
],
'sink' => $destination,
]);
} | php | public function download($uri, $destination)
{
// Setup the connection.
$this->setup();
$this->client->get($uri, [
'headers' => [
'Content-Type' => null,
'Authentication' => $this->accessToken->getToken(),
],
'sink' => $destination,
]);
} | [
"public",
"function",
"download",
"(",
"$",
"uri",
",",
"$",
"destination",
")",
"{",
"// Setup the connection.",
"$",
"this",
"->",
"setup",
"(",
")",
";",
"$",
"this",
"->",
"client",
"->",
"get",
"(",
"$",
"uri",
",",
"[",
"'headers'",
"=>",
"[",
"'Content-Type'",
"=>",
"null",
",",
"'Authentication'",
"=>",
"$",
"this",
"->",
"accessToken",
"->",
"getToken",
"(",
")",
",",
"]",
",",
"'sink'",
"=>",
"$",
"destination",
",",
"]",
")",
";",
"}"
] | Downloads a file using current client configuration and saves it at the specified destination.
@param string|\Psr\Http\Message\UriInterface $uri File URI.
@param string|resource|\Psr\Http\Message\StreamInterface $destination Destination where the file should be saved to. | [
"Downloads",
"a",
"file",
"using",
"current",
"client",
"configuration",
"and",
"saves",
"it",
"at",
"the",
"specified",
"destination",
"."
] | bd12e3c226b061d7152f93ab1195fbaaf074b20d | https://github.com/DivideBV/PHPDivideIQ/blob/bd12e3c226b061d7152f93ab1195fbaaf074b20d/src/DivideIQ.php#L217-L229 |
7,930 | DivideBV/PHPDivideIQ | src/DivideIQ.php | DivideIQ.fromFile | public static function fromFile(\SplFileObject $file)
{
$file->rewind();
$object = static::fromJson($file->fread($file->getSize()));
$object->file = $file;
return $object;
} | php | public static function fromFile(\SplFileObject $file)
{
$file->rewind();
$object = static::fromJson($file->fread($file->getSize()));
$object->file = $file;
return $object;
} | [
"public",
"static",
"function",
"fromFile",
"(",
"\\",
"SplFileObject",
"$",
"file",
")",
"{",
"$",
"file",
"->",
"rewind",
"(",
")",
";",
"$",
"object",
"=",
"static",
"::",
"fromJson",
"(",
"$",
"file",
"->",
"fread",
"(",
"$",
"file",
"->",
"getSize",
"(",
")",
")",
")",
";",
"$",
"object",
"->",
"file",
"=",
"$",
"file",
";",
"return",
"$",
"object",
";",
"}"
] | Unserializes the object from JSON contained in the given file.
@param \SplFileObject $file
The file to be read from. Since it may also be written to, it should
be opened with mode `c+`.
@return DivideIQ
The unserialized object. | [
"Unserializes",
"the",
"object",
"from",
"JSON",
"contained",
"in",
"the",
"given",
"file",
"."
] | bd12e3c226b061d7152f93ab1195fbaaf074b20d | https://github.com/DivideBV/PHPDivideIQ/blob/bd12e3c226b061d7152f93ab1195fbaaf074b20d/src/DivideIQ.php#L252-L259 |
7,931 | DivideBV/PHPDivideIQ | src/DivideIQ.php | DivideIQ.setup | protected function setup()
{
// Check if a valid access token exists.
if (!$this->accessToken || $this->accessToken->expired()) {
// Refresh is successful unless explicitly set to false.
$refreshSuccess = true;
// Check if a valid refresh token exists.
if ($this->refreshToken && $this->refreshToken->getToken()) {
// Attempt to use the refresh token.
try {
$this->refresh();
} catch (RequestException $e) {
// Check if the exception is due to an HTTP 403.
if ($e->getCode() == 403) {
$response = $e->getResponse();
$json = json_decode($response->getBody());
$body = $json->{'nl.divide.iq'};
// Check if the error is indeed a "TokenExpired" error,
// as expected.
if ($body->answer == 'TokenExpired') {
// Token is expired; refreshing unsuccessful.
$refreshSuccess = false;
} else {
// Unexpected error. Pass it up the stack. This
// might be a "TokenEmpty" error, but that would
// still be unexpected, because the token value was
// checked beforehand.
throw $e;
}
} else {
// Unexpected error. Pass it up the stack.
throw $e;
}
}
} else {
// There is no refresh token to use; refreshing unsuccessful.
$refreshSuccess = false;
}
// If refreshing failed, login from scratch and then authenticate.
if (!$refreshSuccess) {
$this->login()->authenticate();
}
}
// Request the settings if needed.
if (!$this->settings) {
$response = $this->client->get('settings', [
'headers' => ['Authentication' => $this->accessToken->getToken()],
]);
$json = json_decode($response->getBody());
$body = $json->{'nl.divide.iq'};
$services = [];
foreach ($body->services as $service) {
$services[] = $service->code;
}
// Create new settings object.
$this->settings = new Settings($services, $body->settings_updated);
}
} | php | protected function setup()
{
// Check if a valid access token exists.
if (!$this->accessToken || $this->accessToken->expired()) {
// Refresh is successful unless explicitly set to false.
$refreshSuccess = true;
// Check if a valid refresh token exists.
if ($this->refreshToken && $this->refreshToken->getToken()) {
// Attempt to use the refresh token.
try {
$this->refresh();
} catch (RequestException $e) {
// Check if the exception is due to an HTTP 403.
if ($e->getCode() == 403) {
$response = $e->getResponse();
$json = json_decode($response->getBody());
$body = $json->{'nl.divide.iq'};
// Check if the error is indeed a "TokenExpired" error,
// as expected.
if ($body->answer == 'TokenExpired') {
// Token is expired; refreshing unsuccessful.
$refreshSuccess = false;
} else {
// Unexpected error. Pass it up the stack. This
// might be a "TokenEmpty" error, but that would
// still be unexpected, because the token value was
// checked beforehand.
throw $e;
}
} else {
// Unexpected error. Pass it up the stack.
throw $e;
}
}
} else {
// There is no refresh token to use; refreshing unsuccessful.
$refreshSuccess = false;
}
// If refreshing failed, login from scratch and then authenticate.
if (!$refreshSuccess) {
$this->login()->authenticate();
}
}
// Request the settings if needed.
if (!$this->settings) {
$response = $this->client->get('settings', [
'headers' => ['Authentication' => $this->accessToken->getToken()],
]);
$json = json_decode($response->getBody());
$body = $json->{'nl.divide.iq'};
$services = [];
foreach ($body->services as $service) {
$services[] = $service->code;
}
// Create new settings object.
$this->settings = new Settings($services, $body->settings_updated);
}
} | [
"protected",
"function",
"setup",
"(",
")",
"{",
"// Check if a valid access token exists.",
"if",
"(",
"!",
"$",
"this",
"->",
"accessToken",
"||",
"$",
"this",
"->",
"accessToken",
"->",
"expired",
"(",
")",
")",
"{",
"// Refresh is successful unless explicitly set to false.",
"$",
"refreshSuccess",
"=",
"true",
";",
"// Check if a valid refresh token exists.",
"if",
"(",
"$",
"this",
"->",
"refreshToken",
"&&",
"$",
"this",
"->",
"refreshToken",
"->",
"getToken",
"(",
")",
")",
"{",
"// Attempt to use the refresh token.",
"try",
"{",
"$",
"this",
"->",
"refresh",
"(",
")",
";",
"}",
"catch",
"(",
"RequestException",
"$",
"e",
")",
"{",
"// Check if the exception is due to an HTTP 403.",
"if",
"(",
"$",
"e",
"->",
"getCode",
"(",
")",
"==",
"403",
")",
"{",
"$",
"response",
"=",
"$",
"e",
"->",
"getResponse",
"(",
")",
";",
"$",
"json",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
")",
";",
"$",
"body",
"=",
"$",
"json",
"->",
"{",
"'nl.divide.iq'",
"}",
";",
"// Check if the error is indeed a \"TokenExpired\" error,",
"// as expected.",
"if",
"(",
"$",
"body",
"->",
"answer",
"==",
"'TokenExpired'",
")",
"{",
"// Token is expired; refreshing unsuccessful.",
"$",
"refreshSuccess",
"=",
"false",
";",
"}",
"else",
"{",
"// Unexpected error. Pass it up the stack. This",
"// might be a \"TokenEmpty\" error, but that would",
"// still be unexpected, because the token value was",
"// checked beforehand.",
"throw",
"$",
"e",
";",
"}",
"}",
"else",
"{",
"// Unexpected error. Pass it up the stack.",
"throw",
"$",
"e",
";",
"}",
"}",
"}",
"else",
"{",
"// There is no refresh token to use; refreshing unsuccessful.",
"$",
"refreshSuccess",
"=",
"false",
";",
"}",
"// If refreshing failed, login from scratch and then authenticate.",
"if",
"(",
"!",
"$",
"refreshSuccess",
")",
"{",
"$",
"this",
"->",
"login",
"(",
")",
"->",
"authenticate",
"(",
")",
";",
"}",
"}",
"// Request the settings if needed.",
"if",
"(",
"!",
"$",
"this",
"->",
"settings",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"get",
"(",
"'settings'",
",",
"[",
"'headers'",
"=>",
"[",
"'Authentication'",
"=>",
"$",
"this",
"->",
"accessToken",
"->",
"getToken",
"(",
")",
"]",
",",
"]",
")",
";",
"$",
"json",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
")",
";",
"$",
"body",
"=",
"$",
"json",
"->",
"{",
"'nl.divide.iq'",
"}",
";",
"$",
"services",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"body",
"->",
"services",
"as",
"$",
"service",
")",
"{",
"$",
"services",
"[",
"]",
"=",
"$",
"service",
"->",
"code",
";",
"}",
"// Create new settings object.",
"$",
"this",
"->",
"settings",
"=",
"new",
"Settings",
"(",
"$",
"services",
",",
"$",
"body",
"->",
"settings_updated",
")",
";",
"}",
"}"
] | Sets up a connection with the Divide.IQ server. | [
"Sets",
"up",
"a",
"connection",
"with",
"the",
"Divide",
".",
"IQ",
"server",
"."
] | bd12e3c226b061d7152f93ab1195fbaaf074b20d | https://github.com/DivideBV/PHPDivideIQ/blob/bd12e3c226b061d7152f93ab1195fbaaf074b20d/src/DivideIQ.php#L303-L366 |
7,932 | DivideBV/PHPDivideIQ | src/DivideIQ.php | DivideIQ.login | protected function login()
{
// Perform a request with the login credentials in the request header.
$response = $this->client->get('services/login', [
'headers' => ['username'=> $this->username, 'password' => $this->password],
]);
// Parse the response body.
$json = json_decode($response->getBody());
$body = $json->{'nl.divide.iq'};
$expire = new \DateTime($body->expiration_date, new \DateTimezone('UTC'));
// Store the authentication token in the object.
$this->authToken = new Token($body->authentication_token, $expire);
return $this;
} | php | protected function login()
{
// Perform a request with the login credentials in the request header.
$response = $this->client->get('services/login', [
'headers' => ['username'=> $this->username, 'password' => $this->password],
]);
// Parse the response body.
$json = json_decode($response->getBody());
$body = $json->{'nl.divide.iq'};
$expire = new \DateTime($body->expiration_date, new \DateTimezone('UTC'));
// Store the authentication token in the object.
$this->authToken = new Token($body->authentication_token, $expire);
return $this;
} | [
"protected",
"function",
"login",
"(",
")",
"{",
"// Perform a request with the login credentials in the request header.",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"get",
"(",
"'services/login'",
",",
"[",
"'headers'",
"=>",
"[",
"'username'",
"=>",
"$",
"this",
"->",
"username",
",",
"'password'",
"=>",
"$",
"this",
"->",
"password",
"]",
",",
"]",
")",
";",
"// Parse the response body.",
"$",
"json",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
")",
";",
"$",
"body",
"=",
"$",
"json",
"->",
"{",
"'nl.divide.iq'",
"}",
";",
"$",
"expire",
"=",
"new",
"\\",
"DateTime",
"(",
"$",
"body",
"->",
"expiration_date",
",",
"new",
"\\",
"DateTimezone",
"(",
"'UTC'",
")",
")",
";",
"// Store the authentication token in the object.",
"$",
"this",
"->",
"authToken",
"=",
"new",
"Token",
"(",
"$",
"body",
"->",
"authentication_token",
",",
"$",
"expire",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Logs in using the provided credentials. | [
"Logs",
"in",
"using",
"the",
"provided",
"credentials",
"."
] | bd12e3c226b061d7152f93ab1195fbaaf074b20d | https://github.com/DivideBV/PHPDivideIQ/blob/bd12e3c226b061d7152f93ab1195fbaaf074b20d/src/DivideIQ.php#L371-L387 |
7,933 | DivideBV/PHPDivideIQ | src/DivideIQ.php | DivideIQ.authenticate | protected function authenticate($refresh = false)
{
$token = $refresh ? $this->refreshToken : $this->authToken ;
$response = $this->client->get('authenticate', [
'headers' => ['Authentication' => $token->getToken()],
]);
// Parse the response body.
$json = json_decode($response->getBody());
$body = $json->{'nl.divide.iq'};
$expire = new \DateTime($body->expiration_date, new \DateTimezone('UTC'));
// Store the access and refresh (if any) tokens in the object.
$this->accessToken = new Token($body->access_token, $expire);
if (isset($body->refresh_token)) {
$this->refreshToken = new Token($body->refresh_token);
}
return $this;
} | php | protected function authenticate($refresh = false)
{
$token = $refresh ? $this->refreshToken : $this->authToken ;
$response = $this->client->get('authenticate', [
'headers' => ['Authentication' => $token->getToken()],
]);
// Parse the response body.
$json = json_decode($response->getBody());
$body = $json->{'nl.divide.iq'};
$expire = new \DateTime($body->expiration_date, new \DateTimezone('UTC'));
// Store the access and refresh (if any) tokens in the object.
$this->accessToken = new Token($body->access_token, $expire);
if (isset($body->refresh_token)) {
$this->refreshToken = new Token($body->refresh_token);
}
return $this;
} | [
"protected",
"function",
"authenticate",
"(",
"$",
"refresh",
"=",
"false",
")",
"{",
"$",
"token",
"=",
"$",
"refresh",
"?",
"$",
"this",
"->",
"refreshToken",
":",
"$",
"this",
"->",
"authToken",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"get",
"(",
"'authenticate'",
",",
"[",
"'headers'",
"=>",
"[",
"'Authentication'",
"=>",
"$",
"token",
"->",
"getToken",
"(",
")",
"]",
",",
"]",
")",
";",
"// Parse the response body.",
"$",
"json",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
")",
";",
"$",
"body",
"=",
"$",
"json",
"->",
"{",
"'nl.divide.iq'",
"}",
";",
"$",
"expire",
"=",
"new",
"\\",
"DateTime",
"(",
"$",
"body",
"->",
"expiration_date",
",",
"new",
"\\",
"DateTimezone",
"(",
"'UTC'",
")",
")",
";",
"// Store the access and refresh (if any) tokens in the object.",
"$",
"this",
"->",
"accessToken",
"=",
"new",
"Token",
"(",
"$",
"body",
"->",
"access_token",
",",
"$",
"expire",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"body",
"->",
"refresh_token",
")",
")",
"{",
"$",
"this",
"->",
"refreshToken",
"=",
"new",
"Token",
"(",
"$",
"body",
"->",
"refresh_token",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Authenticates using the stored authentication token.
@param bool $refresh
Whether to use the refresh token instead of the authentication token. | [
"Authenticates",
"using",
"the",
"stored",
"authentication",
"token",
"."
] | bd12e3c226b061d7152f93ab1195fbaaf074b20d | https://github.com/DivideBV/PHPDivideIQ/blob/bd12e3c226b061d7152f93ab1195fbaaf074b20d/src/DivideIQ.php#L395-L415 |
7,934 | FrenzelGmbH/sblog | controllers/WidgetconfigController.php | WidgetconfigController.actionAddlocation | public function actionAddlocation($module=NULL,$id=NULL)
{
$model=new WidgetConfig;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$query = WidgetConfig::findRelatedRecords('MAPWIDGET', $model->wgt_table, $model->wgt_id);
$dpLocations = new ActiveDataProvider(array(
'query' => $query,
));
return $this->renderAjax('@frenzelgmbh/sblog/widgets/views/_mapwidget',[
'dpLocations' => $dpLocations,
'module' => $model->wgt_table,
'id' => $model->wgt_id
]);
} else {
$model->wgt_id = $id;
$model->wgt_table = $module;
$model->name = 'MAPWIDGET';
return $this->renderAjax('_form_addlocation', array(
'model' => $model,
));
}
} | php | public function actionAddlocation($module=NULL,$id=NULL)
{
$model=new WidgetConfig;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$query = WidgetConfig::findRelatedRecords('MAPWIDGET', $model->wgt_table, $model->wgt_id);
$dpLocations = new ActiveDataProvider(array(
'query' => $query,
));
return $this->renderAjax('@frenzelgmbh/sblog/widgets/views/_mapwidget',[
'dpLocations' => $dpLocations,
'module' => $model->wgt_table,
'id' => $model->wgt_id
]);
} else {
$model->wgt_id = $id;
$model->wgt_table = $module;
$model->name = 'MAPWIDGET';
return $this->renderAjax('_form_addlocation', array(
'model' => $model,
));
}
} | [
"public",
"function",
"actionAddlocation",
"(",
"$",
"module",
"=",
"NULL",
",",
"$",
"id",
"=",
"NULL",
")",
"{",
"$",
"model",
"=",
"new",
"WidgetConfig",
";",
"if",
"(",
"$",
"model",
"->",
"load",
"(",
"Yii",
"::",
"$",
"app",
"->",
"request",
"->",
"post",
"(",
")",
")",
"&&",
"$",
"model",
"->",
"save",
"(",
")",
")",
"{",
"$",
"query",
"=",
"WidgetConfig",
"::",
"findRelatedRecords",
"(",
"'MAPWIDGET'",
",",
"$",
"model",
"->",
"wgt_table",
",",
"$",
"model",
"->",
"wgt_id",
")",
";",
"$",
"dpLocations",
"=",
"new",
"ActiveDataProvider",
"(",
"array",
"(",
"'query'",
"=>",
"$",
"query",
",",
")",
")",
";",
"return",
"$",
"this",
"->",
"renderAjax",
"(",
"'@frenzelgmbh/sblog/widgets/views/_mapwidget'",
",",
"[",
"'dpLocations'",
"=>",
"$",
"dpLocations",
",",
"'module'",
"=>",
"$",
"model",
"->",
"wgt_table",
",",
"'id'",
"=>",
"$",
"model",
"->",
"wgt_id",
"]",
")",
";",
"}",
"else",
"{",
"$",
"model",
"->",
"wgt_id",
"=",
"$",
"id",
";",
"$",
"model",
"->",
"wgt_table",
"=",
"$",
"module",
";",
"$",
"model",
"->",
"name",
"=",
"'MAPWIDGET'",
";",
"return",
"$",
"this",
"->",
"renderAjax",
"(",
"'_form_addlocation'",
",",
"array",
"(",
"'model'",
"=>",
"$",
"model",
",",
")",
")",
";",
"}",
"}"
] | will create a new commment
@param integer $id [description]
@param integer $module [description]
@return [type] [description] | [
"will",
"create",
"a",
"new",
"commment"
] | 8a8b967f57cee9c9323403847f2556a35bdb4a71 | https://github.com/FrenzelGmbH/sblog/blob/8a8b967f57cee9c9323403847f2556a35bdb4a71/controllers/WidgetconfigController.php#L75-L97 |
7,935 | appcia/utils | src/Appcia/Utils/Php.php | Php.getSetting | public static function getSetting($key, $value = null)
{
$data = ini_get($key);
if ($data === false) {
throw new \InvalidArgumentException(sprintf("Invalid PHP setting '%s'", $key));
}
if ($value === null) {
return $data;
} else {
ini_set($key, $value);
}
} | php | public static function getSetting($key, $value = null)
{
$data = ini_get($key);
if ($data === false) {
throw new \InvalidArgumentException(sprintf("Invalid PHP setting '%s'", $key));
}
if ($value === null) {
return $data;
} else {
ini_set($key, $value);
}
} | [
"public",
"static",
"function",
"getSetting",
"(",
"$",
"key",
",",
"$",
"value",
"=",
"null",
")",
"{",
"$",
"data",
"=",
"ini_get",
"(",
"$",
"key",
")",
";",
"if",
"(",
"$",
"data",
"===",
"false",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"\"Invalid PHP setting '%s'\"",
",",
"$",
"key",
")",
")",
";",
"}",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"return",
"$",
"data",
";",
"}",
"else",
"{",
"ini_set",
"(",
"$",
"key",
",",
"$",
"value",
")",
";",
"}",
"}"
] | Get PHP setting runtime value with parameter name check
@param string $key
@param mixed $value
@return string
@throws \InvalidArgumentException | [
"Get",
"PHP",
"setting",
"runtime",
"value",
"with",
"parameter",
"name",
"check"
] | 8f7874e2c6563bcac0be821381d0c3b541999e40 | https://github.com/appcia/utils/blob/8f7874e2c6563bcac0be821381d0c3b541999e40/src/Appcia/Utils/Php.php#L19-L31 |
7,936 | appcia/utils | src/Appcia/Utils/Php.php | Php.decode | public static function decode($value)
{
if (empty($value)) {
return null;
}
if (!is_string($value)) {
throw new \InvalidArgumentException(sprintf(
"Value type '%s' is not a PHP string so it cannot be unserialized.",
gettype($value)
));
}
$data = unserialize($value);
return $data;
} | php | public static function decode($value)
{
if (empty($value)) {
return null;
}
if (!is_string($value)) {
throw new \InvalidArgumentException(sprintf(
"Value type '%s' is not a PHP string so it cannot be unserialized.",
gettype($value)
));
}
$data = unserialize($value);
return $data;
} | [
"public",
"static",
"function",
"decode",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"\"Value type '%s' is not a PHP string so it cannot be unserialized.\"",
",",
"gettype",
"(",
"$",
"value",
")",
")",
")",
";",
"}",
"$",
"data",
"=",
"unserialize",
"(",
"$",
"value",
")",
";",
"return",
"$",
"data",
";",
"}"
] | Unserialize mixed type data
@param string $value
@return mixed|NULL
@throws \InvalidArgumentException | [
"Unserialize",
"mixed",
"type",
"data"
] | 8f7874e2c6563bcac0be821381d0c3b541999e40 | https://github.com/appcia/utils/blob/8f7874e2c6563bcac0be821381d0c3b541999e40/src/Appcia/Utils/Php.php#L55-L71 |
7,937 | appcia/utils | src/Appcia/Utils/Php.php | Php.isEncoded | public static function isEncoded($data)
{
if (!is_string($data)) {
return false;
}
$data = trim($data);
if ('N;' == $data) {
return true;
}
$match = array();
if (!preg_match('/^([adObis]):/', $data, $match)) {
return false;
}
switch ($match[1]) {
case 'a' :
case 'O' :
case 's' :
if (preg_match("/^{$match[1]}:[0-9]+:.*[;}]\$/s", $data)) {
return true;
}
break;
case 'b' :
case 'i' :
case 'd' :
if (preg_match("/^{$match[1]}:[0-9.E-]+;\$/", $data)) {
return true;
}
break;
}
return false;
} | php | public static function isEncoded($data)
{
if (!is_string($data)) {
return false;
}
$data = trim($data);
if ('N;' == $data) {
return true;
}
$match = array();
if (!preg_match('/^([adObis]):/', $data, $match)) {
return false;
}
switch ($match[1]) {
case 'a' :
case 'O' :
case 's' :
if (preg_match("/^{$match[1]}:[0-9]+:.*[;}]\$/s", $data)) {
return true;
}
break;
case 'b' :
case 'i' :
case 'd' :
if (preg_match("/^{$match[1]}:[0-9.E-]+;\$/", $data)) {
return true;
}
break;
}
return false;
} | [
"public",
"static",
"function",
"isEncoded",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"data",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"data",
"=",
"trim",
"(",
"$",
"data",
")",
";",
"if",
"(",
"'N;'",
"==",
"$",
"data",
")",
"{",
"return",
"true",
";",
"}",
"$",
"match",
"=",
"array",
"(",
")",
";",
"if",
"(",
"!",
"preg_match",
"(",
"'/^([adObis]):/'",
",",
"$",
"data",
",",
"$",
"match",
")",
")",
"{",
"return",
"false",
";",
"}",
"switch",
"(",
"$",
"match",
"[",
"1",
"]",
")",
"{",
"case",
"'a'",
":",
"case",
"'O'",
":",
"case",
"'s'",
":",
"if",
"(",
"preg_match",
"(",
"\"/^{$match[1]}:[0-9]+:.*[;}]\\$/s\"",
",",
"$",
"data",
")",
")",
"{",
"return",
"true",
";",
"}",
"break",
";",
"case",
"'b'",
":",
"case",
"'i'",
":",
"case",
"'d'",
":",
"if",
"(",
"preg_match",
"(",
"\"/^{$match[1]}:[0-9.E-]+;\\$/\"",
",",
"$",
"data",
")",
")",
"{",
"return",
"true",
";",
"}",
"break",
";",
"}",
"return",
"false",
";",
"}"
] | Check whether specified string is serialized in PHP format
@see http://stackoverflow.com/questions/1369936/check-to-see-if-a-string-is-serialized
@param string $data
@return bool | [
"Check",
"whether",
"specified",
"string",
"is",
"serialized",
"in",
"PHP",
"format"
] | 8f7874e2c6563bcac0be821381d0c3b541999e40 | https://github.com/appcia/utils/blob/8f7874e2c6563bcac0be821381d0c3b541999e40/src/Appcia/Utils/Php.php#L82-L118 |
7,938 | avassilenko/route-resolver | src/RouteResolver.php | RouteResolver.getFromRequest | public function getFromRequest($route = null) {
$resolvers = [];
foreach ($this->segmentsResolvers as $key => $resolverClass) {
if( $bindedClass = request()->route($key) ) {
$resolvers[$key] = new $resolverClass($bindedClass);
}
}
// sort resolvers in same order they are in request
if (!empty($resolvers)) {
if (empty($route)) {
$route = \Route::getCurrentRoute()->uri();
}
$segments = explode('/', $route);
$sortedResolvers = [];
foreach($segments as $segment) {
$segment = trim($segment, "{}");
if (isset($resolvers [$segment])) {
$sortedResolvers[$segment] = $resolvers[$segment];
}
}
$resolvers = $sortedResolvers;
}
return empty($resolvers) ? false : $resolvers;
} | php | public function getFromRequest($route = null) {
$resolvers = [];
foreach ($this->segmentsResolvers as $key => $resolverClass) {
if( $bindedClass = request()->route($key) ) {
$resolvers[$key] = new $resolverClass($bindedClass);
}
}
// sort resolvers in same order they are in request
if (!empty($resolvers)) {
if (empty($route)) {
$route = \Route::getCurrentRoute()->uri();
}
$segments = explode('/', $route);
$sortedResolvers = [];
foreach($segments as $segment) {
$segment = trim($segment, "{}");
if (isset($resolvers [$segment])) {
$sortedResolvers[$segment] = $resolvers[$segment];
}
}
$resolvers = $sortedResolvers;
}
return empty($resolvers) ? false : $resolvers;
} | [
"public",
"function",
"getFromRequest",
"(",
"$",
"route",
"=",
"null",
")",
"{",
"$",
"resolvers",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"segmentsResolvers",
"as",
"$",
"key",
"=>",
"$",
"resolverClass",
")",
"{",
"if",
"(",
"$",
"bindedClass",
"=",
"request",
"(",
")",
"->",
"route",
"(",
"$",
"key",
")",
")",
"{",
"$",
"resolvers",
"[",
"$",
"key",
"]",
"=",
"new",
"$",
"resolverClass",
"(",
"$",
"bindedClass",
")",
";",
"}",
"}",
"// sort resolvers in same order they are in request",
"if",
"(",
"!",
"empty",
"(",
"$",
"resolvers",
")",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"route",
")",
")",
"{",
"$",
"route",
"=",
"\\",
"Route",
"::",
"getCurrentRoute",
"(",
")",
"->",
"uri",
"(",
")",
";",
"}",
"$",
"segments",
"=",
"explode",
"(",
"'/'",
",",
"$",
"route",
")",
";",
"$",
"sortedResolvers",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"segments",
"as",
"$",
"segment",
")",
"{",
"$",
"segment",
"=",
"trim",
"(",
"$",
"segment",
",",
"\"{}\"",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"resolvers",
"[",
"$",
"segment",
"]",
")",
")",
"{",
"$",
"sortedResolvers",
"[",
"$",
"segment",
"]",
"=",
"$",
"resolvers",
"[",
"$",
"segment",
"]",
";",
"}",
"}",
"$",
"resolvers",
"=",
"$",
"sortedResolvers",
";",
"}",
"return",
"empty",
"(",
"$",
"resolvers",
")",
"?",
"false",
":",
"$",
"resolvers",
";",
"}"
] | Test request and dynamically creates classes to resolve properties of binded class
@return [] of Crumby\RouteResolver\ParamResolver | [
"Test",
"request",
"and",
"dynamically",
"creates",
"classes",
"to",
"resolve",
"properties",
"of",
"binded",
"class"
] | 26550d0046b0b5bbf461c4e817ce46168c455525 | https://github.com/avassilenko/route-resolver/blob/26550d0046b0b5bbf461c4e817ce46168c455525/src/RouteResolver.php#L54-L77 |
7,939 | avassilenko/route-resolver | src/RouteResolver.php | RouteResolver.resolveRouteItem | public function resolveRouteItem($uriWithParam = null, $resolvers = null, $trailingSlash = false) {
if (empty($uriWithParam)) {
$uriWithParam = \Route::getCurrentRoute()->uri();
}
if (empty($resolvers)) {
$resolvers = \RouteResolver::getFromRequest($uriWithParam);
}
$resolvedRoute = [];
if (!empty($resolvers)) {
foreach ($resolvers as $parameter => $resolver) {
if ($resolver instanceof ParamResolver) {
if ($item = $resolver->item()) {
$urlCurrent = $uriWithParam;
if (isset($resolvedRoute['url'])) {
$urlCurrent = $resolvedRoute['url'];
}
// build real url
// last values of label overwrites previous
$resolvedRoute = [
'locale' => $resolver->locale($item),
'label' => $resolver->label($item),
'url' => str_replace('{'. $parameter . '}', $resolver->segment($item), $urlCurrent)
];
}
}
else {
throw new \Exception("Resolver has to implement of 'Crumby\RouteResolver\Contracts\ParamResolver', " . get_class($resolver) . " given.");
}
}
}
/**
* fix trailng slash
*/
if ($trailingSlash && isset($resolvedRoute['url'])) {
$resolvedRoute['url'] = '/' . ltrim($resolvedRoute['url'], '/');
}
return empty($resolvedRoute) ? false : $resolvedRoute;
} | php | public function resolveRouteItem($uriWithParam = null, $resolvers = null, $trailingSlash = false) {
if (empty($uriWithParam)) {
$uriWithParam = \Route::getCurrentRoute()->uri();
}
if (empty($resolvers)) {
$resolvers = \RouteResolver::getFromRequest($uriWithParam);
}
$resolvedRoute = [];
if (!empty($resolvers)) {
foreach ($resolvers as $parameter => $resolver) {
if ($resolver instanceof ParamResolver) {
if ($item = $resolver->item()) {
$urlCurrent = $uriWithParam;
if (isset($resolvedRoute['url'])) {
$urlCurrent = $resolvedRoute['url'];
}
// build real url
// last values of label overwrites previous
$resolvedRoute = [
'locale' => $resolver->locale($item),
'label' => $resolver->label($item),
'url' => str_replace('{'. $parameter . '}', $resolver->segment($item), $urlCurrent)
];
}
}
else {
throw new \Exception("Resolver has to implement of 'Crumby\RouteResolver\Contracts\ParamResolver', " . get_class($resolver) . " given.");
}
}
}
/**
* fix trailng slash
*/
if ($trailingSlash && isset($resolvedRoute['url'])) {
$resolvedRoute['url'] = '/' . ltrim($resolvedRoute['url'], '/');
}
return empty($resolvedRoute) ? false : $resolvedRoute;
} | [
"public",
"function",
"resolveRouteItem",
"(",
"$",
"uriWithParam",
"=",
"null",
",",
"$",
"resolvers",
"=",
"null",
",",
"$",
"trailingSlash",
"=",
"false",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"uriWithParam",
")",
")",
"{",
"$",
"uriWithParam",
"=",
"\\",
"Route",
"::",
"getCurrentRoute",
"(",
")",
"->",
"uri",
"(",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"resolvers",
")",
")",
"{",
"$",
"resolvers",
"=",
"\\",
"RouteResolver",
"::",
"getFromRequest",
"(",
"$",
"uriWithParam",
")",
";",
"}",
"$",
"resolvedRoute",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"resolvers",
")",
")",
"{",
"foreach",
"(",
"$",
"resolvers",
"as",
"$",
"parameter",
"=>",
"$",
"resolver",
")",
"{",
"if",
"(",
"$",
"resolver",
"instanceof",
"ParamResolver",
")",
"{",
"if",
"(",
"$",
"item",
"=",
"$",
"resolver",
"->",
"item",
"(",
")",
")",
"{",
"$",
"urlCurrent",
"=",
"$",
"uriWithParam",
";",
"if",
"(",
"isset",
"(",
"$",
"resolvedRoute",
"[",
"'url'",
"]",
")",
")",
"{",
"$",
"urlCurrent",
"=",
"$",
"resolvedRoute",
"[",
"'url'",
"]",
";",
"}",
"// build real url",
"// last values of label overwrites previous",
"$",
"resolvedRoute",
"=",
"[",
"'locale'",
"=>",
"$",
"resolver",
"->",
"locale",
"(",
"$",
"item",
")",
",",
"'label'",
"=>",
"$",
"resolver",
"->",
"label",
"(",
"$",
"item",
")",
",",
"'url'",
"=>",
"str_replace",
"(",
"'{'",
".",
"$",
"parameter",
".",
"'}'",
",",
"$",
"resolver",
"->",
"segment",
"(",
"$",
"item",
")",
",",
"$",
"urlCurrent",
")",
"]",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"\"Resolver has to implement of 'Crumby\\RouteResolver\\Contracts\\ParamResolver', \"",
".",
"get_class",
"(",
"$",
"resolver",
")",
".",
"\" given.\"",
")",
";",
"}",
"}",
"}",
"/**\n * fix trailng slash\n */",
"if",
"(",
"$",
"trailingSlash",
"&&",
"isset",
"(",
"$",
"resolvedRoute",
"[",
"'url'",
"]",
")",
")",
"{",
"$",
"resolvedRoute",
"[",
"'url'",
"]",
"=",
"'/'",
".",
"ltrim",
"(",
"$",
"resolvedRoute",
"[",
"'url'",
"]",
",",
"'/'",
")",
";",
"}",
"return",
"empty",
"(",
"$",
"resolvedRoute",
")",
"?",
"false",
":",
"$",
"resolvedRoute",
";",
"}"
] | Resolves route Locale, Label, Url
@param string $uriWithParam
@param [] $resolvers Assosiative array, where key is dynamic parameter name, value is Crumby\RouteResolver\ParamResolver
@param boolean $trailingSlash If url starts from trailing slash
@return [] | false :
[ 'locale' => string,
'label' => string,
'url' => string
];
@throws \Exception | [
"Resolves",
"route",
"Locale",
"Label",
"Url"
] | 26550d0046b0b5bbf461c4e817ce46168c455525 | https://github.com/avassilenko/route-resolver/blob/26550d0046b0b5bbf461c4e817ce46168c455525/src/RouteResolver.php#L137-L176 |
7,940 | wasabi-cms/cms | src/BaseCollection.php | BaseCollection.register | public static function register($id, $options)
{
$id = (string)$id;
if (self::exists($id)) {
user_error(Text::insert('A collection with id ":id" is already registered.', ['id' => $id]));
return;
}
$defaults = [
'model' => 'Plugin.Model',
'displayName' => 'Translated Name'
];
$options = array_merge($defaults, $options);
self::_instance()->_items[$id] = $options;
} | php | public static function register($id, $options)
{
$id = (string)$id;
if (self::exists($id)) {
user_error(Text::insert('A collection with id ":id" is already registered.', ['id' => $id]));
return;
}
$defaults = [
'model' => 'Plugin.Model',
'displayName' => 'Translated Name'
];
$options = array_merge($defaults, $options);
self::_instance()->_items[$id] = $options;
} | [
"public",
"static",
"function",
"register",
"(",
"$",
"id",
",",
"$",
"options",
")",
"{",
"$",
"id",
"=",
"(",
"string",
")",
"$",
"id",
";",
"if",
"(",
"self",
"::",
"exists",
"(",
"$",
"id",
")",
")",
"{",
"user_error",
"(",
"Text",
"::",
"insert",
"(",
"'A collection with id \":id\" is already registered.'",
",",
"[",
"'id'",
"=>",
"$",
"id",
"]",
")",
")",
";",
"return",
";",
"}",
"$",
"defaults",
"=",
"[",
"'model'",
"=>",
"'Plugin.Model'",
",",
"'displayName'",
"=>",
"'Translated Name'",
"]",
";",
"$",
"options",
"=",
"array_merge",
"(",
"$",
"defaults",
",",
"$",
"options",
")",
";",
"self",
"::",
"_instance",
"(",
")",
"->",
"_items",
"[",
"$",
"id",
"]",
"=",
"$",
"options",
";",
"}"
] | Register a new collection.
@param string $id The collection identifier.
@param array $options The collection options. | [
"Register",
"a",
"new",
"collection",
"."
] | 2787b6422ea1d719cf49951b3253fd0ac31d22ca | https://github.com/wasabi-cms/cms/blob/2787b6422ea1d719cf49951b3253fd0ac31d22ca/src/BaseCollection.php#L18-L31 |
7,941 | wasabi-cms/cms | src/BaseCollection.php | BaseCollection.getForSelect | public static function getForSelect()
{
$instance = self::_instance();
return array_combine(array_keys($instance->_items), Hash::extract($instance->_items, '{s}.displayName'));
} | php | public static function getForSelect()
{
$instance = self::_instance();
return array_combine(array_keys($instance->_items), Hash::extract($instance->_items, '{s}.displayName'));
} | [
"public",
"static",
"function",
"getForSelect",
"(",
")",
"{",
"$",
"instance",
"=",
"self",
"::",
"_instance",
"(",
")",
";",
"return",
"array_combine",
"(",
"array_keys",
"(",
"$",
"instance",
"->",
"_items",
")",
",",
"Hash",
"::",
"extract",
"(",
"$",
"instance",
"->",
"_items",
",",
"'{s}.displayName'",
")",
")",
";",
"}"
] | Get all collections for a select.
@return array | [
"Get",
"all",
"collections",
"for",
"a",
"select",
"."
] | 2787b6422ea1d719cf49951b3253fd0ac31d22ca | https://github.com/wasabi-cms/cms/blob/2787b6422ea1d719cf49951b3253fd0ac31d22ca/src/BaseCollection.php#L38-L42 |
7,942 | wasabi-cms/cms | src/BaseCollection.php | BaseCollection.getDisplayName | public static function getDisplayName($id)
{
$instance = self::_instance();
if (!isset($instance->_items[$id])) {
return false;
}
return $instance->_items[$id]['displayName'];
} | php | public static function getDisplayName($id)
{
$instance = self::_instance();
if (!isset($instance->_items[$id])) {
return false;
}
return $instance->_items[$id]['displayName'];
} | [
"public",
"static",
"function",
"getDisplayName",
"(",
"$",
"id",
")",
"{",
"$",
"instance",
"=",
"self",
"::",
"_instance",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"instance",
"->",
"_items",
"[",
"$",
"id",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"instance",
"->",
"_items",
"[",
"$",
"id",
"]",
"[",
"'displayName'",
"]",
";",
"}"
] | Get the display name for a specific item.
@param string $id
@return bool | [
"Get",
"the",
"display",
"name",
"for",
"a",
"specific",
"item",
"."
] | 2787b6422ea1d719cf49951b3253fd0ac31d22ca | https://github.com/wasabi-cms/cms/blob/2787b6422ea1d719cf49951b3253fd0ac31d22ca/src/BaseCollection.php#L50-L58 |
7,943 | elastification/php-client | src/Serializer/JmsSerializer.php | JmsSerializer.serialize | public function serialize($data, array $params = array())
{
return $this->jms->serialize(
$data,
self::SERIALIZER_FORMAT,
$this->determineContext($this->jmsSerializeContext, $params)
);
} | php | public function serialize($data, array $params = array())
{
return $this->jms->serialize(
$data,
self::SERIALIZER_FORMAT,
$this->determineContext($this->jmsSerializeContext, $params)
);
} | [
"public",
"function",
"serialize",
"(",
"$",
"data",
",",
"array",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"jms",
"->",
"serialize",
"(",
"$",
"data",
",",
"self",
"::",
"SERIALIZER_FORMAT",
",",
"$",
"this",
"->",
"determineContext",
"(",
"$",
"this",
"->",
"jmsSerializeContext",
",",
"$",
"params",
")",
")",
";",
"}"
] | Serializes given data to string
@param mixed $data
@param array $params
@return string | [
"Serializes",
"given",
"data",
"to",
"string"
] | eb01be0905dd1eba7baa62f84492d82e4b3cae61 | https://github.com/elastification/php-client/blob/eb01be0905dd1eba7baa62f84492d82e4b3cae61/src/Serializer/JmsSerializer.php#L108-L115 |
7,944 | elastification/php-client | src/Serializer/JmsSerializer.php | JmsSerializer.deserialize | public function deserialize($data, array $params = array())
{
$sourceClass = $this->getSourceClassFromMapping($params);
$this->handler->setSourceDeSerClass($sourceClass);
return new NativeObjectGateway(
$this->jms->deserialize(
$data,
$this->deserializerClass,
self::SERIALIZER_FORMAT,
$this->determineContext($this->jmsDeserializeContext, $params)
)
);
} | php | public function deserialize($data, array $params = array())
{
$sourceClass = $this->getSourceClassFromMapping($params);
$this->handler->setSourceDeSerClass($sourceClass);
return new NativeObjectGateway(
$this->jms->deserialize(
$data,
$this->deserializerClass,
self::SERIALIZER_FORMAT,
$this->determineContext($this->jmsDeserializeContext, $params)
)
);
} | [
"public",
"function",
"deserialize",
"(",
"$",
"data",
",",
"array",
"$",
"params",
"=",
"array",
"(",
")",
")",
"{",
"$",
"sourceClass",
"=",
"$",
"this",
"->",
"getSourceClassFromMapping",
"(",
"$",
"params",
")",
";",
"$",
"this",
"->",
"handler",
"->",
"setSourceDeSerClass",
"(",
"$",
"sourceClass",
")",
";",
"return",
"new",
"NativeObjectGateway",
"(",
"$",
"this",
"->",
"jms",
"->",
"deserialize",
"(",
"$",
"data",
",",
"$",
"this",
"->",
"deserializerClass",
",",
"self",
"::",
"SERIALIZER_FORMAT",
",",
"$",
"this",
"->",
"determineContext",
"(",
"$",
"this",
"->",
"jmsDeserializeContext",
",",
"$",
"params",
")",
")",
")",
";",
"}"
] | Deserializes given data to array or object
@param string $data
@param array $params
@return GatewayInterface | [
"Deserializes",
"given",
"data",
"to",
"array",
"or",
"object"
] | eb01be0905dd1eba7baa62f84492d82e4b3cae61 | https://github.com/elastification/php-client/blob/eb01be0905dd1eba7baa62f84492d82e4b3cae61/src/Serializer/JmsSerializer.php#L125-L138 |
7,945 | elastification/php-client | src/Serializer/JmsSerializer.php | JmsSerializer.getSourceClassFromMapping | private function getSourceClassFromMapping(array $params)
{
$index = $params['index'];
$type = $params['type'];
if (!isset($this->indexTypeClassMap[$index])) {
throw new DeserializationFailureException('Cannot find index in source class map: ' . $index);
}
if (!isset($this->indexTypeClassMap[$index][$type])) {
throw new DeserializationFailureException(
'Cannot find type in source class map: ' . $type . ' in index ' . $index
);
}
return $this->indexTypeClassMap[$index][$type];
} | php | private function getSourceClassFromMapping(array $params)
{
$index = $params['index'];
$type = $params['type'];
if (!isset($this->indexTypeClassMap[$index])) {
throw new DeserializationFailureException('Cannot find index in source class map: ' . $index);
}
if (!isset($this->indexTypeClassMap[$index][$type])) {
throw new DeserializationFailureException(
'Cannot find type in source class map: ' . $type . ' in index ' . $index
);
}
return $this->indexTypeClassMap[$index][$type];
} | [
"private",
"function",
"getSourceClassFromMapping",
"(",
"array",
"$",
"params",
")",
"{",
"$",
"index",
"=",
"$",
"params",
"[",
"'index'",
"]",
";",
"$",
"type",
"=",
"$",
"params",
"[",
"'type'",
"]",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"indexTypeClassMap",
"[",
"$",
"index",
"]",
")",
")",
"{",
"throw",
"new",
"DeserializationFailureException",
"(",
"'Cannot find index in source class map: '",
".",
"$",
"index",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"indexTypeClassMap",
"[",
"$",
"index",
"]",
"[",
"$",
"type",
"]",
")",
")",
"{",
"throw",
"new",
"DeserializationFailureException",
"(",
"'Cannot find type in source class map: '",
".",
"$",
"type",
".",
"' in index '",
".",
"$",
"index",
")",
";",
"}",
"return",
"$",
"this",
"->",
"indexTypeClassMap",
"[",
"$",
"index",
"]",
"[",
"$",
"type",
"]",
";",
"}"
] | gets the source class.
@param array $params
@return string
@author Daniel Wendlandt | [
"gets",
"the",
"source",
"class",
"."
] | eb01be0905dd1eba7baa62f84492d82e4b3cae61 | https://github.com/elastification/php-client/blob/eb01be0905dd1eba7baa62f84492d82e4b3cae61/src/Serializer/JmsSerializer.php#L148-L163 |
7,946 | tekton-php/support | src/Manifest/YamlFormat.php | YamlFormat.decode | public function decode($data)
{
try {
return Yaml::parse($data);
}
catch (ParseException $e) {
printf("Unable to parse the YAML string: %s", $e->getMessage());
return [];
}
} | php | public function decode($data)
{
try {
return Yaml::parse($data);
}
catch (ParseException $e) {
printf("Unable to parse the YAML string: %s", $e->getMessage());
return [];
}
} | [
"public",
"function",
"decode",
"(",
"$",
"data",
")",
"{",
"try",
"{",
"return",
"Yaml",
"::",
"parse",
"(",
"$",
"data",
")",
";",
"}",
"catch",
"(",
"ParseException",
"$",
"e",
")",
"{",
"printf",
"(",
"\"Unable to parse the YAML string: %s\"",
",",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"return",
"[",
"]",
";",
"}",
"}"
] | Decodes the data that was loaded with read
@param mixed $data The data to decode
@return mixed The decoded data | [
"Decodes",
"the",
"data",
"that",
"was",
"loaded",
"with",
"read"
] | 615b9f19ab66ebc2aa49aaccff12b1fc3b9266b5 | https://github.com/tekton-php/support/blob/615b9f19ab66ebc2aa49aaccff12b1fc3b9266b5/src/Manifest/YamlFormat.php#L26-L35 |
7,947 | tenside/core | src/Task/AbstractCliSpawningTask.php | AbstractCliSpawningTask.runProcess | protected function runProcess(Process $process)
{
$ioHandler = $this->getIO();
$process->run(
function ($pipe, $content) use ($ioHandler) {
if (Process::ERR === $pipe) {
$ioHandler->writeError($content, false);
// @codingStandardsIgnoreStart
return;
// @codingStandardsIgnoreEnd
}
$ioHandler->write($content, false);
}
);
if (0 !== $process->getExitCode()) {
throw new ProcessFailedException($process);
}
} | php | protected function runProcess(Process $process)
{
$ioHandler = $this->getIO();
$process->run(
function ($pipe, $content) use ($ioHandler) {
if (Process::ERR === $pipe) {
$ioHandler->writeError($content, false);
// @codingStandardsIgnoreStart
return;
// @codingStandardsIgnoreEnd
}
$ioHandler->write($content, false);
}
);
if (0 !== $process->getExitCode()) {
throw new ProcessFailedException($process);
}
} | [
"protected",
"function",
"runProcess",
"(",
"Process",
"$",
"process",
")",
"{",
"$",
"ioHandler",
"=",
"$",
"this",
"->",
"getIO",
"(",
")",
";",
"$",
"process",
"->",
"run",
"(",
"function",
"(",
"$",
"pipe",
",",
"$",
"content",
")",
"use",
"(",
"$",
"ioHandler",
")",
"{",
"if",
"(",
"Process",
"::",
"ERR",
"===",
"$",
"pipe",
")",
"{",
"$",
"ioHandler",
"->",
"writeError",
"(",
"$",
"content",
",",
"false",
")",
";",
"// @codingStandardsIgnoreStart",
"return",
";",
"// @codingStandardsIgnoreEnd",
"}",
"$",
"ioHandler",
"->",
"write",
"(",
"$",
"content",
",",
"false",
")",
";",
"}",
")",
";",
"if",
"(",
"0",
"!==",
"$",
"process",
"->",
"getExitCode",
"(",
")",
")",
"{",
"throw",
"new",
"ProcessFailedException",
"(",
"$",
"process",
")",
";",
"}",
"}"
] | Run a process and throw exception if it failed.
@param Process $process The process to run.
@return void
@throws ProcessFailedException When the process returned a non zero result. | [
"Run",
"a",
"process",
"and",
"throw",
"exception",
"if",
"it",
"failed",
"."
] | 56422fa8cdecf03cb431bb6654c2942ade39bf7b | https://github.com/tenside/core/blob/56422fa8cdecf03cb431bb6654c2942ade39bf7b/src/Task/AbstractCliSpawningTask.php#L40-L58 |
7,948 | JamesRezo/webhelper-parser | src/Server/Server.php | Server.isValid | public function isValid()
{
$valid = $this->prefix != '';
$valid = $valid && $this->startMultiLine != '';
$valid = $valid && $this->endMultiLine != '';
$valid = $valid && $this->simpleDirective != '';
return $valid;
} | php | public function isValid()
{
$valid = $this->prefix != '';
$valid = $valid && $this->startMultiLine != '';
$valid = $valid && $this->endMultiLine != '';
$valid = $valid && $this->simpleDirective != '';
return $valid;
} | [
"public",
"function",
"isValid",
"(",
")",
"{",
"$",
"valid",
"=",
"$",
"this",
"->",
"prefix",
"!=",
"''",
";",
"$",
"valid",
"=",
"$",
"valid",
"&&",
"$",
"this",
"->",
"startMultiLine",
"!=",
"''",
";",
"$",
"valid",
"=",
"$",
"valid",
"&&",
"$",
"this",
"->",
"endMultiLine",
"!=",
"''",
";",
"$",
"valid",
"=",
"$",
"valid",
"&&",
"$",
"this",
"->",
"simpleDirective",
"!=",
"''",
";",
"return",
"$",
"valid",
";",
"}"
] | Confirms if the server instance has valid parameters.
@return bool true if all parameters are initialized, false otherwise | [
"Confirms",
"if",
"the",
"server",
"instance",
"has",
"valid",
"parameters",
"."
] | 0b39e7abe8f35afbeacdd6681fa9d0767888c646 | https://github.com/JamesRezo/webhelper-parser/blob/0b39e7abe8f35afbeacdd6681fa9d0767888c646/src/Server/Server.php#L137-L145 |
7,949 | JamesRezo/webhelper-parser | src/Server/Server.php | Server.setPrefix | public function setPrefix($prefix)
{
if (!$this->checker->setString($prefix)->getString()) {
throw ServerException::forInvalidPrefix($prefix, 'The path is expected to be a string. Got: %s');
}
if (!$this->checker->isValidAbsolutePath()) {
throw ServerException::forInvalidPrefix(
$prefix,
'The path is expected to be absolute and an existing directory. Got: %s'
);
}
$this->prefix = $prefix;
return $this;
} | php | public function setPrefix($prefix)
{
if (!$this->checker->setString($prefix)->getString()) {
throw ServerException::forInvalidPrefix($prefix, 'The path is expected to be a string. Got: %s');
}
if (!$this->checker->isValidAbsolutePath()) {
throw ServerException::forInvalidPrefix(
$prefix,
'The path is expected to be absolute and an existing directory. Got: %s'
);
}
$this->prefix = $prefix;
return $this;
} | [
"public",
"function",
"setPrefix",
"(",
"$",
"prefix",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"checker",
"->",
"setString",
"(",
"$",
"prefix",
")",
"->",
"getString",
"(",
")",
")",
"{",
"throw",
"ServerException",
"::",
"forInvalidPrefix",
"(",
"$",
"prefix",
",",
"'The path is expected to be a string. Got: %s'",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"checker",
"->",
"isValidAbsolutePath",
"(",
")",
")",
"{",
"throw",
"ServerException",
"::",
"forInvalidPrefix",
"(",
"$",
"prefix",
",",
"'The path is expected to be absolute and an existing directory. Got: %s'",
")",
";",
"}",
"$",
"this",
"->",
"prefix",
"=",
"$",
"prefix",
";",
"return",
"$",
"this",
";",
"}"
] | Sets the prefix of a server instance.
@param string $prefix the filesystem path where the web server is installed
@throws ServerException if the prefix is invalid | [
"Sets",
"the",
"prefix",
"of",
"a",
"server",
"instance",
"."
] | 0b39e7abe8f35afbeacdd6681fa9d0767888c646 | https://github.com/JamesRezo/webhelper-parser/blob/0b39e7abe8f35afbeacdd6681fa9d0767888c646/src/Server/Server.php#L165-L181 |
7,950 | JamesRezo/webhelper-parser | src/Server/Server.php | Server.setRegexDirective | private function setRegexDirective($directive, $message1, $message2)
{
if (!$this->checker->setString($directive)->getString()) {
throw ServerException::forInvalidMatcher(
$directive,
$message1
);
}
if (!$this->checker->isValidRegex()) {
throw ServerException::forInvalidMatcher(
$directive,
$message2
);
}
return $directive;
} | php | private function setRegexDirective($directive, $message1, $message2)
{
if (!$this->checker->setString($directive)->getString()) {
throw ServerException::forInvalidMatcher(
$directive,
$message1
);
}
if (!$this->checker->isValidRegex()) {
throw ServerException::forInvalidMatcher(
$directive,
$message2
);
}
return $directive;
} | [
"private",
"function",
"setRegexDirective",
"(",
"$",
"directive",
",",
"$",
"message1",
",",
"$",
"message2",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"checker",
"->",
"setString",
"(",
"$",
"directive",
")",
"->",
"getString",
"(",
")",
")",
"{",
"throw",
"ServerException",
"::",
"forInvalidMatcher",
"(",
"$",
"directive",
",",
"$",
"message1",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"checker",
"->",
"isValidRegex",
"(",
")",
")",
"{",
"throw",
"ServerException",
"::",
"forInvalidMatcher",
"(",
"$",
"directive",
",",
"$",
"message2",
")",
";",
"}",
"return",
"$",
"directive",
";",
"}"
] | Sets the regular expression directive.
@param string $directive the directive string
@param string $message1 message exception if the matcher is not a string
@param string $message2 message exception if the matcher is not a valid regex
@throws ServerException if the directive matcher is invalid
@return string the regular expression directive | [
"Sets",
"the",
"regular",
"expression",
"directive",
"."
] | 0b39e7abe8f35afbeacdd6681fa9d0767888c646 | https://github.com/JamesRezo/webhelper-parser/blob/0b39e7abe8f35afbeacdd6681fa9d0767888c646/src/Server/Server.php#L278-L295 |
7,951 | JamesRezo/webhelper-parser | src/Server/Server.php | Server.isValidDirective | private function isValidDirective($directive, $message1, $message2)
{
if (!$this->checker->setString($directive)->getString()) {
throw ServerException::forInvalidMatcher(
$directive,
$message1
);
}
if (!$this->checker->hasKeyAndValueSubPattern()) {
throw ServerException::forInvalidMatcher(
$directive,
$message2
);
}
return true;
} | php | private function isValidDirective($directive, $message1, $message2)
{
if (!$this->checker->setString($directive)->getString()) {
throw ServerException::forInvalidMatcher(
$directive,
$message1
);
}
if (!$this->checker->hasKeyAndValueSubPattern()) {
throw ServerException::forInvalidMatcher(
$directive,
$message2
);
}
return true;
} | [
"private",
"function",
"isValidDirective",
"(",
"$",
"directive",
",",
"$",
"message1",
",",
"$",
"message2",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"checker",
"->",
"setString",
"(",
"$",
"directive",
")",
"->",
"getString",
"(",
")",
")",
"{",
"throw",
"ServerException",
"::",
"forInvalidMatcher",
"(",
"$",
"directive",
",",
"$",
"message1",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"checker",
"->",
"hasKeyAndValueSubPattern",
"(",
")",
")",
"{",
"throw",
"ServerException",
"::",
"forInvalidMatcher",
"(",
"$",
"directive",
",",
"$",
"message2",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Confirms if a directive matcher is a valid regex.
@param string $directive the directive matcher to check
@param string $message1 message exception if the matcher is not a string
@param string $message2 message exception if the matcher is not a valid regex
@throws ServerException if the directive matcher is invalid
@return bool true if the directive matcher is valid | [
"Confirms",
"if",
"a",
"directive",
"matcher",
"is",
"a",
"valid",
"regex",
"."
] | 0b39e7abe8f35afbeacdd6681fa9d0767888c646 | https://github.com/JamesRezo/webhelper-parser/blob/0b39e7abe8f35afbeacdd6681fa9d0767888c646/src/Server/Server.php#L308-L325 |
7,952 | prestaconcept/PrestaCMSMediaBundle | Block/MediaBlockService.php | MediaBlockService.getFormatChoices | protected function getFormatChoices($context = 'prestacms')
{
$formatChoices = array();
$formats = $this->getMediaPool()->getFormatNamesByContext($context);
foreach ($formats as $code => $format) {
$formatChoices[$code] = $this->trans('media.format.' . $code);
}
return $formatChoices;
} | php | protected function getFormatChoices($context = 'prestacms')
{
$formatChoices = array();
$formats = $this->getMediaPool()->getFormatNamesByContext($context);
foreach ($formats as $code => $format) {
$formatChoices[$code] = $this->trans('media.format.' . $code);
}
return $formatChoices;
} | [
"protected",
"function",
"getFormatChoices",
"(",
"$",
"context",
"=",
"'prestacms'",
")",
"{",
"$",
"formatChoices",
"=",
"array",
"(",
")",
";",
"$",
"formats",
"=",
"$",
"this",
"->",
"getMediaPool",
"(",
")",
"->",
"getFormatNamesByContext",
"(",
"$",
"context",
")",
";",
"foreach",
"(",
"$",
"formats",
"as",
"$",
"code",
"=>",
"$",
"format",
")",
"{",
"$",
"formatChoices",
"[",
"$",
"code",
"]",
"=",
"$",
"this",
"->",
"trans",
"(",
"'media.format.'",
".",
"$",
"code",
")",
";",
"}",
"return",
"$",
"formatChoices",
";",
"}"
] | Returns available formats
@param string $context
@return array | [
"Returns",
"available",
"formats"
] | e442d2bae2d1624f7ff234d003f82b5e1c6c4555 | https://github.com/prestaconcept/PrestaCMSMediaBundle/blob/e442d2bae2d1624f7ff234d003f82b5e1c6c4555/Block/MediaBlockService.php#L54-L65 |
7,953 | diarmuidie/ImageRack-Kernel | src/Server.php | Server.run | public function run()
{
// Catch all errors and convert to exceptions
set_error_handler(array('\Diarmuidie\ImageRack\Server', 'handleErrors'));
// Catch all uncaught exceptions
set_exception_handler(array($this, 'error'));
// Send a not found response if the request is not valid
if (!$this->validRequest()) {
$this->notFound();
return $this->response;
}
// First try and load the image from the cache
$cachePath = $this->getCachePath();
if ($this->serveFromCache($cachePath)) {
return $this->response;
}
// Secondly try load the source image
$sourcePath = $this->getSourcePath();
if ($this->serveFromSource($sourcePath)) {
return $this->response;
}
// Finally default to returning a not found response
$this->notFound();
return $this->response;
} | php | public function run()
{
// Catch all errors and convert to exceptions
set_error_handler(array('\Diarmuidie\ImageRack\Server', 'handleErrors'));
// Catch all uncaught exceptions
set_exception_handler(array($this, 'error'));
// Send a not found response if the request is not valid
if (!$this->validRequest()) {
$this->notFound();
return $this->response;
}
// First try and load the image from the cache
$cachePath = $this->getCachePath();
if ($this->serveFromCache($cachePath)) {
return $this->response;
}
// Secondly try load the source image
$sourcePath = $this->getSourcePath();
if ($this->serveFromSource($sourcePath)) {
return $this->response;
}
// Finally default to returning a not found response
$this->notFound();
return $this->response;
} | [
"public",
"function",
"run",
"(",
")",
"{",
"// Catch all errors and convert to exceptions",
"set_error_handler",
"(",
"array",
"(",
"'\\Diarmuidie\\ImageRack\\Server'",
",",
"'handleErrors'",
")",
")",
";",
"// Catch all uncaught exceptions",
"set_exception_handler",
"(",
"array",
"(",
"$",
"this",
",",
"'error'",
")",
")",
";",
"// Send a not found response if the request is not valid",
"if",
"(",
"!",
"$",
"this",
"->",
"validRequest",
"(",
")",
")",
"{",
"$",
"this",
"->",
"notFound",
"(",
")",
";",
"return",
"$",
"this",
"->",
"response",
";",
"}",
"// First try and load the image from the cache",
"$",
"cachePath",
"=",
"$",
"this",
"->",
"getCachePath",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"serveFromCache",
"(",
"$",
"cachePath",
")",
")",
"{",
"return",
"$",
"this",
"->",
"response",
";",
"}",
"// Secondly try load the source image",
"$",
"sourcePath",
"=",
"$",
"this",
"->",
"getSourcePath",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"serveFromSource",
"(",
"$",
"sourcePath",
")",
")",
"{",
"return",
"$",
"this",
"->",
"response",
";",
"}",
"// Finally default to returning a not found response",
"$",
"this",
"->",
"notFound",
"(",
")",
";",
"return",
"$",
"this",
"->",
"response",
";",
"}"
] | Run the image Server on the curent request.
@return Response The response object | [
"Run",
"the",
"image",
"Server",
"on",
"the",
"curent",
"request",
"."
] | 0bd14bb561ba0486f60a6d3058587497ae99ea97 | https://github.com/diarmuidie/ImageRack-Kernel/blob/0bd14bb561ba0486f60a6d3058587497ae99ea97/src/Server.php#L171-L202 |
7,954 | diarmuidie/ImageRack-Kernel | src/Server.php | Server.serveFromCache | private function serveFromCache($path)
{
//try and load the image from the cache
if ($this->cache->has($path)) {
$file = $this->cache->get($path);
$lastModified = new \DateTime();
$lastModified->setTimestamp($file->getTimestamp());
$this->setHttpCacheHeaders(
$lastModified,
md5($this->getCachePath().$lastModified->getTimestamp()),
$this->maxAge
);
// Respond with 304 not modified
if ($this->response->isNotModified($this->request)) {
return true;
}
$this->response = new StreamedResponse();
// Set the headers
$this->response->headers->set('Content-Type', $file->getMimetype());
$this->response->headers->set('Content-Length', $file->getSize());
$this->setHttpCacheHeaders(
$lastModified,
md5($this->getCachePath().$lastModified->getTimestamp()),
$this->maxAge
);
$this->response->setCallback(function () use ($file) {
fpassthru($file->readStream());
});
return true;
}
return false;
} | php | private function serveFromCache($path)
{
//try and load the image from the cache
if ($this->cache->has($path)) {
$file = $this->cache->get($path);
$lastModified = new \DateTime();
$lastModified->setTimestamp($file->getTimestamp());
$this->setHttpCacheHeaders(
$lastModified,
md5($this->getCachePath().$lastModified->getTimestamp()),
$this->maxAge
);
// Respond with 304 not modified
if ($this->response->isNotModified($this->request)) {
return true;
}
$this->response = new StreamedResponse();
// Set the headers
$this->response->headers->set('Content-Type', $file->getMimetype());
$this->response->headers->set('Content-Length', $file->getSize());
$this->setHttpCacheHeaders(
$lastModified,
md5($this->getCachePath().$lastModified->getTimestamp()),
$this->maxAge
);
$this->response->setCallback(function () use ($file) {
fpassthru($file->readStream());
});
return true;
}
return false;
} | [
"private",
"function",
"serveFromCache",
"(",
"$",
"path",
")",
"{",
"//try and load the image from the cache",
"if",
"(",
"$",
"this",
"->",
"cache",
"->",
"has",
"(",
"$",
"path",
")",
")",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"cache",
"->",
"get",
"(",
"$",
"path",
")",
";",
"$",
"lastModified",
"=",
"new",
"\\",
"DateTime",
"(",
")",
";",
"$",
"lastModified",
"->",
"setTimestamp",
"(",
"$",
"file",
"->",
"getTimestamp",
"(",
")",
")",
";",
"$",
"this",
"->",
"setHttpCacheHeaders",
"(",
"$",
"lastModified",
",",
"md5",
"(",
"$",
"this",
"->",
"getCachePath",
"(",
")",
".",
"$",
"lastModified",
"->",
"getTimestamp",
"(",
")",
")",
",",
"$",
"this",
"->",
"maxAge",
")",
";",
"// Respond with 304 not modified",
"if",
"(",
"$",
"this",
"->",
"response",
"->",
"isNotModified",
"(",
"$",
"this",
"->",
"request",
")",
")",
"{",
"return",
"true",
";",
"}",
"$",
"this",
"->",
"response",
"=",
"new",
"StreamedResponse",
"(",
")",
";",
"// Set the headers",
"$",
"this",
"->",
"response",
"->",
"headers",
"->",
"set",
"(",
"'Content-Type'",
",",
"$",
"file",
"->",
"getMimetype",
"(",
")",
")",
";",
"$",
"this",
"->",
"response",
"->",
"headers",
"->",
"set",
"(",
"'Content-Length'",
",",
"$",
"file",
"->",
"getSize",
"(",
")",
")",
";",
"$",
"this",
"->",
"setHttpCacheHeaders",
"(",
"$",
"lastModified",
",",
"md5",
"(",
"$",
"this",
"->",
"getCachePath",
"(",
")",
".",
"$",
"lastModified",
"->",
"getTimestamp",
"(",
")",
")",
",",
"$",
"this",
"->",
"maxAge",
")",
";",
"$",
"this",
"->",
"response",
"->",
"setCallback",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"file",
")",
"{",
"fpassthru",
"(",
"$",
"file",
"->",
"readStream",
"(",
")",
")",
";",
"}",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Generate a response object for a cached image.
@param string $path Path to the cached image
@return bool | [
"Generate",
"a",
"response",
"object",
"for",
"a",
"cached",
"image",
"."
] | 0bd14bb561ba0486f60a6d3058587497ae99ea97 | https://github.com/diarmuidie/ImageRack-Kernel/blob/0bd14bb561ba0486f60a6d3058587497ae99ea97/src/Server.php#L231-L271 |
7,955 | diarmuidie/ImageRack-Kernel | src/Server.php | Server.serveFromSource | private function serveFromSource($path)
{
//try and load the image from the source
if ($this->source->has($path)) {
$file = $this->source->get($path);
// Get the template object
$template = $this->templates[$this->template]();
// Process the image
$image = $this->processImage(
$file,
$this->imageManager,
$template
);
// Set the headers
$this->response->headers->set('Content-Type', $image->mime);
$this->response->headers->set('Content-Length', strlen($image->encoded));
$lastModified = new \DateTime(); // now
$this->setHttpCacheHeaders(
$lastModified,
md5($this->getCachePath().$lastModified->getTimestamp()),
$this->maxAge
);
// Send the processed image in the response
$this->response->setContent($image->encoded);
// Setup a callback to write the processed image to the cache
// This will be called after the image has been sent to the browser
$this->cacheWrite = function (FilesystemInterface $cache, $path) use ($image) {
// use put() to write or update
$cache->put($path, $image->encoded);
};
return true;
}
return false;
} | php | private function serveFromSource($path)
{
//try and load the image from the source
if ($this->source->has($path)) {
$file = $this->source->get($path);
// Get the template object
$template = $this->templates[$this->template]();
// Process the image
$image = $this->processImage(
$file,
$this->imageManager,
$template
);
// Set the headers
$this->response->headers->set('Content-Type', $image->mime);
$this->response->headers->set('Content-Length', strlen($image->encoded));
$lastModified = new \DateTime(); // now
$this->setHttpCacheHeaders(
$lastModified,
md5($this->getCachePath().$lastModified->getTimestamp()),
$this->maxAge
);
// Send the processed image in the response
$this->response->setContent($image->encoded);
// Setup a callback to write the processed image to the cache
// This will be called after the image has been sent to the browser
$this->cacheWrite = function (FilesystemInterface $cache, $path) use ($image) {
// use put() to write or update
$cache->put($path, $image->encoded);
};
return true;
}
return false;
} | [
"private",
"function",
"serveFromSource",
"(",
"$",
"path",
")",
"{",
"//try and load the image from the source",
"if",
"(",
"$",
"this",
"->",
"source",
"->",
"has",
"(",
"$",
"path",
")",
")",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"source",
"->",
"get",
"(",
"$",
"path",
")",
";",
"// Get the template object",
"$",
"template",
"=",
"$",
"this",
"->",
"templates",
"[",
"$",
"this",
"->",
"template",
"]",
"(",
")",
";",
"// Process the image",
"$",
"image",
"=",
"$",
"this",
"->",
"processImage",
"(",
"$",
"file",
",",
"$",
"this",
"->",
"imageManager",
",",
"$",
"template",
")",
";",
"// Set the headers",
"$",
"this",
"->",
"response",
"->",
"headers",
"->",
"set",
"(",
"'Content-Type'",
",",
"$",
"image",
"->",
"mime",
")",
";",
"$",
"this",
"->",
"response",
"->",
"headers",
"->",
"set",
"(",
"'Content-Length'",
",",
"strlen",
"(",
"$",
"image",
"->",
"encoded",
")",
")",
";",
"$",
"lastModified",
"=",
"new",
"\\",
"DateTime",
"(",
")",
";",
"// now",
"$",
"this",
"->",
"setHttpCacheHeaders",
"(",
"$",
"lastModified",
",",
"md5",
"(",
"$",
"this",
"->",
"getCachePath",
"(",
")",
".",
"$",
"lastModified",
"->",
"getTimestamp",
"(",
")",
")",
",",
"$",
"this",
"->",
"maxAge",
")",
";",
"// Send the processed image in the response",
"$",
"this",
"->",
"response",
"->",
"setContent",
"(",
"$",
"image",
"->",
"encoded",
")",
";",
"// Setup a callback to write the processed image to the cache",
"// This will be called after the image has been sent to the browser",
"$",
"this",
"->",
"cacheWrite",
"=",
"function",
"(",
"FilesystemInterface",
"$",
"cache",
",",
"$",
"path",
")",
"use",
"(",
"$",
"image",
")",
"{",
"// use put() to write or update",
"$",
"cache",
"->",
"put",
"(",
"$",
"path",
",",
"$",
"image",
"->",
"encoded",
")",
";",
"}",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Process a source image and Generate a response object.
@param string $path Path to the source image
@return bool | [
"Process",
"a",
"source",
"image",
"and",
"Generate",
"a",
"response",
"object",
"."
] | 0bd14bb561ba0486f60a6d3058587497ae99ea97 | https://github.com/diarmuidie/ImageRack-Kernel/blob/0bd14bb561ba0486f60a6d3058587497ae99ea97/src/Server.php#L280-L322 |
7,956 | diarmuidie/ImageRack-Kernel | src/Server.php | Server.setHttpCacheHeaders | private function setHttpCacheHeaders(\DateTime $lastModified, $eTag, $maxAge)
{
$this->response->setMaxAge($maxAge);
$this->response->setPublic();
if ($this->maxAge === 0) {
$this->response->headers->set('Cache-Control', 'no-cache');
return;
}
$this->response->setLastModified($lastModified);
$this->response->setEtag($eTag);
} | php | private function setHttpCacheHeaders(\DateTime $lastModified, $eTag, $maxAge)
{
$this->response->setMaxAge($maxAge);
$this->response->setPublic();
if ($this->maxAge === 0) {
$this->response->headers->set('Cache-Control', 'no-cache');
return;
}
$this->response->setLastModified($lastModified);
$this->response->setEtag($eTag);
} | [
"private",
"function",
"setHttpCacheHeaders",
"(",
"\\",
"DateTime",
"$",
"lastModified",
",",
"$",
"eTag",
",",
"$",
"maxAge",
")",
"{",
"$",
"this",
"->",
"response",
"->",
"setMaxAge",
"(",
"$",
"maxAge",
")",
";",
"$",
"this",
"->",
"response",
"->",
"setPublic",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"maxAge",
"===",
"0",
")",
"{",
"$",
"this",
"->",
"response",
"->",
"headers",
"->",
"set",
"(",
"'Cache-Control'",
",",
"'no-cache'",
")",
";",
"return",
";",
"}",
"$",
"this",
"->",
"response",
"->",
"setLastModified",
"(",
"$",
"lastModified",
")",
";",
"$",
"this",
"->",
"response",
"->",
"setEtag",
"(",
"$",
"eTag",
")",
";",
"}"
] | Set the appripriate HTTP cache headers.
@param \DateTime $lastModified the last time the resource was modified
@param string $eTag unique eTag for the resource
@param int $maxAge the max age (in seconds) | [
"Set",
"the",
"appripriate",
"HTTP",
"cache",
"headers",
"."
] | 0bd14bb561ba0486f60a6d3058587497ae99ea97 | https://github.com/diarmuidie/ImageRack-Kernel/blob/0bd14bb561ba0486f60a6d3058587497ae99ea97/src/Server.php#L331-L344 |
7,957 | diarmuidie/ImageRack-Kernel | src/Server.php | Server.notFound | protected function notFound()
{
// Set the default not found response
$this->response->setContent('File not found');
$this->response->headers->set('content-type', 'text/html');
$this->response->setStatusCode(Response::HTTP_NOT_FOUND);
// Execute the user defined notFound callback
if (is_callable($this->notFound)) {
$this->response = call_user_func($this->notFound, $this->response);
}
} | php | protected function notFound()
{
// Set the default not found response
$this->response->setContent('File not found');
$this->response->headers->set('content-type', 'text/html');
$this->response->setStatusCode(Response::HTTP_NOT_FOUND);
// Execute the user defined notFound callback
if (is_callable($this->notFound)) {
$this->response = call_user_func($this->notFound, $this->response);
}
} | [
"protected",
"function",
"notFound",
"(",
")",
"{",
"// Set the default not found response",
"$",
"this",
"->",
"response",
"->",
"setContent",
"(",
"'File not found'",
")",
";",
"$",
"this",
"->",
"response",
"->",
"headers",
"->",
"set",
"(",
"'content-type'",
",",
"'text/html'",
")",
";",
"$",
"this",
"->",
"response",
"->",
"setStatusCode",
"(",
"Response",
"::",
"HTTP_NOT_FOUND",
")",
";",
"// Execute the user defined notFound callback",
"if",
"(",
"is_callable",
"(",
"$",
"this",
"->",
"notFound",
")",
")",
"{",
"$",
"this",
"->",
"response",
"=",
"call_user_func",
"(",
"$",
"this",
"->",
"notFound",
",",
"$",
"this",
"->",
"response",
")",
";",
"}",
"}"
] | Set a not found response. | [
"Set",
"a",
"not",
"found",
"response",
"."
] | 0bd14bb561ba0486f60a6d3058587497ae99ea97 | https://github.com/diarmuidie/ImageRack-Kernel/blob/0bd14bb561ba0486f60a6d3058587497ae99ea97/src/Server.php#L359-L370 |
7,958 | diarmuidie/ImageRack-Kernel | src/Server.php | Server.error | public function error($exception)
{
$response = new Response();
// Set the default error response
$response->setContent('There has been a problem serving this request.');
$response->headers->set('content-type', 'text/html');
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
// Execute the user defined error callback
if (is_callable($this->error)) {
$response = call_user_func($this->error, $response, $exception);
}
// Send the response
$response->send();
} | php | public function error($exception)
{
$response = new Response();
// Set the default error response
$response->setContent('There has been a problem serving this request.');
$response->headers->set('content-type', 'text/html');
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
// Execute the user defined error callback
if (is_callable($this->error)) {
$response = call_user_func($this->error, $response, $exception);
}
// Send the response
$response->send();
} | [
"public",
"function",
"error",
"(",
"$",
"exception",
")",
"{",
"$",
"response",
"=",
"new",
"Response",
"(",
")",
";",
"// Set the default error response",
"$",
"response",
"->",
"setContent",
"(",
"'There has been a problem serving this request.'",
")",
";",
"$",
"response",
"->",
"headers",
"->",
"set",
"(",
"'content-type'",
",",
"'text/html'",
")",
";",
"$",
"response",
"->",
"setStatusCode",
"(",
"Response",
"::",
"HTTP_INTERNAL_SERVER_ERROR",
")",
";",
"// Execute the user defined error callback",
"if",
"(",
"is_callable",
"(",
"$",
"this",
"->",
"error",
")",
")",
"{",
"$",
"response",
"=",
"call_user_func",
"(",
"$",
"this",
"->",
"error",
",",
"$",
"response",
",",
"$",
"exception",
")",
";",
"}",
"// Send the response",
"$",
"response",
"->",
"send",
"(",
")",
";",
"}"
] | Set an error response.
@param Exceptions $exception The caught exception | [
"Set",
"an",
"error",
"response",
"."
] | 0bd14bb561ba0486f60a6d3058587497ae99ea97 | https://github.com/diarmuidie/ImageRack-Kernel/blob/0bd14bb561ba0486f60a6d3058587497ae99ea97/src/Server.php#L387-L403 |
7,959 | diarmuidie/ImageRack-Kernel | src/Server.php | Server.send | public function send(Response $response = null)
{
if ($response) {
$this->response = $response;
}
$this->response->prepare($this->request);
$this->response->send();
// If a cacheWrite callback exists execute
// it now to write the image to the cache
if (is_callable($this->cacheWrite)) {
call_user_func_array(
$this->cacheWrite,
array($this->cache, $this->getCachePath())
);
}
} | php | public function send(Response $response = null)
{
if ($response) {
$this->response = $response;
}
$this->response->prepare($this->request);
$this->response->send();
// If a cacheWrite callback exists execute
// it now to write the image to the cache
if (is_callable($this->cacheWrite)) {
call_user_func_array(
$this->cacheWrite,
array($this->cache, $this->getCachePath())
);
}
} | [
"public",
"function",
"send",
"(",
"Response",
"$",
"response",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"response",
")",
"{",
"$",
"this",
"->",
"response",
"=",
"$",
"response",
";",
"}",
"$",
"this",
"->",
"response",
"->",
"prepare",
"(",
"$",
"this",
"->",
"request",
")",
";",
"$",
"this",
"->",
"response",
"->",
"send",
"(",
")",
";",
"// If a cacheWrite callback exists execute",
"// it now to write the image to the cache",
"if",
"(",
"is_callable",
"(",
"$",
"this",
"->",
"cacheWrite",
")",
")",
"{",
"call_user_func_array",
"(",
"$",
"this",
"->",
"cacheWrite",
",",
"array",
"(",
"$",
"this",
"->",
"cache",
",",
"$",
"this",
"->",
"getCachePath",
"(",
")",
")",
")",
";",
"}",
"}"
] | Send the response to the browser.
@param Response $response Optional overwrite response | [
"Send",
"the",
"response",
"to",
"the",
"browser",
"."
] | 0bd14bb561ba0486f60a6d3058587497ae99ea97 | https://github.com/diarmuidie/ImageRack-Kernel/blob/0bd14bb561ba0486f60a6d3058587497ae99ea97/src/Server.php#L410-L426 |
7,960 | diarmuidie/ImageRack-Kernel | src/Server.php | Server.processImage | private function processImage(File $file, ImageManager $imageManager, TemplateInterface $template)
{
// Process the image using the template
$image = new \Diarmuidie\ImageRack\Image\Process(
$file->readStream(),
$imageManager
);
// Process the image
return $image->process($template);
} | php | private function processImage(File $file, ImageManager $imageManager, TemplateInterface $template)
{
// Process the image using the template
$image = new \Diarmuidie\ImageRack\Image\Process(
$file->readStream(),
$imageManager
);
// Process the image
return $image->process($template);
} | [
"private",
"function",
"processImage",
"(",
"File",
"$",
"file",
",",
"ImageManager",
"$",
"imageManager",
",",
"TemplateInterface",
"$",
"template",
")",
"{",
"// Process the image using the template",
"$",
"image",
"=",
"new",
"\\",
"Diarmuidie",
"\\",
"ImageRack",
"\\",
"Image",
"\\",
"Process",
"(",
"$",
"file",
"->",
"readStream",
"(",
")",
",",
"$",
"imageManager",
")",
";",
"// Process the image",
"return",
"$",
"image",
"->",
"process",
"(",
"$",
"template",
")",
";",
"}"
] | Process an image using the provided template.
@param File $file The file handler for the image
@param ImageManager $imageManager The image manipulation manager
@param TemplateInterface $template The template
@return Image The processed image | [
"Process",
"an",
"image",
"using",
"the",
"provided",
"template",
"."
] | 0bd14bb561ba0486f60a6d3058587497ae99ea97 | https://github.com/diarmuidie/ImageRack-Kernel/blob/0bd14bb561ba0486f60a6d3058587497ae99ea97/src/Server.php#L437-L447 |
7,961 | diarmuidie/ImageRack-Kernel | src/Server.php | Server.parsePath | private function parsePath($path)
{
$parts = array(
'template' => null,
'path' => null,
);
// strip out any query params
if (preg_match('/^\/?(.*?)\/(.*)/', $path, $matches)) {
$parts['template'] = $matches[1];
$parts['path'] = $matches[2];
}
return $parts;
} | php | private function parsePath($path)
{
$parts = array(
'template' => null,
'path' => null,
);
// strip out any query params
if (preg_match('/^\/?(.*?)\/(.*)/', $path, $matches)) {
$parts['template'] = $matches[1];
$parts['path'] = $matches[2];
}
return $parts;
} | [
"private",
"function",
"parsePath",
"(",
"$",
"path",
")",
"{",
"$",
"parts",
"=",
"array",
"(",
"'template'",
"=>",
"null",
",",
"'path'",
"=>",
"null",
",",
")",
";",
"// strip out any query params",
"if",
"(",
"preg_match",
"(",
"'/^\\/?(.*?)\\/(.*)/'",
",",
"$",
"path",
",",
"$",
"matches",
")",
")",
"{",
"$",
"parts",
"[",
"'template'",
"]",
"=",
"$",
"matches",
"[",
"1",
"]",
";",
"$",
"parts",
"[",
"'path'",
"]",
"=",
"$",
"matches",
"[",
"2",
"]",
";",
"}",
"return",
"$",
"parts",
";",
"}"
] | Parse the request path to extract the path and template elements.
@param string $path The complet server path
@return array Array of 'template' and 'path' portions of the URL | [
"Parse",
"the",
"request",
"path",
"to",
"extract",
"the",
"path",
"and",
"template",
"elements",
"."
] | 0bd14bb561ba0486f60a6d3058587497ae99ea97 | https://github.com/diarmuidie/ImageRack-Kernel/blob/0bd14bb561ba0486f60a6d3058587497ae99ea97/src/Server.php#L476-L490 |
7,962 | diarmuidie/ImageRack-Kernel | src/Server.php | Server.validRequest | private function validRequest()
{
// Is a path and template set
if (empty($this->template) || empty($this->path)) {
return false;
}
// Is the template a valid template
if (!array_key_exists($this->template, $this->templates)) {
return false;
}
return true;
} | php | private function validRequest()
{
// Is a path and template set
if (empty($this->template) || empty($this->path)) {
return false;
}
// Is the template a valid template
if (!array_key_exists($this->template, $this->templates)) {
return false;
}
return true;
} | [
"private",
"function",
"validRequest",
"(",
")",
"{",
"// Is a path and template set",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"template",
")",
"||",
"empty",
"(",
"$",
"this",
"->",
"path",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Is the template a valid template",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"this",
"->",
"template",
",",
"$",
"this",
"->",
"templates",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Test if the request is valid.
@return bool | [
"Test",
"if",
"the",
"request",
"is",
"valid",
"."
] | 0bd14bb561ba0486f60a6d3058587497ae99ea97 | https://github.com/diarmuidie/ImageRack-Kernel/blob/0bd14bb561ba0486f60a6d3058587497ae99ea97/src/Server.php#L497-L510 |
7,963 | indigophp-archive/codeception-fuel-module | fuel/fuel/core/classes/cache/storage/apc.php | Cache_Storage_Apc._get_key | protected function _get_key($remove = false)
{
// get the current index information
list($identifier, $sections, $index) = $this->_get_index();
// get the key from the index
$key = isset($index[$identifier][0]) ? $index[$identifier][0] : false;
if ($remove === true)
{
if ( $key !== false )
{
unset($index[$identifier]);
apc_store($this->config['cache_id'].$sections, $index);
}
}
else
{
// create a new key if needed
$key === false and $key = $this->_new_key();
}
return $key;
} | php | protected function _get_key($remove = false)
{
// get the current index information
list($identifier, $sections, $index) = $this->_get_index();
// get the key from the index
$key = isset($index[$identifier][0]) ? $index[$identifier][0] : false;
if ($remove === true)
{
if ( $key !== false )
{
unset($index[$identifier]);
apc_store($this->config['cache_id'].$sections, $index);
}
}
else
{
// create a new key if needed
$key === false and $key = $this->_new_key();
}
return $key;
} | [
"protected",
"function",
"_get_key",
"(",
"$",
"remove",
"=",
"false",
")",
"{",
"// get the current index information",
"list",
"(",
"$",
"identifier",
",",
"$",
"sections",
",",
"$",
"index",
")",
"=",
"$",
"this",
"->",
"_get_index",
"(",
")",
";",
"// get the key from the index",
"$",
"key",
"=",
"isset",
"(",
"$",
"index",
"[",
"$",
"identifier",
"]",
"[",
"0",
"]",
")",
"?",
"$",
"index",
"[",
"$",
"identifier",
"]",
"[",
"0",
"]",
":",
"false",
";",
"if",
"(",
"$",
"remove",
"===",
"true",
")",
"{",
"if",
"(",
"$",
"key",
"!==",
"false",
")",
"{",
"unset",
"(",
"$",
"index",
"[",
"$",
"identifier",
"]",
")",
";",
"apc_store",
"(",
"$",
"this",
"->",
"config",
"[",
"'cache_id'",
"]",
".",
"$",
"sections",
",",
"$",
"index",
")",
";",
"}",
"}",
"else",
"{",
"// create a new key if needed",
"$",
"key",
"===",
"false",
"and",
"$",
"key",
"=",
"$",
"this",
"->",
"_new_key",
"(",
")",
";",
"}",
"return",
"$",
"key",
";",
"}"
] | get's the apc key belonging to the cache identifier
@param bool if true, remove the key retrieved from the index
@return string | [
"get",
"s",
"the",
"apc",
"key",
"belonging",
"to",
"the",
"cache",
"identifier"
] | 0973b7cbd540a0e89cc5bb7af94627f77f09bf49 | https://github.com/indigophp-archive/codeception-fuel-module/blob/0973b7cbd540a0e89cc5bb7af94627f77f09bf49/fuel/fuel/core/classes/cache/storage/apc.php#L289-L312 |
7,964 | synapsestudios/synapse-base | src/Synapse/Stdlib/DataObject.php | DataObject.exchangeArray | public function exchangeArray(array $data)
{
foreach ($this->object as $key => $value) {
if (array_key_exists($key, $data)) {
$setter = $this->getSetter($key);
$this->$setter($data[$key]);
}
}
return $this;
} | php | public function exchangeArray(array $data)
{
foreach ($this->object as $key => $value) {
if (array_key_exists($key, $data)) {
$setter = $this->getSetter($key);
$this->$setter($data[$key]);
}
}
return $this;
} | [
"public",
"function",
"exchangeArray",
"(",
"array",
"$",
"data",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"object",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"data",
")",
")",
"{",
"$",
"setter",
"=",
"$",
"this",
"->",
"getSetter",
"(",
"$",
"key",
")",
";",
"$",
"this",
"->",
"$",
"setter",
"(",
"$",
"data",
"[",
"$",
"key",
"]",
")",
";",
"}",
"}",
"return",
"$",
"this",
";",
"}"
] | Load object data in this entity from array
@param array $data Entity data to be set
@return AbstractEntity | [
"Load",
"object",
"data",
"in",
"this",
"entity",
"from",
"array"
] | 60c830550491742a077ab063f924e2f0b63825da | https://github.com/synapsestudios/synapse-base/blob/60c830550491742a077ab063f924e2f0b63825da/src/Synapse/Stdlib/DataObject.php#L57-L67 |
7,965 | synapsestudios/synapse-base | src/Synapse/Stdlib/DataObject.php | DataObject.getSetter | protected function getSetter($key)
{
$key = str_replace('_', ' ', $key);
$key = ucwords($key);
$key = str_replace(' ', '', $key);
return 'set'.$key;
} | php | protected function getSetter($key)
{
$key = str_replace('_', ' ', $key);
$key = ucwords($key);
$key = str_replace(' ', '', $key);
return 'set'.$key;
} | [
"protected",
"function",
"getSetter",
"(",
"$",
"key",
")",
"{",
"$",
"key",
"=",
"str_replace",
"(",
"'_'",
",",
"' '",
",",
"$",
"key",
")",
";",
"$",
"key",
"=",
"ucwords",
"(",
"$",
"key",
")",
";",
"$",
"key",
"=",
"str_replace",
"(",
"' '",
",",
"''",
",",
"$",
"key",
")",
";",
"return",
"'set'",
".",
"$",
"key",
";",
"}"
] | Return the method name for the setter of a given variable
Example: Converts 'user_id' to 'setUserId'
@param string $key Key of the variable in $this->object
@return string | [
"Return",
"the",
"method",
"name",
"for",
"the",
"setter",
"of",
"a",
"given",
"variable"
] | 60c830550491742a077ab063f924e2f0b63825da | https://github.com/synapsestudios/synapse-base/blob/60c830550491742a077ab063f924e2f0b63825da/src/Synapse/Stdlib/DataObject.php#L87-L94 |
7,966 | synapsestudios/synapse-base | src/Synapse/Stdlib/DataObject.php | DataObject.getMagicMethodType | protected function getMagicMethodType($method)
{
// If the method name is less than or equal to four characters
// then it's not a getter or a setter
if (strlen($method) <= 3) {
throw new BadMethodCallException('Method not found');
}
// Whether we are setting or getting
$type = substr($method, 0, 3);
if ($type !== 'get' and $type !== 'set') {
throw new BadMethodCallException('Method not found');
}
return $type;
} | php | protected function getMagicMethodType($method)
{
// If the method name is less than or equal to four characters
// then it's not a getter or a setter
if (strlen($method) <= 3) {
throw new BadMethodCallException('Method not found');
}
// Whether we are setting or getting
$type = substr($method, 0, 3);
if ($type !== 'get' and $type !== 'set') {
throw new BadMethodCallException('Method not found');
}
return $type;
} | [
"protected",
"function",
"getMagicMethodType",
"(",
"$",
"method",
")",
"{",
"// If the method name is less than or equal to four characters",
"// then it's not a getter or a setter",
"if",
"(",
"strlen",
"(",
"$",
"method",
")",
"<=",
"3",
")",
"{",
"throw",
"new",
"BadMethodCallException",
"(",
"'Method not found'",
")",
";",
"}",
"// Whether we are setting or getting",
"$",
"type",
"=",
"substr",
"(",
"$",
"method",
",",
"0",
",",
"3",
")",
";",
"if",
"(",
"$",
"type",
"!==",
"'get'",
"and",
"$",
"type",
"!==",
"'set'",
")",
"{",
"throw",
"new",
"BadMethodCallException",
"(",
"'Method not found'",
")",
";",
"}",
"return",
"$",
"type",
";",
"}"
] | Determine whether the method being called is a getter or setter
@param string $method Method being called
@return string | [
"Determine",
"whether",
"the",
"method",
"being",
"called",
"is",
"a",
"getter",
"or",
"setter"
] | 60c830550491742a077ab063f924e2f0b63825da | https://github.com/synapsestudios/synapse-base/blob/60c830550491742a077ab063f924e2f0b63825da/src/Synapse/Stdlib/DataObject.php#L102-L118 |
7,967 | synapsestudios/synapse-base | src/Synapse/Stdlib/DataObject.php | DataObject.getMagicMethodProperty | protected function getMagicMethodProperty($method)
{
// Get the property name
$property = lcfirst(substr($method, 3));
$transform = function ($letters) {
$letter = array_shift($letters);
return '_' . strtolower($letter);
};
$property = preg_replace_callback('/([A-Z])/', $transform, $property);
// Make sure the property exists
if (! array_key_exists($property, $this->object)) {
throw new InvalidArgumentException('Property, '.$property.', not found');
}
return $property;
} | php | protected function getMagicMethodProperty($method)
{
// Get the property name
$property = lcfirst(substr($method, 3));
$transform = function ($letters) {
$letter = array_shift($letters);
return '_' . strtolower($letter);
};
$property = preg_replace_callback('/([A-Z])/', $transform, $property);
// Make sure the property exists
if (! array_key_exists($property, $this->object)) {
throw new InvalidArgumentException('Property, '.$property.', not found');
}
return $property;
} | [
"protected",
"function",
"getMagicMethodProperty",
"(",
"$",
"method",
")",
"{",
"// Get the property name",
"$",
"property",
"=",
"lcfirst",
"(",
"substr",
"(",
"$",
"method",
",",
"3",
")",
")",
";",
"$",
"transform",
"=",
"function",
"(",
"$",
"letters",
")",
"{",
"$",
"letter",
"=",
"array_shift",
"(",
"$",
"letters",
")",
";",
"return",
"'_'",
".",
"strtolower",
"(",
"$",
"letter",
")",
";",
"}",
";",
"$",
"property",
"=",
"preg_replace_callback",
"(",
"'/([A-Z])/'",
",",
"$",
"transform",
",",
"$",
"property",
")",
";",
"// Make sure the property exists",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"property",
",",
"$",
"this",
"->",
"object",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Property, '",
".",
"$",
"property",
".",
"', not found'",
")",
";",
"}",
"return",
"$",
"property",
";",
"}"
] | Determine the property that is being set or get
@param string $method Method being called
@return string | [
"Determine",
"the",
"property",
"that",
"is",
"being",
"set",
"or",
"get"
] | 60c830550491742a077ab063f924e2f0b63825da | https://github.com/synapsestudios/synapse-base/blob/60c830550491742a077ab063f924e2f0b63825da/src/Synapse/Stdlib/DataObject.php#L126-L145 |
7,968 | arnegroskurth/TempFile | src/TempFile.php | TempFile.getContent | public function getContent() {
$size = $this->getSize();
if($size > 0) {
$pos = $this->ftell();
$this->fseek(0);
$return = $this->fread($size);
$this->fseek($pos);
return $return;
}
return '';
} | php | public function getContent() {
$size = $this->getSize();
if($size > 0) {
$pos = $this->ftell();
$this->fseek(0);
$return = $this->fread($size);
$this->fseek($pos);
return $return;
}
return '';
} | [
"public",
"function",
"getContent",
"(",
")",
"{",
"$",
"size",
"=",
"$",
"this",
"->",
"getSize",
"(",
")",
";",
"if",
"(",
"$",
"size",
">",
"0",
")",
"{",
"$",
"pos",
"=",
"$",
"this",
"->",
"ftell",
"(",
")",
";",
"$",
"this",
"->",
"fseek",
"(",
"0",
")",
";",
"$",
"return",
"=",
"$",
"this",
"->",
"fread",
"(",
"$",
"size",
")",
";",
"$",
"this",
"->",
"fseek",
"(",
"$",
"pos",
")",
";",
"return",
"$",
"return",
";",
"}",
"return",
"''",
";",
"}"
] | Returns file content as string.
@return string
@throws TempFileException | [
"Returns",
"file",
"content",
"as",
"string",
"."
] | e8f41a9d3cabf54e001c8e15f9c32aca71511d0a | https://github.com/arnegroskurth/TempFile/blob/e8f41a9d3cabf54e001c8e15f9c32aca71511d0a/src/TempFile.php#L139-L155 |
7,969 | arnegroskurth/TempFile | src/TempFile.php | TempFile.detectMime | public function detectMime() {
$fileInfo = new \finfo(FILEINFO_MIME);
return $fileInfo->buffer($this->getContent(), FILEINFO_MIME) ?: null;
} | php | public function detectMime() {
$fileInfo = new \finfo(FILEINFO_MIME);
return $fileInfo->buffer($this->getContent(), FILEINFO_MIME) ?: null;
} | [
"public",
"function",
"detectMime",
"(",
")",
"{",
"$",
"fileInfo",
"=",
"new",
"\\",
"finfo",
"(",
"FILEINFO_MIME",
")",
";",
"return",
"$",
"fileInfo",
"->",
"buffer",
"(",
"$",
"this",
"->",
"getContent",
"(",
")",
",",
"FILEINFO_MIME",
")",
"?",
":",
"null",
";",
"}"
] | Tries to detect MIME-Type using PHP's Fileinfo extension.
@return string | [
"Tries",
"to",
"detect",
"MIME",
"-",
"Type",
"using",
"PHP",
"s",
"Fileinfo",
"extension",
"."
] | e8f41a9d3cabf54e001c8e15f9c32aca71511d0a | https://github.com/arnegroskurth/TempFile/blob/e8f41a9d3cabf54e001c8e15f9c32aca71511d0a/src/TempFile.php#L163-L168 |
7,970 | arnegroskurth/TempFile | src/TempFile.php | TempFile.accessPath | public function accessPath(callable $callback) {
$this->closeFileHandle();
call_user_func($callback, $this->filePath);
$this->openFileHandle('r+');
return $this;
} | php | public function accessPath(callable $callback) {
$this->closeFileHandle();
call_user_func($callback, $this->filePath);
$this->openFileHandle('r+');
return $this;
} | [
"public",
"function",
"accessPath",
"(",
"callable",
"$",
"callback",
")",
"{",
"$",
"this",
"->",
"closeFileHandle",
"(",
")",
";",
"call_user_func",
"(",
"$",
"callback",
",",
"$",
"this",
"->",
"filePath",
")",
";",
"$",
"this",
"->",
"openFileHandle",
"(",
"'r+'",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Executes a given callback function
@param callable $callback
@return $this
@throws TempFileException | [
"Executes",
"a",
"given",
"callback",
"function"
] | e8f41a9d3cabf54e001c8e15f9c32aca71511d0a | https://github.com/arnegroskurth/TempFile/blob/e8f41a9d3cabf54e001c8e15f9c32aca71511d0a/src/TempFile.php#L295-L304 |
7,971 | arnegroskurth/TempFile | src/TempFile.php | TempFile.fromFile | public static function fromFile($path) {
if(!is_file($path) || !is_readable($path)) {
throw new TempFileException(sprintf('File %s does not exist or is not readable.', $path));
}
$tempFile = new static();
$tempFile->closeFileHandle();
if(!copy($path, $tempFile->filePath)) {
throw new TempFileException(sprintf('Could not read in file %s.', $path));
}
$tempFile->openFileHandle('r+');
return $tempFile;
} | php | public static function fromFile($path) {
if(!is_file($path) || !is_readable($path)) {
throw new TempFileException(sprintf('File %s does not exist or is not readable.', $path));
}
$tempFile = new static();
$tempFile->closeFileHandle();
if(!copy($path, $tempFile->filePath)) {
throw new TempFileException(sprintf('Could not read in file %s.', $path));
}
$tempFile->openFileHandle('r+');
return $tempFile;
} | [
"public",
"static",
"function",
"fromFile",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"!",
"is_file",
"(",
"$",
"path",
")",
"||",
"!",
"is_readable",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"TempFileException",
"(",
"sprintf",
"(",
"'File %s does not exist or is not readable.'",
",",
"$",
"path",
")",
")",
";",
"}",
"$",
"tempFile",
"=",
"new",
"static",
"(",
")",
";",
"$",
"tempFile",
"->",
"closeFileHandle",
"(",
")",
";",
"if",
"(",
"!",
"copy",
"(",
"$",
"path",
",",
"$",
"tempFile",
"->",
"filePath",
")",
")",
"{",
"throw",
"new",
"TempFileException",
"(",
"sprintf",
"(",
"'Could not read in file %s.'",
",",
"$",
"path",
")",
")",
";",
"}",
"$",
"tempFile",
"->",
"openFileHandle",
"(",
"'r+'",
")",
";",
"return",
"$",
"tempFile",
";",
"}"
] | Returns a TempFile object representing a copy of an existing file.
The file pointer is set to the beginning to the file.
@param string $path
@return TempFile
@throws TempFileException | [
"Returns",
"a",
"TempFile",
"object",
"representing",
"a",
"copy",
"of",
"an",
"existing",
"file",
".",
"The",
"file",
"pointer",
"is",
"set",
"to",
"the",
"beginning",
"to",
"the",
"file",
"."
] | e8f41a9d3cabf54e001c8e15f9c32aca71511d0a | https://github.com/arnegroskurth/TempFile/blob/e8f41a9d3cabf54e001c8e15f9c32aca71511d0a/src/TempFile.php#L362-L380 |
7,972 | jmpantoja/planb-utils | src/Type/Data/Data.php | Data.isEquivalentTo | private function isEquivalentTo(string $type): bool
{
$equivalents = self::EQUIVALENT_TYPES_METHODS;
if (!isset($equivalents[$type])) {
return false;
}
$method = $equivalents[$type];
return call_user_func([$this, $method]);
} | php | private function isEquivalentTo(string $type): bool
{
$equivalents = self::EQUIVALENT_TYPES_METHODS;
if (!isset($equivalents[$type])) {
return false;
}
$method = $equivalents[$type];
return call_user_func([$this, $method]);
} | [
"private",
"function",
"isEquivalentTo",
"(",
"string",
"$",
"type",
")",
":",
"bool",
"{",
"$",
"equivalents",
"=",
"self",
"::",
"EQUIVALENT_TYPES_METHODS",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"equivalents",
"[",
"$",
"type",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"method",
"=",
"$",
"equivalents",
"[",
"$",
"type",
"]",
";",
"return",
"call_user_func",
"(",
"[",
"$",
"this",
",",
"$",
"method",
"]",
")",
";",
"}"
] | Indica si el tipo de la variable es equivalente al dado
@param string $type
@return bool | [
"Indica",
"si",
"el",
"tipo",
"de",
"la",
"variable",
"es",
"equivalente",
"al",
"dado"
] | d17fbced4a285275928f8428ee56e269eb851690 | https://github.com/jmpantoja/planb-utils/blob/d17fbced4a285275928f8428ee56e269eb851690/src/Type/Data/Data.php#L251-L262 |
7,973 | jmpantoja/planb-utils | src/Type/Data/Data.php | Data.isConvertibleToString | public function isConvertibleToString(): bool
{
$isConvertible = $this->isScalar() || $this->isTypeOf(Stringifable::class) || $this->isNull();
if ($isConvertible) {
return true;
}
$hasToStringMethod = method_exists($this->variable, '__toString');
return $hasToStringMethod;
} | php | public function isConvertibleToString(): bool
{
$isConvertible = $this->isScalar() || $this->isTypeOf(Stringifable::class) || $this->isNull();
if ($isConvertible) {
return true;
}
$hasToStringMethod = method_exists($this->variable, '__toString');
return $hasToStringMethod;
} | [
"public",
"function",
"isConvertibleToString",
"(",
")",
":",
"bool",
"{",
"$",
"isConvertible",
"=",
"$",
"this",
"->",
"isScalar",
"(",
")",
"||",
"$",
"this",
"->",
"isTypeOf",
"(",
"Stringifable",
"::",
"class",
")",
"||",
"$",
"this",
"->",
"isNull",
"(",
")",
";",
"if",
"(",
"$",
"isConvertible",
")",
"{",
"return",
"true",
";",
"}",
"$",
"hasToStringMethod",
"=",
"method_exists",
"(",
"$",
"this",
"->",
"variable",
",",
"'__toString'",
")",
";",
"return",
"$",
"hasToStringMethod",
";",
"}"
] | Indica si la variable se puede expresar como una cadena de texto
@return bool | [
"Indica",
"si",
"la",
"variable",
"se",
"puede",
"expresar",
"como",
"una",
"cadena",
"de",
"texto"
] | d17fbced4a285275928f8428ee56e269eb851690 | https://github.com/jmpantoja/planb-utils/blob/d17fbced4a285275928f8428ee56e269eb851690/src/Type/Data/Data.php#L279-L290 |
7,974 | jmpantoja/planb-utils | src/Type/Data/Data.php | Data.getType | public function getType(): DataType
{
if (is_object($this->variable)) {
$typeName = get_class($this->variable);
return DataType::make($typeName);
}
$typeName = gettype($this->variable);
return DataType::make($typeName);
} | php | public function getType(): DataType
{
if (is_object($this->variable)) {
$typeName = get_class($this->variable);
return DataType::make($typeName);
}
$typeName = gettype($this->variable);
return DataType::make($typeName);
} | [
"public",
"function",
"getType",
"(",
")",
":",
"DataType",
"{",
"if",
"(",
"is_object",
"(",
"$",
"this",
"->",
"variable",
")",
")",
"{",
"$",
"typeName",
"=",
"get_class",
"(",
"$",
"this",
"->",
"variable",
")",
";",
"return",
"DataType",
"::",
"make",
"(",
"$",
"typeName",
")",
";",
"}",
"$",
"typeName",
"=",
"gettype",
"(",
"$",
"this",
"->",
"variable",
")",
";",
"return",
"DataType",
"::",
"make",
"(",
"$",
"typeName",
")",
";",
"}"
] | Devuelve el DataType
@return \PlanB\Type\DataType\DataType | [
"Devuelve",
"el",
"DataType"
] | d17fbced4a285275928f8428ee56e269eb851690 | https://github.com/jmpantoja/planb-utils/blob/d17fbced4a285275928f8428ee56e269eb851690/src/Type/Data/Data.php#L298-L309 |
7,975 | edunola13/enolaphp-framework | src/Http/Models/Session.php | Session.startSession | public function startSession($sessionId = NULl){
if($sessionId != NULL){
session_id($sessionId);
}
session_start();
$this->checkIdentity();
} | php | public function startSession($sessionId = NULl){
if($sessionId != NULL){
session_id($sessionId);
}
session_start();
$this->checkIdentity();
} | [
"public",
"function",
"startSession",
"(",
"$",
"sessionId",
"=",
"NULl",
")",
"{",
"if",
"(",
"$",
"sessionId",
"!=",
"NULL",
")",
"{",
"session_id",
"(",
"$",
"sessionId",
")",
";",
"}",
"session_start",
"(",
")",
";",
"$",
"this",
"->",
"checkIdentity",
"(",
")",
";",
"}"
] | Inicia una session | [
"Inicia",
"una",
"session"
] | a962bfcd53d7bc129d8c9946aaa71d264285229d | https://github.com/edunola13/enolaphp-framework/blob/a962bfcd53d7bc129d8c9946aaa71d264285229d/src/Http/Models/Session.php#L28-L34 |
7,976 | edunola13/enolaphp-framework | src/Http/Models/Session.php | Session.checkIdentity | private function checkIdentity(){
if(isset($_SESSION['REMOTE_ADDR']) && isset($_SESSION['HTTP_USER_AGENT'])){
if($_SESSION['REMOTE_ADDR'] != $this->serverVars['REMOTE_ADDR'] || $_SESSION['HTTP_USER_AGENT'] != $this->serverVars['HTTP_USER_AGENT']) {
Error::general_error('Session - Identity', 'There are a problem with the Sesion identity');
exit;
}
}
else{
$_SESSION['REMOTE_ADDR'] = $this->serverVars['REMOTE_ADDR'];
$_SESSION['HTTP_USER_AGENT'] = $this->serverVars['HTTP_USER_AGENT'];
}
} | php | private function checkIdentity(){
if(isset($_SESSION['REMOTE_ADDR']) && isset($_SESSION['HTTP_USER_AGENT'])){
if($_SESSION['REMOTE_ADDR'] != $this->serverVars['REMOTE_ADDR'] || $_SESSION['HTTP_USER_AGENT'] != $this->serverVars['HTTP_USER_AGENT']) {
Error::general_error('Session - Identity', 'There are a problem with the Sesion identity');
exit;
}
}
else{
$_SESSION['REMOTE_ADDR'] = $this->serverVars['REMOTE_ADDR'];
$_SESSION['HTTP_USER_AGENT'] = $this->serverVars['HTTP_USER_AGENT'];
}
} | [
"private",
"function",
"checkIdentity",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"_SESSION",
"[",
"'REMOTE_ADDR'",
"]",
")",
"&&",
"isset",
"(",
"$",
"_SESSION",
"[",
"'HTTP_USER_AGENT'",
"]",
")",
")",
"{",
"if",
"(",
"$",
"_SESSION",
"[",
"'REMOTE_ADDR'",
"]",
"!=",
"$",
"this",
"->",
"serverVars",
"[",
"'REMOTE_ADDR'",
"]",
"||",
"$",
"_SESSION",
"[",
"'HTTP_USER_AGENT'",
"]",
"!=",
"$",
"this",
"->",
"serverVars",
"[",
"'HTTP_USER_AGENT'",
"]",
")",
"{",
"Error",
"::",
"general_error",
"(",
"'Session - Identity'",
",",
"'There are a problem with the Sesion identity'",
")",
";",
"exit",
";",
"}",
"}",
"else",
"{",
"$",
"_SESSION",
"[",
"'REMOTE_ADDR'",
"]",
"=",
"$",
"this",
"->",
"serverVars",
"[",
"'REMOTE_ADDR'",
"]",
";",
"$",
"_SESSION",
"[",
"'HTTP_USER_AGENT'",
"]",
"=",
"$",
"this",
"->",
"serverVars",
"[",
"'HTTP_USER_AGENT'",
"]",
";",
"}",
"}"
] | Realiza una comprobacion de identidad
Analiza que no se este suplantando la identidad del verdadero usuario | [
"Realiza",
"una",
"comprobacion",
"de",
"identidad",
"Analiza",
"que",
"no",
"se",
"este",
"suplantando",
"la",
"identidad",
"del",
"verdadero",
"usuario"
] | a962bfcd53d7bc129d8c9946aaa71d264285229d | https://github.com/edunola13/enolaphp-framework/blob/a962bfcd53d7bc129d8c9946aaa71d264285229d/src/Http/Models/Session.php#L122-L133 |
7,977 | jeromeklam/freefw | src/FreeFW/Tools/ImageResizer.php | ImageResizer.getImageAsString | public function getImageAsString($image_type = null, $quality = null)
{
$string_temp = tempnam('', '');
$this->save($string_temp, $image_type, $quality);
$string = file_get_contents($string_temp);
unlink($string_temp);
return $string;
} | php | public function getImageAsString($image_type = null, $quality = null)
{
$string_temp = tempnam('', '');
$this->save($string_temp, $image_type, $quality);
$string = file_get_contents($string_temp);
unlink($string_temp);
return $string;
} | [
"public",
"function",
"getImageAsString",
"(",
"$",
"image_type",
"=",
"null",
",",
"$",
"quality",
"=",
"null",
")",
"{",
"$",
"string_temp",
"=",
"tempnam",
"(",
"''",
",",
"''",
")",
";",
"$",
"this",
"->",
"save",
"(",
"$",
"string_temp",
",",
"$",
"image_type",
",",
"$",
"quality",
")",
";",
"$",
"string",
"=",
"file_get_contents",
"(",
"$",
"string_temp",
")",
";",
"unlink",
"(",
"$",
"string_temp",
")",
";",
"return",
"$",
"string",
";",
"}"
] | Conversion en chaine
@param int $image_type
@param int $quality
@return string | [
"Conversion",
"en",
"chaine"
] | 16ecf24192375c920a070296f396b9d3fd994a1e | https://github.com/jeromeklam/freefw/blob/16ecf24192375c920a070296f396b9d3fd994a1e/src/FreeFW/Tools/ImageResizer.php#L217-L225 |
7,978 | themichaelhall/bluemvc-core | src/Route.php | Route.matches | public function matches(RequestInterface $request): ?RouteMatchInterface
{
$path = $request->getUrl()->getPath();
$directoryParts = $path->getDirectoryParts();
$filename = $path->getFilename() ?? '';
if (count($this->path) === 0) {
// My path is empty, i.e. should only match root path.
if (count($directoryParts) !== 0) {
return null;
}
return new RouteMatch($this->getControllerClassName(), $filename);
}
if (count($this->path) > count($directoryParts)) {
// My path contains more than the path in request, e.g. path /foo/ should not match /bar
return null;
}
// Check each parts.
$index = 0;
foreach ($this->path as $pathPart) {
// Part of path does not match.
if ($pathPart !== $directoryParts[$index]) {
return null;
}
$index++;
}
if (count($directoryParts) > $index) {
$action = $directoryParts[$index];
$parameters = array_slice($directoryParts, $index + 1);
$parameters[] = $filename;
} else {
$action = $filename;
$parameters = [];
}
return new RouteMatch($this->getControllerClassName(), $action, $parameters);
} | php | public function matches(RequestInterface $request): ?RouteMatchInterface
{
$path = $request->getUrl()->getPath();
$directoryParts = $path->getDirectoryParts();
$filename = $path->getFilename() ?? '';
if (count($this->path) === 0) {
// My path is empty, i.e. should only match root path.
if (count($directoryParts) !== 0) {
return null;
}
return new RouteMatch($this->getControllerClassName(), $filename);
}
if (count($this->path) > count($directoryParts)) {
// My path contains more than the path in request, e.g. path /foo/ should not match /bar
return null;
}
// Check each parts.
$index = 0;
foreach ($this->path as $pathPart) {
// Part of path does not match.
if ($pathPart !== $directoryParts[$index]) {
return null;
}
$index++;
}
if (count($directoryParts) > $index) {
$action = $directoryParts[$index];
$parameters = array_slice($directoryParts, $index + 1);
$parameters[] = $filename;
} else {
$action = $filename;
$parameters = [];
}
return new RouteMatch($this->getControllerClassName(), $action, $parameters);
} | [
"public",
"function",
"matches",
"(",
"RequestInterface",
"$",
"request",
")",
":",
"?",
"RouteMatchInterface",
"{",
"$",
"path",
"=",
"$",
"request",
"->",
"getUrl",
"(",
")",
"->",
"getPath",
"(",
")",
";",
"$",
"directoryParts",
"=",
"$",
"path",
"->",
"getDirectoryParts",
"(",
")",
";",
"$",
"filename",
"=",
"$",
"path",
"->",
"getFilename",
"(",
")",
"??",
"''",
";",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"path",
")",
"===",
"0",
")",
"{",
"// My path is empty, i.e. should only match root path.",
"if",
"(",
"count",
"(",
"$",
"directoryParts",
")",
"!==",
"0",
")",
"{",
"return",
"null",
";",
"}",
"return",
"new",
"RouteMatch",
"(",
"$",
"this",
"->",
"getControllerClassName",
"(",
")",
",",
"$",
"filename",
")",
";",
"}",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"path",
")",
">",
"count",
"(",
"$",
"directoryParts",
")",
")",
"{",
"// My path contains more than the path in request, e.g. path /foo/ should not match /bar",
"return",
"null",
";",
"}",
"// Check each parts.",
"$",
"index",
"=",
"0",
";",
"foreach",
"(",
"$",
"this",
"->",
"path",
"as",
"$",
"pathPart",
")",
"{",
"// Part of path does not match.",
"if",
"(",
"$",
"pathPart",
"!==",
"$",
"directoryParts",
"[",
"$",
"index",
"]",
")",
"{",
"return",
"null",
";",
"}",
"$",
"index",
"++",
";",
"}",
"if",
"(",
"count",
"(",
"$",
"directoryParts",
")",
">",
"$",
"index",
")",
"{",
"$",
"action",
"=",
"$",
"directoryParts",
"[",
"$",
"index",
"]",
";",
"$",
"parameters",
"=",
"array_slice",
"(",
"$",
"directoryParts",
",",
"$",
"index",
"+",
"1",
")",
";",
"$",
"parameters",
"[",
"]",
"=",
"$",
"filename",
";",
"}",
"else",
"{",
"$",
"action",
"=",
"$",
"filename",
";",
"$",
"parameters",
"=",
"[",
"]",
";",
"}",
"return",
"new",
"RouteMatch",
"(",
"$",
"this",
"->",
"getControllerClassName",
"(",
")",
",",
"$",
"action",
",",
"$",
"parameters",
")",
";",
"}"
] | Check if a route matches a request.
@since 1.0.0
@param RequestInterface $request The request.
@return RouteMatchInterface|null The route match if rout matches request, false otherwise. | [
"Check",
"if",
"a",
"route",
"matches",
"a",
"request",
"."
] | cbc8ccf8ed4f15ec6105837b29c2bd3db3f93680 | https://github.com/themichaelhall/bluemvc-core/blob/cbc8ccf8ed4f15ec6105837b29c2bd3db3f93680/src/Route.php#L51-L92 |
7,979 | themichaelhall/bluemvc-core | src/Route.php | Route.splitPath | private static function splitPath(string $path): array
{
if ($path === '') {
return [];
}
$result = explode('/', $path);
foreach ($result as $pathPart) {
if ($pathPart === '') {
throw new InvalidRoutePathException('Path "' . $path . '" contains empty part.');
}
if (preg_match('/[^a-zA-Z0-9._-]/', $pathPart, $matches)) {
throw new InvalidRoutePathException('Path "' . $path . '" contains invalid character "' . $matches[0] . '".');
}
}
return $result;
} | php | private static function splitPath(string $path): array
{
if ($path === '') {
return [];
}
$result = explode('/', $path);
foreach ($result as $pathPart) {
if ($pathPart === '') {
throw new InvalidRoutePathException('Path "' . $path . '" contains empty part.');
}
if (preg_match('/[^a-zA-Z0-9._-]/', $pathPart, $matches)) {
throw new InvalidRoutePathException('Path "' . $path . '" contains invalid character "' . $matches[0] . '".');
}
}
return $result;
} | [
"private",
"static",
"function",
"splitPath",
"(",
"string",
"$",
"path",
")",
":",
"array",
"{",
"if",
"(",
"$",
"path",
"===",
"''",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"result",
"=",
"explode",
"(",
"'/'",
",",
"$",
"path",
")",
";",
"foreach",
"(",
"$",
"result",
"as",
"$",
"pathPart",
")",
"{",
"if",
"(",
"$",
"pathPart",
"===",
"''",
")",
"{",
"throw",
"new",
"InvalidRoutePathException",
"(",
"'Path \"'",
".",
"$",
"path",
".",
"'\" contains empty part.'",
")",
";",
"}",
"if",
"(",
"preg_match",
"(",
"'/[^a-zA-Z0-9._-]/'",
",",
"$",
"pathPart",
",",
"$",
"matches",
")",
")",
"{",
"throw",
"new",
"InvalidRoutePathException",
"(",
"'Path \"'",
".",
"$",
"path",
".",
"'\" contains invalid character \"'",
".",
"$",
"matches",
"[",
"0",
"]",
".",
"'\".'",
")",
";",
"}",
"}",
"return",
"$",
"result",
";",
"}"
] | Splits a path in parts.
@param string $path The path.
@throws InvalidRoutePathException If the path is invalid.
@return string[] The path as parts. | [
"Splits",
"a",
"path",
"in",
"parts",
"."
] | cbc8ccf8ed4f15ec6105837b29c2bd3db3f93680 | https://github.com/themichaelhall/bluemvc-core/blob/cbc8ccf8ed4f15ec6105837b29c2bd3db3f93680/src/Route.php#L103-L121 |
7,980 | letrunghieu/taki | src/Traits/TakiAuthentication.php | TakiAuthentication.loginUsername | public function loginUsername()
{
$loginBy = config('taki.login_by');
$loginField = config('taki.field.both');
if ($loginBy === 'email') {
$loginField = config('taki.field.email');
} elseif ($loginBy === 'username') {
$loginField = config('taki.field.username');
}
return $loginField;
} | php | public function loginUsername()
{
$loginBy = config('taki.login_by');
$loginField = config('taki.field.both');
if ($loginBy === 'email') {
$loginField = config('taki.field.email');
} elseif ($loginBy === 'username') {
$loginField = config('taki.field.username');
}
return $loginField;
} | [
"public",
"function",
"loginUsername",
"(",
")",
"{",
"$",
"loginBy",
"=",
"config",
"(",
"'taki.login_by'",
")",
";",
"$",
"loginField",
"=",
"config",
"(",
"'taki.field.both'",
")",
";",
"if",
"(",
"$",
"loginBy",
"===",
"'email'",
")",
"{",
"$",
"loginField",
"=",
"config",
"(",
"'taki.field.email'",
")",
";",
"}",
"elseif",
"(",
"$",
"loginBy",
"===",
"'username'",
")",
"{",
"$",
"loginField",
"=",
"config",
"(",
"'taki.field.username'",
")",
";",
"}",
"return",
"$",
"loginField",
";",
"}"
] | Get the login username to be used by the controller.
@return string | [
"Get",
"the",
"login",
"username",
"to",
"be",
"used",
"by",
"the",
"controller",
"."
] | c4af7345a4a9df6d83c84f04335da92b62debf17 | https://github.com/letrunghieu/taki/blob/c4af7345a4a9df6d83c84f04335da92b62debf17/src/Traits/TakiAuthentication.php#L66-L77 |
7,981 | sellerlabs/quip | src/Quip/Expressions/ExpressionParser.php | ExpressionParser.parse | public function parse()
{
// Note: Order is very important here!
$operators = [
Expression::OPERATOR_GTE,
Expression::OPERATOR_LTE,
Expression::OPERATOR_NOT,
Expression::OPERATOR_EQ,
Expression::OPERATOR_GT,
Expression::OPERATOR_LT
];
foreach ($operators as $operator) {
$pos = strpos($this->rawExpression, $operator);
if ($pos) {
return new Expression(
substr($this->rawExpression, 0, $pos),
$operator,
substr($this->rawExpression, $pos + strlen($operator))
);
}
}
// Throw an exception if an operator can't be found
throw new InvalidExpressionException();
} | php | public function parse()
{
// Note: Order is very important here!
$operators = [
Expression::OPERATOR_GTE,
Expression::OPERATOR_LTE,
Expression::OPERATOR_NOT,
Expression::OPERATOR_EQ,
Expression::OPERATOR_GT,
Expression::OPERATOR_LT
];
foreach ($operators as $operator) {
$pos = strpos($this->rawExpression, $operator);
if ($pos) {
return new Expression(
substr($this->rawExpression, 0, $pos),
$operator,
substr($this->rawExpression, $pos + strlen($operator))
);
}
}
// Throw an exception if an operator can't be found
throw new InvalidExpressionException();
} | [
"public",
"function",
"parse",
"(",
")",
"{",
"// Note: Order is very important here!",
"$",
"operators",
"=",
"[",
"Expression",
"::",
"OPERATOR_GTE",
",",
"Expression",
"::",
"OPERATOR_LTE",
",",
"Expression",
"::",
"OPERATOR_NOT",
",",
"Expression",
"::",
"OPERATOR_EQ",
",",
"Expression",
"::",
"OPERATOR_GT",
",",
"Expression",
"::",
"OPERATOR_LT",
"]",
";",
"foreach",
"(",
"$",
"operators",
"as",
"$",
"operator",
")",
"{",
"$",
"pos",
"=",
"strpos",
"(",
"$",
"this",
"->",
"rawExpression",
",",
"$",
"operator",
")",
";",
"if",
"(",
"$",
"pos",
")",
"{",
"return",
"new",
"Expression",
"(",
"substr",
"(",
"$",
"this",
"->",
"rawExpression",
",",
"0",
",",
"$",
"pos",
")",
",",
"$",
"operator",
",",
"substr",
"(",
"$",
"this",
"->",
"rawExpression",
",",
"$",
"pos",
"+",
"strlen",
"(",
"$",
"operator",
")",
")",
")",
";",
"}",
"}",
"// Throw an exception if an operator can't be found",
"throw",
"new",
"InvalidExpressionException",
"(",
")",
";",
"}"
] | Parse a raw expression into a valid expression
@return Expression
@throws InvalidExpressionException | [
"Parse",
"a",
"raw",
"expression",
"into",
"a",
"valid",
"expression"
] | d4211f96edfc1893a3690e93adfecfb3dc19ad32 | https://github.com/sellerlabs/quip/blob/d4211f96edfc1893a3690e93adfecfb3dc19ad32/src/Quip/Expressions/ExpressionParser.php#L42-L69 |
7,982 | zepi/turbo-base | Zepi/Core/Utils/src/Backend/ConfigurationFileBackend.php | ConfigurationFileBackend.saveConfiguration | public function saveConfiguration($settings)
{
if (file_exists($this->path) && !is_writable($this->path)) {
throw new Exception('The file "' . $this->path . '" isn\'t writable!');
}
$content = json_encode($settings);
return file_put_contents($this->path, $content);
} | php | public function saveConfiguration($settings)
{
if (file_exists($this->path) && !is_writable($this->path)) {
throw new Exception('The file "' . $this->path . '" isn\'t writable!');
}
$content = json_encode($settings);
return file_put_contents($this->path, $content);
} | [
"public",
"function",
"saveConfiguration",
"(",
"$",
"settings",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"this",
"->",
"path",
")",
"&&",
"!",
"is_writable",
"(",
"$",
"this",
"->",
"path",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'The file \"'",
".",
"$",
"this",
"->",
"path",
".",
"'\" isn\\'t writable!'",
")",
";",
"}",
"$",
"content",
"=",
"json_encode",
"(",
"$",
"settings",
")",
";",
"return",
"file_put_contents",
"(",
"$",
"this",
"->",
"path",
",",
"$",
"content",
")",
";",
"}"
] | Saves the configuration to the file.
@access public
@param array $settings
@return boolean
@throws Zepi\Turbo\Exception The file "$path" isn't writable! | [
"Saves",
"the",
"configuration",
"to",
"the",
"file",
"."
] | 9a36d8c7649317f55f91b2adf386bd1f04ec02a3 | https://github.com/zepi/turbo-base/blob/9a36d8c7649317f55f91b2adf386bd1f04ec02a3/Zepi/Core/Utils/src/Backend/ConfigurationFileBackend.php#L74-L83 |
7,983 | zepi/turbo-base | Zepi/Core/Utils/src/Backend/ConfigurationFileBackend.php | ConfigurationFileBackend.loadConfiguration | public function loadConfiguration()
{
if (!file_exists($this->path)) {
return array();
}
if (!is_readable($this->path)) {
throw new Exception('The file "' . $this->path . '" isn\'t readable!');
}
$content = file_get_contents($this->path);
$settings = json_decode($content, true);
if ($settings == false) {
return array();
}
return $settings;
} | php | public function loadConfiguration()
{
if (!file_exists($this->path)) {
return array();
}
if (!is_readable($this->path)) {
throw new Exception('The file "' . $this->path . '" isn\'t readable!');
}
$content = file_get_contents($this->path);
$settings = json_decode($content, true);
if ($settings == false) {
return array();
}
return $settings;
} | [
"public",
"function",
"loadConfiguration",
"(",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"this",
"->",
"path",
")",
")",
"{",
"return",
"array",
"(",
")",
";",
"}",
"if",
"(",
"!",
"is_readable",
"(",
"$",
"this",
"->",
"path",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'The file \"'",
".",
"$",
"this",
"->",
"path",
".",
"'\" isn\\'t readable!'",
")",
";",
"}",
"$",
"content",
"=",
"file_get_contents",
"(",
"$",
"this",
"->",
"path",
")",
";",
"$",
"settings",
"=",
"json_decode",
"(",
"$",
"content",
",",
"true",
")",
";",
"if",
"(",
"$",
"settings",
"==",
"false",
")",
"{",
"return",
"array",
"(",
")",
";",
"}",
"return",
"$",
"settings",
";",
"}"
] | Loads the configuration from the file.
@access public
@return array
@throws Zepi\Turbo\Exception The file "$path" isn't readable! | [
"Loads",
"the",
"configuration",
"from",
"the",
"file",
"."
] | 9a36d8c7649317f55f91b2adf386bd1f04ec02a3 | https://github.com/zepi/turbo-base/blob/9a36d8c7649317f55f91b2adf386bd1f04ec02a3/Zepi/Core/Utils/src/Backend/ConfigurationFileBackend.php#L93-L111 |
7,984 | Sowapps/orpheus-sqladapter | src/SQLRequest/SQLSelectRequest.php | SQLSelectRequest.where | public function where($condition, $equality = null, $value = null) {
if( $equality !== null ) {
if( $value === null ) {
$value = $equality;
$equality = is_array($value) ? 'IN' : '=';
}
$condition = $this->escapeIdentifier($condition) . ' ' . $equality . ' ' . (is_array($value) ?
'(' . $this->sqlAdapter->formatValueList($value) . ')' :
$this->escapeValue(is_object($value) ? id($value) : $value));
}
$where = $this->get('where', array());
$where[] = $condition;
return $this->sget('where', $where);
} | php | public function where($condition, $equality = null, $value = null) {
if( $equality !== null ) {
if( $value === null ) {
$value = $equality;
$equality = is_array($value) ? 'IN' : '=';
}
$condition = $this->escapeIdentifier($condition) . ' ' . $equality . ' ' . (is_array($value) ?
'(' . $this->sqlAdapter->formatValueList($value) . ')' :
$this->escapeValue(is_object($value) ? id($value) : $value));
}
$where = $this->get('where', array());
$where[] = $condition;
return $this->sget('where', $where);
} | [
"public",
"function",
"where",
"(",
"$",
"condition",
",",
"$",
"equality",
"=",
"null",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"equality",
"!==",
"null",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"$",
"value",
"=",
"$",
"equality",
";",
"$",
"equality",
"=",
"is_array",
"(",
"$",
"value",
")",
"?",
"'IN'",
":",
"'='",
";",
"}",
"$",
"condition",
"=",
"$",
"this",
"->",
"escapeIdentifier",
"(",
"$",
"condition",
")",
".",
"' '",
".",
"$",
"equality",
".",
"' '",
".",
"(",
"is_array",
"(",
"$",
"value",
")",
"?",
"'('",
".",
"$",
"this",
"->",
"sqlAdapter",
"->",
"formatValueList",
"(",
"$",
"value",
")",
".",
"')'",
":",
"$",
"this",
"->",
"escapeValue",
"(",
"is_object",
"(",
"$",
"value",
")",
"?",
"id",
"(",
"$",
"value",
")",
":",
"$",
"value",
")",
")",
";",
"}",
"$",
"where",
"=",
"$",
"this",
"->",
"get",
"(",
"'where'",
",",
"array",
"(",
")",
")",
";",
"$",
"where",
"[",
"]",
"=",
"$",
"condition",
";",
"return",
"$",
"this",
"->",
"sget",
"(",
"'where'",
",",
"$",
"where",
")",
";",
"}"
] | Set the whereclause
@param string $condition
@param string $equality
@param string $value
@return \Orpheus\SQLRequest\SQLSelectRequest
If only $condition is provided, this is used as complete string, e.g where("id = 5")
If $equality & $value are provided, it uses it with $condition as a field (identifier), e.g where('id', '=', '5')
where identifier and value are escaped with escapeIdentifier() & escapeValue()
If $equality is provided but $value is not, $equality is the value and where are using a smart comparator, e.g where('id', '5')
All examples return the same results. Smart comparator is IN for array values and = for all other. | [
"Set",
"the",
"whereclause"
] | d7730e70f84d7d877a688ff4408cefea34117a1c | https://github.com/Sowapps/orpheus-sqladapter/blob/d7730e70f84d7d877a688ff4408cefea34117a1c/src/SQLRequest/SQLSelectRequest.php#L99-L112 |
7,985 | Sowapps/orpheus-sqladapter | src/SQLRequest/SQLSelectRequest.php | SQLSelectRequest.join | public function join($join) {
$joins = $this->get('join', array());
$joins[] = $join;
return $this->sget('join', $joins);
} | php | public function join($join) {
$joins = $this->get('join', array());
$joins[] = $join;
return $this->sget('join', $joins);
} | [
"public",
"function",
"join",
"(",
"$",
"join",
")",
"{",
"$",
"joins",
"=",
"$",
"this",
"->",
"get",
"(",
"'join'",
",",
"array",
"(",
")",
")",
";",
"$",
"joins",
"[",
"]",
"=",
"$",
"join",
";",
"return",
"$",
"this",
"->",
"sget",
"(",
"'join'",
",",
"$",
"joins",
")",
";",
"}"
] | Add a join condition to this query
@param string $join
@return $this | [
"Add",
"a",
"join",
"condition",
"to",
"this",
"query"
] | d7730e70f84d7d877a688ff4408cefea34117a1c | https://github.com/Sowapps/orpheus-sqladapter/blob/d7730e70f84d7d877a688ff4408cefea34117a1c/src/SQLRequest/SQLSelectRequest.php#L170-L174 |
7,986 | Sowapps/orpheus-sqladapter | src/SQLRequest/SQLSelectRequest.php | SQLSelectRequest.count | public function count($max = '') {
$countKey = '0rpHeus_Count';
$query = $this->getClone(false);
$result = $query->set('what', 'COUNT(*) ' . $countKey)
->from('(' . $this->getQuery() . ') oq')
->asArray()->run();
return isset($result[$countKey]) ? $result[$countKey] : 0;
} | php | public function count($max = '') {
$countKey = '0rpHeus_Count';
$query = $this->getClone(false);
$result = $query->set('what', 'COUNT(*) ' . $countKey)
->from('(' . $this->getQuery() . ') oq')
->asArray()->run();
return isset($result[$countKey]) ? $result[$countKey] : 0;
} | [
"public",
"function",
"count",
"(",
"$",
"max",
"=",
"''",
")",
"{",
"$",
"countKey",
"=",
"'0rpHeus_Count'",
";",
"$",
"query",
"=",
"$",
"this",
"->",
"getClone",
"(",
"false",
")",
";",
"$",
"result",
"=",
"$",
"query",
"->",
"set",
"(",
"'what'",
",",
"'COUNT(*) '",
".",
"$",
"countKey",
")",
"->",
"from",
"(",
"'('",
".",
"$",
"this",
"->",
"getQuery",
"(",
")",
".",
"') oq'",
")",
"->",
"asArray",
"(",
")",
"->",
"run",
"(",
")",
";",
"return",
"isset",
"(",
"$",
"result",
"[",
"$",
"countKey",
"]",
")",
"?",
"$",
"result",
"[",
"$",
"countKey",
"]",
":",
"0",
";",
"}"
] | Count the number of result of this query
@param int $max The max number where are expecting
@throws Exception
@return int | [
"Count",
"the",
"number",
"of",
"result",
"of",
"this",
"query"
] | d7730e70f84d7d877a688ff4408cefea34117a1c | https://github.com/Sowapps/orpheus-sqladapter/blob/d7730e70f84d7d877a688ff4408cefea34117a1c/src/SQLRequest/SQLSelectRequest.php#L245-L254 |
7,987 | Sowapps/orpheus-sqladapter | src/SQLRequest/SQLSelectRequest.php | SQLSelectRequest.fetch | public function fetch() {
if( !$this->fetchLastStatement ) {
$this->startFetching();
}
$row = $this->fetchLastStatement->fetch(\PDO::FETCH_ASSOC);
if( !$row ) {
// Last return false, we return null, same effect
return null;
}
if( !$this->fetchIsObject ) {
return $row;
}
$class = $this->class;
return $class::load($row, true, $this->usingCache);
} | php | public function fetch() {
if( !$this->fetchLastStatement ) {
$this->startFetching();
}
$row = $this->fetchLastStatement->fetch(\PDO::FETCH_ASSOC);
if( !$row ) {
// Last return false, we return null, same effect
return null;
}
if( !$this->fetchIsObject ) {
return $row;
}
$class = $this->class;
return $class::load($row, true, $this->usingCache);
} | [
"public",
"function",
"fetch",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"fetchLastStatement",
")",
"{",
"$",
"this",
"->",
"startFetching",
"(",
")",
";",
"}",
"$",
"row",
"=",
"$",
"this",
"->",
"fetchLastStatement",
"->",
"fetch",
"(",
"\\",
"PDO",
"::",
"FETCH_ASSOC",
")",
";",
"if",
"(",
"!",
"$",
"row",
")",
"{",
"// Last return false, we return null, same effect",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"fetchIsObject",
")",
"{",
"return",
"$",
"row",
";",
"}",
"$",
"class",
"=",
"$",
"this",
"->",
"class",
";",
"return",
"$",
"class",
"::",
"load",
"(",
"$",
"row",
",",
"true",
",",
"$",
"this",
"->",
"usingCache",
")",
";",
"}"
] | Fetch the next result of this query
@return NULL|mixed
Query one time the DBMS and fetch result for next calls
This feature is made for common used else it may have an unexpected behavior | [
"Fetch",
"the",
"next",
"result",
"of",
"this",
"query"
] | d7730e70f84d7d877a688ff4408cefea34117a1c | https://github.com/Sowapps/orpheus-sqladapter/blob/d7730e70f84d7d877a688ff4408cefea34117a1c/src/SQLRequest/SQLSelectRequest.php#L298-L312 |
7,988 | docit/core | src/Document.php | Document.attr | public function attr($key = null, $default = null)
{
return is_null($key) ? $this->attributes : array_get($this->attributes, $key, $default);
} | php | public function attr($key = null, $default = null)
{
return is_null($key) ? $this->attributes : array_get($this->attributes, $key, $default);
} | [
"public",
"function",
"attr",
"(",
"$",
"key",
"=",
"null",
",",
"$",
"default",
"=",
"null",
")",
"{",
"return",
"is_null",
"(",
"$",
"key",
")",
"?",
"$",
"this",
"->",
"attributes",
":",
"array_get",
"(",
"$",
"this",
"->",
"attributes",
",",
"$",
"key",
",",
"$",
"default",
")",
";",
"}"
] | Get a attribute using dot notation
@param string $key
@param null|mixed $default
@return array|null|mixed | [
"Get",
"a",
"attribute",
"using",
"dot",
"notation"
] | 448e1cdca18a8ffb6c08430cad8d22162171ac35 | https://github.com/docit/core/blob/448e1cdca18a8ffb6c08430cad8d22162171ac35/src/Document.php#L139-L142 |
7,989 | docit/core | src/Document.php | Document.url | public function url()
{
return $this->docit->url($this->project, $this->project->getRef(), $this->pathName);
} | php | public function url()
{
return $this->docit->url($this->project, $this->project->getRef(), $this->pathName);
} | [
"public",
"function",
"url",
"(",
")",
"{",
"return",
"$",
"this",
"->",
"docit",
"->",
"url",
"(",
"$",
"this",
"->",
"project",
",",
"$",
"this",
"->",
"project",
"->",
"getRef",
"(",
")",
",",
"$",
"this",
"->",
"pathName",
")",
";",
"}"
] | Get the url to this document
@return string | [
"Get",
"the",
"url",
"to",
"this",
"document"
] | 448e1cdca18a8ffb6c08430cad8d22162171ac35 | https://github.com/docit/core/blob/448e1cdca18a8ffb6c08430cad8d22162171ac35/src/Document.php#L149-L152 |
7,990 | ekyna/Characteristics | Entity/BooleanCharacteristic.php | BooleanCharacteristic.setBoolean | public function setBoolean($boolean = null)
{
$this->boolean = null !== $boolean ? (bool) $boolean : null;
return $this;
} | php | public function setBoolean($boolean = null)
{
$this->boolean = null !== $boolean ? (bool) $boolean : null;
return $this;
} | [
"public",
"function",
"setBoolean",
"(",
"$",
"boolean",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"boolean",
"=",
"null",
"!==",
"$",
"boolean",
"?",
"(",
"bool",
")",
"$",
"boolean",
":",
"null",
";",
"return",
"$",
"this",
";",
"}"
] | Sets the boolean.
@param boolean $boolean
@return BooleanCharacteristic | [
"Sets",
"the",
"boolean",
"."
] | 118a349fd98a7c28721d3cbaba67ce79d1cffada | https://github.com/ekyna/Characteristics/blob/118a349fd98a7c28721d3cbaba67ce79d1cffada/Entity/BooleanCharacteristic.php#L27-L32 |
7,991 | pascalbaljetmedia/specifications | src/Matcher.php | Matcher.addCandidates | public function addCandidates($candidates): Matcher
{
$candidates = is_array($candidates) ? $candidates : func_get_args();
Collection::make($candidates)->each(function ($candidate) {
$this->addCandidate($candidate);
});
return $this;
} | php | public function addCandidates($candidates): Matcher
{
$candidates = is_array($candidates) ? $candidates : func_get_args();
Collection::make($candidates)->each(function ($candidate) {
$this->addCandidate($candidate);
});
return $this;
} | [
"public",
"function",
"addCandidates",
"(",
"$",
"candidates",
")",
":",
"Matcher",
"{",
"$",
"candidates",
"=",
"is_array",
"(",
"$",
"candidates",
")",
"?",
"$",
"candidates",
":",
"func_get_args",
"(",
")",
";",
"Collection",
"::",
"make",
"(",
"$",
"candidates",
")",
"->",
"each",
"(",
"function",
"(",
"$",
"candidate",
")",
"{",
"$",
"this",
"->",
"addCandidate",
"(",
"$",
"candidate",
")",
";",
"}",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Helper method to add multiple candidates at once.
@param mixed $candidates
@return $this | [
"Helper",
"method",
"to",
"add",
"multiple",
"candidates",
"at",
"once",
"."
] | ca3beb36affc9a6b3df0b786469c033cc02ad6fc | https://github.com/pascalbaljetmedia/specifications/blob/ca3beb36affc9a6b3df0b786469c033cc02ad6fc/src/Matcher.php#L49-L58 |
7,992 | pascalbaljetmedia/specifications | src/Matcher.php | Matcher.getScoresByAttribute | public function getScoresByAttribute(Attribute $attribute): Collection
{
return $this->candidates->map(function (CanBeSpecified $candidate) {
return $candidate->specifications();
})->map(function (SpecificationsInterface $specifications) use ($attribute) {
if (!$specifications->has($attribute)) {
return;
}
return $specifications->get($attribute)->getScoreValue();
});
} | php | public function getScoresByAttribute(Attribute $attribute): Collection
{
return $this->candidates->map(function (CanBeSpecified $candidate) {
return $candidate->specifications();
})->map(function (SpecificationsInterface $specifications) use ($attribute) {
if (!$specifications->has($attribute)) {
return;
}
return $specifications->get($attribute)->getScoreValue();
});
} | [
"public",
"function",
"getScoresByAttribute",
"(",
"Attribute",
"$",
"attribute",
")",
":",
"Collection",
"{",
"return",
"$",
"this",
"->",
"candidates",
"->",
"map",
"(",
"function",
"(",
"CanBeSpecified",
"$",
"candidate",
")",
"{",
"return",
"$",
"candidate",
"->",
"specifications",
"(",
")",
";",
"}",
")",
"->",
"map",
"(",
"function",
"(",
"SpecificationsInterface",
"$",
"specifications",
")",
"use",
"(",
"$",
"attribute",
")",
"{",
"if",
"(",
"!",
"$",
"specifications",
"->",
"has",
"(",
"$",
"attribute",
")",
")",
"{",
"return",
";",
"}",
"return",
"$",
"specifications",
"->",
"get",
"(",
"$",
"attribute",
")",
"->",
"getScoreValue",
"(",
")",
";",
"}",
")",
";",
"}"
] | Returns a collection where the keys matches the keys of the
candidates Collection but contain the score of the given
Attribute object.
@param \Pbmedia\Specifications\Interfaces\Attribute $attribute
@return \Illuminate\Support\Collection | [
"Returns",
"a",
"collection",
"where",
"the",
"keys",
"matches",
"the",
"keys",
"of",
"the",
"candidates",
"Collection",
"but",
"contain",
"the",
"score",
"of",
"the",
"given",
"Attribute",
"object",
"."
] | ca3beb36affc9a6b3df0b786469c033cc02ad6fc | https://github.com/pascalbaljetmedia/specifications/blob/ca3beb36affc9a6b3df0b786469c033cc02ad6fc/src/Matcher.php#L78-L89 |
7,993 | pascalbaljetmedia/specifications | src/Matcher.php | Matcher.getNormalizedScoresByAttribute | public function getNormalizedScoresByAttribute(Attribute $attribute): Collection
{
$scores = $this->getScoresByAttribute($attribute);
$max = $scores->max();
return $scores->map(function ($score) use ($max) {
return is_null($score) ? null : ($score / $max);
});
} | php | public function getNormalizedScoresByAttribute(Attribute $attribute): Collection
{
$scores = $this->getScoresByAttribute($attribute);
$max = $scores->max();
return $scores->map(function ($score) use ($max) {
return is_null($score) ? null : ($score / $max);
});
} | [
"public",
"function",
"getNormalizedScoresByAttribute",
"(",
"Attribute",
"$",
"attribute",
")",
":",
"Collection",
"{",
"$",
"scores",
"=",
"$",
"this",
"->",
"getScoresByAttribute",
"(",
"$",
"attribute",
")",
";",
"$",
"max",
"=",
"$",
"scores",
"->",
"max",
"(",
")",
";",
"return",
"$",
"scores",
"->",
"map",
"(",
"function",
"(",
"$",
"score",
")",
"use",
"(",
"$",
"max",
")",
"{",
"return",
"is_null",
"(",
"$",
"score",
")",
"?",
"null",
":",
"(",
"$",
"score",
"/",
"$",
"max",
")",
";",
"}",
")",
";",
"}"
] | This method does the same as the 'getScoresByAttribute' method
but has the scores normalized.
@param \Pbmedia\Specifications\Interfaces\Attribute $attribute
@return \Illuminate\Support\Collection | [
"This",
"method",
"does",
"the",
"same",
"as",
"the",
"getScoresByAttribute",
"method",
"but",
"has",
"the",
"scores",
"normalized",
"."
] | ca3beb36affc9a6b3df0b786469c033cc02ad6fc | https://github.com/pascalbaljetmedia/specifications/blob/ca3beb36affc9a6b3df0b786469c033cc02ad6fc/src/Matcher.php#L98-L107 |
7,994 | pascalbaljetmedia/specifications | src/Matcher.php | Matcher.getMatchingScoreByAttributeScore | public function getMatchingScoreByAttributeScore(AttributeScore $attributeScore): Collection
{
$attribute = $attributeScore->getAttribute();
$scoreValue = $attributeScore->getScoreValue();
$scores = $this->getScoresByAttribute($attribute);
if (!$scores->max()) {
return $this->candidates->map(function () {
return 0;
});
}
$scoreToCompareTo = $scoreValue / $scores->max();
return $this->getNormalizedScoresByAttribute($attribute)->map(function ($normalizedScore) use ($scoreToCompareTo) {
if ($normalizedScore === null) {
return null;
}
return 1 - abs($normalizedScore - $scoreToCompareTo);
});
} | php | public function getMatchingScoreByAttributeScore(AttributeScore $attributeScore): Collection
{
$attribute = $attributeScore->getAttribute();
$scoreValue = $attributeScore->getScoreValue();
$scores = $this->getScoresByAttribute($attribute);
if (!$scores->max()) {
return $this->candidates->map(function () {
return 0;
});
}
$scoreToCompareTo = $scoreValue / $scores->max();
return $this->getNormalizedScoresByAttribute($attribute)->map(function ($normalizedScore) use ($scoreToCompareTo) {
if ($normalizedScore === null) {
return null;
}
return 1 - abs($normalizedScore - $scoreToCompareTo);
});
} | [
"public",
"function",
"getMatchingScoreByAttributeScore",
"(",
"AttributeScore",
"$",
"attributeScore",
")",
":",
"Collection",
"{",
"$",
"attribute",
"=",
"$",
"attributeScore",
"->",
"getAttribute",
"(",
")",
";",
"$",
"scoreValue",
"=",
"$",
"attributeScore",
"->",
"getScoreValue",
"(",
")",
";",
"$",
"scores",
"=",
"$",
"this",
"->",
"getScoresByAttribute",
"(",
"$",
"attribute",
")",
";",
"if",
"(",
"!",
"$",
"scores",
"->",
"max",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"candidates",
"->",
"map",
"(",
"function",
"(",
")",
"{",
"return",
"0",
";",
"}",
")",
";",
"}",
"$",
"scoreToCompareTo",
"=",
"$",
"scoreValue",
"/",
"$",
"scores",
"->",
"max",
"(",
")",
";",
"return",
"$",
"this",
"->",
"getNormalizedScoresByAttribute",
"(",
"$",
"attribute",
")",
"->",
"map",
"(",
"function",
"(",
"$",
"normalizedScore",
")",
"use",
"(",
"$",
"scoreToCompareTo",
")",
"{",
"if",
"(",
"$",
"normalizedScore",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"1",
"-",
"abs",
"(",
"$",
"normalizedScore",
"-",
"$",
"scoreToCompareTo",
")",
";",
"}",
")",
";",
"}"
] | Returns a collection where the keys matches the keys of the
candidates Collection but contain the normalized score compaired
to the given AttributeScore.
@param \Pbmedia\Specifications\AttributeScore $attributeScore
@return \Illuminate\Support\Collection | [
"Returns",
"a",
"collection",
"where",
"the",
"keys",
"matches",
"the",
"keys",
"of",
"the",
"candidates",
"Collection",
"but",
"contain",
"the",
"normalized",
"score",
"compaired",
"to",
"the",
"given",
"AttributeScore",
"."
] | ca3beb36affc9a6b3df0b786469c033cc02ad6fc | https://github.com/pascalbaljetmedia/specifications/blob/ca3beb36affc9a6b3df0b786469c033cc02ad6fc/src/Matcher.php#L117-L139 |
7,995 | pascalbaljetmedia/specifications | src/Matcher.php | Matcher.get | public function get(): Collection
{
if ($this->specifications()->all()->isEmpty()) {
return $this->getCandidates();
}
$scores = [];
$this->specifications()->all()->map(function (AttributeScore $attributeScore) {
return $this->getMatchingScoreByAttributeScore($attributeScore);
})->each(function (Collection $matchingScoreByAttributeScore) use (&$scores) {
$matchingScoreByAttributeScore->each(function ($score, $productKey) use (&$scores) {
if (!isset($scores[$productKey])) {
$scores[$productKey] = 0;
}
$scores[$productKey] += $score;
});
});
return $this->getCandidates()->map(function (CanBeSpecified $candidate, $productKey) use ($scores) {
$score = $scores[$productKey];
return compact('candidate', 'score');
})->sortByDesc('score')->map(function ($candidateWithScore): CanBeSpecified {
return $candidateWithScore['candidate'];
})->values();
} | php | public function get(): Collection
{
if ($this->specifications()->all()->isEmpty()) {
return $this->getCandidates();
}
$scores = [];
$this->specifications()->all()->map(function (AttributeScore $attributeScore) {
return $this->getMatchingScoreByAttributeScore($attributeScore);
})->each(function (Collection $matchingScoreByAttributeScore) use (&$scores) {
$matchingScoreByAttributeScore->each(function ($score, $productKey) use (&$scores) {
if (!isset($scores[$productKey])) {
$scores[$productKey] = 0;
}
$scores[$productKey] += $score;
});
});
return $this->getCandidates()->map(function (CanBeSpecified $candidate, $productKey) use ($scores) {
$score = $scores[$productKey];
return compact('candidate', 'score');
})->sortByDesc('score')->map(function ($candidateWithScore): CanBeSpecified {
return $candidateWithScore['candidate'];
})->values();
} | [
"public",
"function",
"get",
"(",
")",
":",
"Collection",
"{",
"if",
"(",
"$",
"this",
"->",
"specifications",
"(",
")",
"->",
"all",
"(",
")",
"->",
"isEmpty",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getCandidates",
"(",
")",
";",
"}",
"$",
"scores",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"specifications",
"(",
")",
"->",
"all",
"(",
")",
"->",
"map",
"(",
"function",
"(",
"AttributeScore",
"$",
"attributeScore",
")",
"{",
"return",
"$",
"this",
"->",
"getMatchingScoreByAttributeScore",
"(",
"$",
"attributeScore",
")",
";",
"}",
")",
"->",
"each",
"(",
"function",
"(",
"Collection",
"$",
"matchingScoreByAttributeScore",
")",
"use",
"(",
"&",
"$",
"scores",
")",
"{",
"$",
"matchingScoreByAttributeScore",
"->",
"each",
"(",
"function",
"(",
"$",
"score",
",",
"$",
"productKey",
")",
"use",
"(",
"&",
"$",
"scores",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"scores",
"[",
"$",
"productKey",
"]",
")",
")",
"{",
"$",
"scores",
"[",
"$",
"productKey",
"]",
"=",
"0",
";",
"}",
"$",
"scores",
"[",
"$",
"productKey",
"]",
"+=",
"$",
"score",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"$",
"this",
"->",
"getCandidates",
"(",
")",
"->",
"map",
"(",
"function",
"(",
"CanBeSpecified",
"$",
"candidate",
",",
"$",
"productKey",
")",
"use",
"(",
"$",
"scores",
")",
"{",
"$",
"score",
"=",
"$",
"scores",
"[",
"$",
"productKey",
"]",
";",
"return",
"compact",
"(",
"'candidate'",
",",
"'score'",
")",
";",
"}",
")",
"->",
"sortByDesc",
"(",
"'score'",
")",
"->",
"map",
"(",
"function",
"(",
"$",
"candidateWithScore",
")",
":",
"CanBeSpecified",
"{",
"return",
"$",
"candidateWithScore",
"[",
"'candidate'",
"]",
";",
"}",
")",
"->",
"values",
"(",
")",
";",
"}"
] | Returns a collection where the candidaties are sorted based
on how close they are to the specifications.
@return \Illuminate\Support\Collection | [
"Returns",
"a",
"collection",
"where",
"the",
"candidaties",
"are",
"sorted",
"based",
"on",
"how",
"close",
"they",
"are",
"to",
"the",
"specifications",
"."
] | ca3beb36affc9a6b3df0b786469c033cc02ad6fc | https://github.com/pascalbaljetmedia/specifications/blob/ca3beb36affc9a6b3df0b786469c033cc02ad6fc/src/Matcher.php#L147-L174 |
7,996 | coolms/common | src/Form/View/Helper/FormCollection.php | FormCollection.renderElements | protected function renderElements(FieldsetInterface $fieldset)
{
$markup = '';
$elementHelper = $this->getElementHelper();
$elements = ArrayUtils::iteratorToArray($fieldset, false);
foreach ($elements as $key => $elementOrFieldset) {
if ($elementOrFieldset instanceof FieldsetInterface &&
$fieldset instanceof Collection
) {
$elementOrFieldset->setAttribute('data-counter', $key);
$elementOrFieldset->setOption(
'allow_remove',
$key >= $fieldset->getOption('count')
? $fieldset->allowRemove()
: false
);
}
$markup .= $elementHelper($elementOrFieldset);
}
$this->reset($fieldset);
return $markup;
} | php | protected function renderElements(FieldsetInterface $fieldset)
{
$markup = '';
$elementHelper = $this->getElementHelper();
$elements = ArrayUtils::iteratorToArray($fieldset, false);
foreach ($elements as $key => $elementOrFieldset) {
if ($elementOrFieldset instanceof FieldsetInterface &&
$fieldset instanceof Collection
) {
$elementOrFieldset->setAttribute('data-counter', $key);
$elementOrFieldset->setOption(
'allow_remove',
$key >= $fieldset->getOption('count')
? $fieldset->allowRemove()
: false
);
}
$markup .= $elementHelper($elementOrFieldset);
}
$this->reset($fieldset);
return $markup;
} | [
"protected",
"function",
"renderElements",
"(",
"FieldsetInterface",
"$",
"fieldset",
")",
"{",
"$",
"markup",
"=",
"''",
";",
"$",
"elementHelper",
"=",
"$",
"this",
"->",
"getElementHelper",
"(",
")",
";",
"$",
"elements",
"=",
"ArrayUtils",
"::",
"iteratorToArray",
"(",
"$",
"fieldset",
",",
"false",
")",
";",
"foreach",
"(",
"$",
"elements",
"as",
"$",
"key",
"=>",
"$",
"elementOrFieldset",
")",
"{",
"if",
"(",
"$",
"elementOrFieldset",
"instanceof",
"FieldsetInterface",
"&&",
"$",
"fieldset",
"instanceof",
"Collection",
")",
"{",
"$",
"elementOrFieldset",
"->",
"setAttribute",
"(",
"'data-counter'",
",",
"$",
"key",
")",
";",
"$",
"elementOrFieldset",
"->",
"setOption",
"(",
"'allow_remove'",
",",
"$",
"key",
">=",
"$",
"fieldset",
"->",
"getOption",
"(",
"'count'",
")",
"?",
"$",
"fieldset",
"->",
"allowRemove",
"(",
")",
":",
"false",
")",
";",
"}",
"$",
"markup",
".=",
"$",
"elementHelper",
"(",
"$",
"elementOrFieldset",
")",
";",
"}",
"$",
"this",
"->",
"reset",
"(",
"$",
"fieldset",
")",
";",
"return",
"$",
"markup",
";",
"}"
] | Render a collection by iterating through all
fieldsets and elements
@param FieldsetInterface $element
@return string | [
"Render",
"a",
"collection",
"by",
"iterating",
"through",
"all",
"fieldsets",
"and",
"elements"
] | 3572993cdcdb2898cdde396a2f1de9864b193660 | https://github.com/coolms/common/blob/3572993cdcdb2898cdde396a2f1de9864b193660/src/Form/View/Helper/FormCollection.php#L188-L213 |
7,997 | iwillhappy1314/wenprise-eloquent | src/Eloquent/Model.php | Model.belongsToMany | public function belongsToMany(
$related,
$table = null,
$foreignPivotKey = null,
$relatedPivotKey = null,
$parentKey = null,
$relatedKey = null,
$relation = null
) {
if (is_null($relation)) {
$relation = $this->guessBelongsToManyRelation();
}
$instance = $this->setInstanceConnection($this->newRelatedInstance($related));
$foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey();
$relatedPivotKey = $relatedPivotKey ?: $instance->getForeignKey();
if (is_null($table)) {
$table = $this->joiningTable($related);
}
$table = $this->getConnection()->db->prefix.$table;
return new BelongsToMany($instance->newQuery(), $this, $table, $foreignPivotKey, $relatedPivotKey, $parentKey ?: $this->getKeyName(), $relatedKey ?: $instance->getKeyName(), $relation);
} | php | public function belongsToMany(
$related,
$table = null,
$foreignPivotKey = null,
$relatedPivotKey = null,
$parentKey = null,
$relatedKey = null,
$relation = null
) {
if (is_null($relation)) {
$relation = $this->guessBelongsToManyRelation();
}
$instance = $this->setInstanceConnection($this->newRelatedInstance($related));
$foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey();
$relatedPivotKey = $relatedPivotKey ?: $instance->getForeignKey();
if (is_null($table)) {
$table = $this->joiningTable($related);
}
$table = $this->getConnection()->db->prefix.$table;
return new BelongsToMany($instance->newQuery(), $this, $table, $foreignPivotKey, $relatedPivotKey, $parentKey ?: $this->getKeyName(), $relatedKey ?: $instance->getKeyName(), $relation);
} | [
"public",
"function",
"belongsToMany",
"(",
"$",
"related",
",",
"$",
"table",
"=",
"null",
",",
"$",
"foreignPivotKey",
"=",
"null",
",",
"$",
"relatedPivotKey",
"=",
"null",
",",
"$",
"parentKey",
"=",
"null",
",",
"$",
"relatedKey",
"=",
"null",
",",
"$",
"relation",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"relation",
")",
")",
"{",
"$",
"relation",
"=",
"$",
"this",
"->",
"guessBelongsToManyRelation",
"(",
")",
";",
"}",
"$",
"instance",
"=",
"$",
"this",
"->",
"setInstanceConnection",
"(",
"$",
"this",
"->",
"newRelatedInstance",
"(",
"$",
"related",
")",
")",
";",
"$",
"foreignPivotKey",
"=",
"$",
"foreignPivotKey",
"?",
":",
"$",
"this",
"->",
"getForeignKey",
"(",
")",
";",
"$",
"relatedPivotKey",
"=",
"$",
"relatedPivotKey",
"?",
":",
"$",
"instance",
"->",
"getForeignKey",
"(",
")",
";",
"if",
"(",
"is_null",
"(",
"$",
"table",
")",
")",
"{",
"$",
"table",
"=",
"$",
"this",
"->",
"joiningTable",
"(",
"$",
"related",
")",
";",
"}",
"$",
"table",
"=",
"$",
"this",
"->",
"getConnection",
"(",
")",
"->",
"db",
"->",
"prefix",
".",
"$",
"table",
";",
"return",
"new",
"BelongsToMany",
"(",
"$",
"instance",
"->",
"newQuery",
"(",
")",
",",
"$",
"this",
",",
"$",
"table",
",",
"$",
"foreignPivotKey",
",",
"$",
"relatedPivotKey",
",",
"$",
"parentKey",
"?",
":",
"$",
"this",
"->",
"getKeyName",
"(",
")",
",",
"$",
"relatedKey",
"?",
":",
"$",
"instance",
"->",
"getKeyName",
"(",
")",
",",
"$",
"relation",
")",
";",
"}"
] | Replace the original belongsToMany function to forward the connection name.
@param string $related
@param string $table
@param string $foreignPivotKey
@param string $relatedPivotKey
@param string $parentKey
@param string $relatedKey
@param string $relation
@return BelongsToMany | [
"Replace",
"the",
"original",
"belongsToMany",
"function",
"to",
"forward",
"the",
"connection",
"name",
"."
] | 7eb045c7d19aaf5e7438625558a390ce39f1a34e | https://github.com/iwillhappy1314/wenprise-eloquent/blob/7eb045c7d19aaf5e7438625558a390ce39f1a34e/src/Eloquent/Model.php#L143-L169 |
7,998 | iwillhappy1314/wenprise-eloquent | src/Eloquent/Model.php | Model.getRelationValue | public function getRelationValue($key)
{
$relation = parent::getRelationValue($key);
if ($relation instanceof Collection) {
$relation->each(function ($model) {
$this->setRelationConnection($model);
});
return $relation;
}
$this->setRelationConnection($relation);
return $relation;
} | php | public function getRelationValue($key)
{
$relation = parent::getRelationValue($key);
if ($relation instanceof Collection) {
$relation->each(function ($model) {
$this->setRelationConnection($model);
});
return $relation;
}
$this->setRelationConnection($relation);
return $relation;
} | [
"public",
"function",
"getRelationValue",
"(",
"$",
"key",
")",
"{",
"$",
"relation",
"=",
"parent",
"::",
"getRelationValue",
"(",
"$",
"key",
")",
";",
"if",
"(",
"$",
"relation",
"instanceof",
"Collection",
")",
"{",
"$",
"relation",
"->",
"each",
"(",
"function",
"(",
"$",
"model",
")",
"{",
"$",
"this",
"->",
"setRelationConnection",
"(",
"$",
"model",
")",
";",
"}",
")",
";",
"return",
"$",
"relation",
";",
"}",
"$",
"this",
"->",
"setRelationConnection",
"(",
"$",
"relation",
")",
";",
"return",
"$",
"relation",
";",
"}"
] | Get the relation value setting the connection name.
@param string $key
@return mixed | [
"Get",
"the",
"relation",
"value",
"setting",
"the",
"connection",
"name",
"."
] | 7eb045c7d19aaf5e7438625558a390ce39f1a34e | https://github.com/iwillhappy1314/wenprise-eloquent/blob/7eb045c7d19aaf5e7438625558a390ce39f1a34e/src/Eloquent/Model.php#L177-L192 |
7,999 | konservs/brilliant.framework | libraries/MVC/BControllerField.php | BControllerField.getid | public function getid($id){
$n=strlen($id);
$i=0;
$arrname='';
while(($i<$n)&&($id[$i]!='[')){
$arrname.=$id[$i];
$i++;
}
if($id[$i]=='['){
$i++;
}
$appendix='';
$brackets=1;//opened brackets
while(($i<$n)&&($brackets>=0)){
if($id[$i]=='['){
$brackets++;
}
if($id[$i]==']'){
$brackets--;
}
$appendix.=$id[$i];
$i++;
}
if(strlen($appendix)>0){
$appendix=substr($appendix, 0, -1);
}
$name='bfields['.$arrname.']'.(empty($appendix)?'':'['.$appendix.']');
//echo('name="'.$name.'", id="'.$id.'"');
return $name;
} | php | public function getid($id){
$n=strlen($id);
$i=0;
$arrname='';
while(($i<$n)&&($id[$i]!='[')){
$arrname.=$id[$i];
$i++;
}
if($id[$i]=='['){
$i++;
}
$appendix='';
$brackets=1;//opened brackets
while(($i<$n)&&($brackets>=0)){
if($id[$i]=='['){
$brackets++;
}
if($id[$i]==']'){
$brackets--;
}
$appendix.=$id[$i];
$i++;
}
if(strlen($appendix)>0){
$appendix=substr($appendix, 0, -1);
}
$name='bfields['.$arrname.']'.(empty($appendix)?'':'['.$appendix.']');
//echo('name="'.$name.'", id="'.$id.'"');
return $name;
} | [
"public",
"function",
"getid",
"(",
"$",
"id",
")",
"{",
"$",
"n",
"=",
"strlen",
"(",
"$",
"id",
")",
";",
"$",
"i",
"=",
"0",
";",
"$",
"arrname",
"=",
"''",
";",
"while",
"(",
"(",
"$",
"i",
"<",
"$",
"n",
")",
"&&",
"(",
"$",
"id",
"[",
"$",
"i",
"]",
"!=",
"'['",
")",
")",
"{",
"$",
"arrname",
".=",
"$",
"id",
"[",
"$",
"i",
"]",
";",
"$",
"i",
"++",
";",
"}",
"if",
"(",
"$",
"id",
"[",
"$",
"i",
"]",
"==",
"'['",
")",
"{",
"$",
"i",
"++",
";",
"}",
"$",
"appendix",
"=",
"''",
";",
"$",
"brackets",
"=",
"1",
";",
"//opened brackets",
"while",
"(",
"(",
"$",
"i",
"<",
"$",
"n",
")",
"&&",
"(",
"$",
"brackets",
">=",
"0",
")",
")",
"{",
"if",
"(",
"$",
"id",
"[",
"$",
"i",
"]",
"==",
"'['",
")",
"{",
"$",
"brackets",
"++",
";",
"}",
"if",
"(",
"$",
"id",
"[",
"$",
"i",
"]",
"==",
"']'",
")",
"{",
"$",
"brackets",
"--",
";",
"}",
"$",
"appendix",
".=",
"$",
"id",
"[",
"$",
"i",
"]",
";",
"$",
"i",
"++",
";",
"}",
"if",
"(",
"strlen",
"(",
"$",
"appendix",
")",
">",
"0",
")",
"{",
"$",
"appendix",
"=",
"substr",
"(",
"$",
"appendix",
",",
"0",
",",
"-",
"1",
")",
";",
"}",
"$",
"name",
"=",
"'bfields['",
".",
"$",
"arrname",
".",
"']'",
".",
"(",
"empty",
"(",
"$",
"appendix",
")",
"?",
"''",
":",
"'['",
".",
"$",
"appendix",
".",
"']'",
")",
";",
"//echo('name=\"'.$name.'\", id=\"'.$id.'\"');",
"return",
"$",
"name",
";",
"}"
] | Generate admin key by field id.
Perform some converts:
catid -> bfields[catid]
tab[1][catid] -> bfields[tab][1][catid]
tab[1][ordering] -> bfields[tab][1][ordering] | [
"Generate",
"admin",
"key",
"by",
"field",
"id",
"."
] | 95f03f1917f746fee98bea8a906ba0588c87762d | https://github.com/konservs/brilliant.framework/blob/95f03f1917f746fee98bea8a906ba0588c87762d/libraries/MVC/BControllerField.php#L23-L54 |
Subsets and Splits