repo
stringlengths 6
63
| path
stringlengths 5
140
| func_name
stringlengths 3
151
| original_string
stringlengths 84
13k
| language
stringclasses 1
value | code
stringlengths 84
13k
| code_tokens
list | docstring
stringlengths 3
47.2k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 91
247
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
SlabPHP/router | src/Route.php | Route.validateDynamicPattern | public function validateDynamicPattern($path, &$debugInformation)
{
if (empty($this->pattern)) {
return false;
}
$value = $this->pattern->testPattern($path, $this->parameters, $debugInformation);
$this->validatedData = $this->pattern->getValidatedData();
return $value;
} | php | public function validateDynamicPattern($path, &$debugInformation)
{
if (empty($this->pattern)) {
return false;
}
$value = $this->pattern->testPattern($path, $this->parameters, $debugInformation);
$this->validatedData = $this->pattern->getValidatedData();
return $value;
} | [
"public",
"function",
"validateDynamicPattern",
"(",
"$",
"path",
",",
"&",
"$",
"debugInformation",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"pattern",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"value",
"=",
"$",
"this",
"->",
"pattern",
"->",
"testPattern",
"(",
"$",
"path",
",",
"$",
"this",
"->",
"parameters",
",",
"$",
"debugInformation",
")",
";",
"$",
"this",
"->",
"validatedData",
"=",
"$",
"this",
"->",
"pattern",
"->",
"getValidatedData",
"(",
")",
";",
"return",
"$",
"value",
";",
"}"
] | Validates a pattern against segments or a path
@param string $path
@param array $debugInformation
@return true | [
"Validates",
"a",
"pattern",
"against",
"segments",
"or",
"a",
"path"
] | 3e95fa07f694c0e2288a9e9a0ca106117f501a6e | https://github.com/SlabPHP/router/blob/3e95fa07f694c0e2288a9e9a0ca106117f501a6e/src/Route.php#L289-L300 | train |
Vectrex/vxPHP | src/Routing/Router.php | Router.setRoutes | public function setRoutes(array $routes) {
foreach($routes as $route) {
if(!$route instanceof Route) {
throw new \InvalidArgumentException(sprintf("'%s' is not a Route instance.", $route));
}
$this->addRoute($route);
}
} | php | public function setRoutes(array $routes) {
foreach($routes as $route) {
if(!$route instanceof Route) {
throw new \InvalidArgumentException(sprintf("'%s' is not a Route instance.", $route));
}
$this->addRoute($route);
}
} | [
"public",
"function",
"setRoutes",
"(",
"array",
"$",
"routes",
")",
"{",
"foreach",
"(",
"$",
"routes",
"as",
"$",
"route",
")",
"{",
"if",
"(",
"!",
"$",
"route",
"instanceof",
"Route",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"\"'%s' is not a Route instance.\"",
",",
"$",
"route",
")",
")",
";",
"}",
"$",
"this",
"->",
"addRoute",
"(",
"$",
"route",
")",
";",
"}",
"}"
] | assign routes to router
@param Route[] $routes | [
"assign",
"routes",
"to",
"router"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Routing/Router.php#L89-L101 | train |
Vectrex/vxPHP | src/Routing/Router.php | Router.addRoute | public function addRoute(Route $route) {
$id = $route->getRouteId();
if(array_key_exists($id, $this->routes)) {
throw new \InvalidArgumentException(sprintf("Route with id '%s' already exists.", $id));
}
$this->routes[$id] = $route;
} | php | public function addRoute(Route $route) {
$id = $route->getRouteId();
if(array_key_exists($id, $this->routes)) {
throw new \InvalidArgumentException(sprintf("Route with id '%s' already exists.", $id));
}
$this->routes[$id] = $route;
} | [
"public",
"function",
"addRoute",
"(",
"Route",
"$",
"route",
")",
"{",
"$",
"id",
"=",
"$",
"route",
"->",
"getRouteId",
"(",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"id",
",",
"$",
"this",
"->",
"routes",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"\"Route with id '%s' already exists.\"",
",",
"$",
"id",
")",
")",
";",
"}",
"$",
"this",
"->",
"routes",
"[",
"$",
"id",
"]",
"=",
"$",
"route",
";",
"}"
] | add a single route to router
throws an exception when route has already been assigned
@param Route $route | [
"add",
"a",
"single",
"route",
"to",
"router",
"throws",
"an",
"exception",
"when",
"route",
"has",
"already",
"been",
"assigned"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Routing/Router.php#L109-L120 | train |
Vectrex/vxPHP | src/Routing/Router.php | Router.getRouteFromPathInfo | public function getRouteFromPathInfo(Request $request) {
$application = Application::getInstance();
$script = basename($request->getScriptName());
if(!($path = trim($request->getPathInfo(), '/'))) {
$pathSegments = [];
}
else {
$pathSegments = explode('/' , $path);
}
// skip if pathinfo matches script name
if(count($pathSegments) && $this->serverSideRewrite && basename($script, '.php') === $pathSegments[0]) {
array_shift($pathSegments);
}
// when locale is found, set it as current locale in application and skip it
if(count($pathSegments) && $application->hasLocale($pathSegments[0])) {
$application->setCurrentLocale($application->getLocale($pathSegments[0]));
array_shift($pathSegments);
}
// find route
$route = $this->findRoute($pathSegments);
// no route found
if(!$route) {
throw new ApplicationException(sprintf("No route found for path '%s'.", implode('/', $pathSegments)));
}
while(!$this->authenticateRoute($route)) {
$route = $this->authenticator->handleViolation($route);
}
return $route;
} | php | public function getRouteFromPathInfo(Request $request) {
$application = Application::getInstance();
$script = basename($request->getScriptName());
if(!($path = trim($request->getPathInfo(), '/'))) {
$pathSegments = [];
}
else {
$pathSegments = explode('/' , $path);
}
// skip if pathinfo matches script name
if(count($pathSegments) && $this->serverSideRewrite && basename($script, '.php') === $pathSegments[0]) {
array_shift($pathSegments);
}
// when locale is found, set it as current locale in application and skip it
if(count($pathSegments) && $application->hasLocale($pathSegments[0])) {
$application->setCurrentLocale($application->getLocale($pathSegments[0]));
array_shift($pathSegments);
}
// find route
$route = $this->findRoute($pathSegments);
// no route found
if(!$route) {
throw new ApplicationException(sprintf("No route found for path '%s'.", implode('/', $pathSegments)));
}
while(!$this->authenticateRoute($route)) {
$route = $this->authenticator->handleViolation($route);
}
return $route;
} | [
"public",
"function",
"getRouteFromPathInfo",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"application",
"=",
"Application",
"::",
"getInstance",
"(",
")",
";",
"$",
"script",
"=",
"basename",
"(",
"$",
"request",
"->",
"getScriptName",
"(",
")",
")",
";",
"if",
"(",
"!",
"(",
"$",
"path",
"=",
"trim",
"(",
"$",
"request",
"->",
"getPathInfo",
"(",
")",
",",
"'/'",
")",
")",
")",
"{",
"$",
"pathSegments",
"=",
"[",
"]",
";",
"}",
"else",
"{",
"$",
"pathSegments",
"=",
"explode",
"(",
"'/'",
",",
"$",
"path",
")",
";",
"}",
"// skip if pathinfo matches script name",
"if",
"(",
"count",
"(",
"$",
"pathSegments",
")",
"&&",
"$",
"this",
"->",
"serverSideRewrite",
"&&",
"basename",
"(",
"$",
"script",
",",
"'.php'",
")",
"===",
"$",
"pathSegments",
"[",
"0",
"]",
")",
"{",
"array_shift",
"(",
"$",
"pathSegments",
")",
";",
"}",
"// when locale is found, set it as current locale in application and skip it",
"if",
"(",
"count",
"(",
"$",
"pathSegments",
")",
"&&",
"$",
"application",
"->",
"hasLocale",
"(",
"$",
"pathSegments",
"[",
"0",
"]",
")",
")",
"{",
"$",
"application",
"->",
"setCurrentLocale",
"(",
"$",
"application",
"->",
"getLocale",
"(",
"$",
"pathSegments",
"[",
"0",
"]",
")",
")",
";",
"array_shift",
"(",
"$",
"pathSegments",
")",
";",
"}",
"// find route",
"$",
"route",
"=",
"$",
"this",
"->",
"findRoute",
"(",
"$",
"pathSegments",
")",
";",
"// no route found",
"if",
"(",
"!",
"$",
"route",
")",
"{",
"throw",
"new",
"ApplicationException",
"(",
"sprintf",
"(",
"\"No route found for path '%s'.\"",
",",
"implode",
"(",
"'/'",
",",
"$",
"pathSegments",
")",
")",
")",
";",
"}",
"while",
"(",
"!",
"$",
"this",
"->",
"authenticateRoute",
"(",
"$",
"route",
")",
")",
"{",
"$",
"route",
"=",
"$",
"this",
"->",
"authenticator",
"->",
"handleViolation",
"(",
"$",
"route",
")",
";",
"}",
"return",
"$",
"route",
";",
"}"
] | analyse path and return route associated with it
the first path fragment can be a locale string,
which is then skipped for determining the route
configured routes are first checked whether they fulfill the
request method and whether they match the path
if more than one route matches these requirements the one which
is more specific about the request method is preferred
if more than one route match the requirements and are equally
specific about the request methods the one with less
placeholders is preferred
if more than one match the requirements, are equally specific
about request methods and have the same number of placeholders
the one with more satisfied placeholders is preferred
@return \vxPHP\Routing\Route
@throws \vxPHP\Application\Exception\ApplicationException | [
"analyse",
"path",
"and",
"return",
"route",
"associated",
"with",
"it",
"the",
"first",
"path",
"fragment",
"can",
"be",
"a",
"locale",
"string",
"which",
"is",
"then",
"skipped",
"for",
"determining",
"the",
"route"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Routing/Router.php#L156-L197 | train |
Vectrex/vxPHP | src/Routing/Router.php | Router.getRoute | public function getRoute($routeId) {
if(!array_key_exists($routeId, $this->routes)) {
throw new ApplicationException(sprintf("No route with id '%s' configured.", $routeId));
}
return $this->routes[$routeId];
} | php | public function getRoute($routeId) {
if(!array_key_exists($routeId, $this->routes)) {
throw new ApplicationException(sprintf("No route with id '%s' configured.", $routeId));
}
return $this->routes[$routeId];
} | [
"public",
"function",
"getRoute",
"(",
"$",
"routeId",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"routeId",
",",
"$",
"this",
"->",
"routes",
")",
")",
"{",
"throw",
"new",
"ApplicationException",
"(",
"sprintf",
"(",
"\"No route with id '%s' configured.\"",
",",
"$",
"routeId",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"routes",
"[",
"$",
"routeId",
"]",
";",
"}"
] | get a route identified by its id
@param string $routeId
@return \vxPHP\Routing\Route
@throws \vxPHP\Application\Exception\ApplicationException | [
"get",
"a",
"route",
"identified",
"by",
"its",
"id"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Routing/Router.php#L207-L215 | train |
Vectrex/vxPHP | src/Routing/Router.php | Router.findRoute | private function findRoute(array $pathSegments = null) {
if(!count($this->routes)) {
throw new ApplicationException('Routing aborted: No routes defined.');
}
// if no page given try to get the first from list
if(empty($pathSegments)) {
return reset($this->routes);
}
$pathToCheck = implode('/', $pathSegments);
$requestMethod = Request::createFromGlobals()->getMethod();
/* @var Route $foundRoute */
$foundRoute = null;
/* @var Route $default */
$default = null;
// iterate over routes and try to find the "best" match
/* @var Route $route */
foreach($this->routes as $route) {
// keep default route as fallback, when no match is found
if($route->getRouteId() === 'default') {
$default = $route;
}
// pick route only when request method requirement is met
if(
preg_match('~^' . $route->getMatchExpression() . '$~', $pathToCheck) &&
$route->allowsRequestMethod($requestMethod)
) {
// if no route was found yet, pick this first match
if(!isset($foundRoute)) {
$foundRoute = $route;
continue;
}
// prefer route which is more specific with request methods
if(count($route->getRequestMethods()) > count($foundRoute->getRequestMethods())) {
continue;
}
// a route with less (or no) placeholders is preferred over one with placeholders
if(count($route->getPlaceholderNames()) > count($foundRoute->getPlaceholderNames())) {
continue;
}
// if a route has been found previously, choose the more "precise" and/or later one
// choose the route with more satisfied placeholders
// @todo could be optimized
$foundRouteSatisfiedPlaceholderCount = count($this->getSatisfiedPlaceholders($foundRoute, $pathToCheck));
$routeSatisfiedPlaceholderCount = count($this->getSatisfiedPlaceholders($route, $pathToCheck));
if (
($routeSatisfiedPlaceholderCount - count($route->getPlaceholderNames())) < ($foundRouteSatisfiedPlaceholderCount - count($foundRoute->getPlaceholderNames()))
) {
continue;
}
if (
($routeSatisfiedPlaceholderCount - count($route->getPlaceholderNames())) === ($foundRouteSatisfiedPlaceholderCount - count($foundRoute->getPlaceholderNames())) &&
count($route->getPlaceholderNames()) > count($foundRoute->getPlaceholderNames())
) {
continue;
}
$foundRoute = $route;
}
}
// return "normal" route, if found
if(isset($foundRoute)) {
return $foundRoute;
}
// return default route as fallback (if available)
return $default;
} | php | private function findRoute(array $pathSegments = null) {
if(!count($this->routes)) {
throw new ApplicationException('Routing aborted: No routes defined.');
}
// if no page given try to get the first from list
if(empty($pathSegments)) {
return reset($this->routes);
}
$pathToCheck = implode('/', $pathSegments);
$requestMethod = Request::createFromGlobals()->getMethod();
/* @var Route $foundRoute */
$foundRoute = null;
/* @var Route $default */
$default = null;
// iterate over routes and try to find the "best" match
/* @var Route $route */
foreach($this->routes as $route) {
// keep default route as fallback, when no match is found
if($route->getRouteId() === 'default') {
$default = $route;
}
// pick route only when request method requirement is met
if(
preg_match('~^' . $route->getMatchExpression() . '$~', $pathToCheck) &&
$route->allowsRequestMethod($requestMethod)
) {
// if no route was found yet, pick this first match
if(!isset($foundRoute)) {
$foundRoute = $route;
continue;
}
// prefer route which is more specific with request methods
if(count($route->getRequestMethods()) > count($foundRoute->getRequestMethods())) {
continue;
}
// a route with less (or no) placeholders is preferred over one with placeholders
if(count($route->getPlaceholderNames()) > count($foundRoute->getPlaceholderNames())) {
continue;
}
// if a route has been found previously, choose the more "precise" and/or later one
// choose the route with more satisfied placeholders
// @todo could be optimized
$foundRouteSatisfiedPlaceholderCount = count($this->getSatisfiedPlaceholders($foundRoute, $pathToCheck));
$routeSatisfiedPlaceholderCount = count($this->getSatisfiedPlaceholders($route, $pathToCheck));
if (
($routeSatisfiedPlaceholderCount - count($route->getPlaceholderNames())) < ($foundRouteSatisfiedPlaceholderCount - count($foundRoute->getPlaceholderNames()))
) {
continue;
}
if (
($routeSatisfiedPlaceholderCount - count($route->getPlaceholderNames())) === ($foundRouteSatisfiedPlaceholderCount - count($foundRoute->getPlaceholderNames())) &&
count($route->getPlaceholderNames()) > count($foundRoute->getPlaceholderNames())
) {
continue;
}
$foundRoute = $route;
}
}
// return "normal" route, if found
if(isset($foundRoute)) {
return $foundRoute;
}
// return default route as fallback (if available)
return $default;
} | [
"private",
"function",
"findRoute",
"(",
"array",
"$",
"pathSegments",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"count",
"(",
"$",
"this",
"->",
"routes",
")",
")",
"{",
"throw",
"new",
"ApplicationException",
"(",
"'Routing aborted: No routes defined.'",
")",
";",
"}",
"// if no page given try to get the first from list",
"if",
"(",
"empty",
"(",
"$",
"pathSegments",
")",
")",
"{",
"return",
"reset",
"(",
"$",
"this",
"->",
"routes",
")",
";",
"}",
"$",
"pathToCheck",
"=",
"implode",
"(",
"'/'",
",",
"$",
"pathSegments",
")",
";",
"$",
"requestMethod",
"=",
"Request",
"::",
"createFromGlobals",
"(",
")",
"->",
"getMethod",
"(",
")",
";",
"/* @var Route $foundRoute */",
"$",
"foundRoute",
"=",
"null",
";",
"/* @var Route $default */",
"$",
"default",
"=",
"null",
";",
"// iterate over routes and try to find the \"best\" match",
"/* @var Route $route */",
"foreach",
"(",
"$",
"this",
"->",
"routes",
"as",
"$",
"route",
")",
"{",
"// keep default route as fallback, when no match is found",
"if",
"(",
"$",
"route",
"->",
"getRouteId",
"(",
")",
"===",
"'default'",
")",
"{",
"$",
"default",
"=",
"$",
"route",
";",
"}",
"// pick route only when request method requirement is met",
"if",
"(",
"preg_match",
"(",
"'~^'",
".",
"$",
"route",
"->",
"getMatchExpression",
"(",
")",
".",
"'$~'",
",",
"$",
"pathToCheck",
")",
"&&",
"$",
"route",
"->",
"allowsRequestMethod",
"(",
"$",
"requestMethod",
")",
")",
"{",
"// if no route was found yet, pick this first match",
"if",
"(",
"!",
"isset",
"(",
"$",
"foundRoute",
")",
")",
"{",
"$",
"foundRoute",
"=",
"$",
"route",
";",
"continue",
";",
"}",
"// prefer route which is more specific with request methods",
"if",
"(",
"count",
"(",
"$",
"route",
"->",
"getRequestMethods",
"(",
")",
")",
">",
"count",
"(",
"$",
"foundRoute",
"->",
"getRequestMethods",
"(",
")",
")",
")",
"{",
"continue",
";",
"}",
"// a route with less (or no) placeholders is preferred over one with placeholders",
"if",
"(",
"count",
"(",
"$",
"route",
"->",
"getPlaceholderNames",
"(",
")",
")",
">",
"count",
"(",
"$",
"foundRoute",
"->",
"getPlaceholderNames",
"(",
")",
")",
")",
"{",
"continue",
";",
"}",
"// if a route has been found previously, choose the more \"precise\" and/or later one",
"// choose the route with more satisfied placeholders",
"// @todo could be optimized",
"$",
"foundRouteSatisfiedPlaceholderCount",
"=",
"count",
"(",
"$",
"this",
"->",
"getSatisfiedPlaceholders",
"(",
"$",
"foundRoute",
",",
"$",
"pathToCheck",
")",
")",
";",
"$",
"routeSatisfiedPlaceholderCount",
"=",
"count",
"(",
"$",
"this",
"->",
"getSatisfiedPlaceholders",
"(",
"$",
"route",
",",
"$",
"pathToCheck",
")",
")",
";",
"if",
"(",
"(",
"$",
"routeSatisfiedPlaceholderCount",
"-",
"count",
"(",
"$",
"route",
"->",
"getPlaceholderNames",
"(",
")",
")",
")",
"<",
"(",
"$",
"foundRouteSatisfiedPlaceholderCount",
"-",
"count",
"(",
"$",
"foundRoute",
"->",
"getPlaceholderNames",
"(",
")",
")",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"(",
"$",
"routeSatisfiedPlaceholderCount",
"-",
"count",
"(",
"$",
"route",
"->",
"getPlaceholderNames",
"(",
")",
")",
")",
"===",
"(",
"$",
"foundRouteSatisfiedPlaceholderCount",
"-",
"count",
"(",
"$",
"foundRoute",
"->",
"getPlaceholderNames",
"(",
")",
")",
")",
"&&",
"count",
"(",
"$",
"route",
"->",
"getPlaceholderNames",
"(",
")",
")",
">",
"count",
"(",
"$",
"foundRoute",
"->",
"getPlaceholderNames",
"(",
")",
")",
")",
"{",
"continue",
";",
"}",
"$",
"foundRoute",
"=",
"$",
"route",
";",
"}",
"}",
"// return \"normal\" route, if found",
"if",
"(",
"isset",
"(",
"$",
"foundRoute",
")",
")",
"{",
"return",
"$",
"foundRoute",
";",
"}",
"// return default route as fallback (if available)",
"return",
"$",
"default",
";",
"}"
] | find route which best matches the passed path segments
@param array $pathSegments
@return \vxPHP\Routing\Route
@throws \vxPHP\Application\Exception\ApplicationException | [
"find",
"route",
"which",
"best",
"matches",
"the",
"passed",
"path",
"segments"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Routing/Router.php#L249-L344 | train |
Vectrex/vxPHP | src/Routing/Router.php | Router.authenticateRoute | private function authenticateRoute(Route $route) {
$auth = $route->getAuth();
// authentication required?
if(is_null($auth)) {
return true;
}
if(!$this->authenticator) {
$this->authenticator = new DefaultRouteAuthenticator();
}
return $this->authenticator->authenticate($route, Application::getInstance()->getCurrentUser());
} | php | private function authenticateRoute(Route $route) {
$auth = $route->getAuth();
// authentication required?
if(is_null($auth)) {
return true;
}
if(!$this->authenticator) {
$this->authenticator = new DefaultRouteAuthenticator();
}
return $this->authenticator->authenticate($route, Application::getInstance()->getCurrentUser());
} | [
"private",
"function",
"authenticateRoute",
"(",
"Route",
"$",
"route",
")",
"{",
"$",
"auth",
"=",
"$",
"route",
"->",
"getAuth",
"(",
")",
";",
"// authentication required?",
"if",
"(",
"is_null",
"(",
"$",
"auth",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"authenticator",
")",
"{",
"$",
"this",
"->",
"authenticator",
"=",
"new",
"DefaultRouteAuthenticator",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"authenticator",
"->",
"authenticate",
"(",
"$",
"route",
",",
"Application",
"::",
"getInstance",
"(",
")",
"->",
"getCurrentUser",
"(",
")",
")",
";",
"}"
] | check whether authentication level required by route is met by
currently active user
@param Route $route
@return boolean
@throws \vxPHP\Application\Exception\ApplicationException | [
"check",
"whether",
"authentication",
"level",
"required",
"by",
"route",
"is",
"met",
"by",
"currently",
"active",
"user"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Routing/Router.php#L354-L374 | train |
Vectrex/vxPHP | src/Routing/Router.php | Router.getSatisfiedPlaceholders | private function getSatisfiedPlaceholders($route, $path) {
$placeholderNames = $route->getPlaceholderNames();
if(!empty($placeholderNames)) {
if(preg_match('~(?:/|^)' . $route->getMatchExpression() .'(?:/|$)~', $path, $matches)) {
array_shift($matches);
return array_combine(array_slice($placeholderNames, 0, count($matches)), $matches);
}
}
return [];
} | php | private function getSatisfiedPlaceholders($route, $path) {
$placeholderNames = $route->getPlaceholderNames();
if(!empty($placeholderNames)) {
if(preg_match('~(?:/|^)' . $route->getMatchExpression() .'(?:/|$)~', $path, $matches)) {
array_shift($matches);
return array_combine(array_slice($placeholderNames, 0, count($matches)), $matches);
}
}
return [];
} | [
"private",
"function",
"getSatisfiedPlaceholders",
"(",
"$",
"route",
",",
"$",
"path",
")",
"{",
"$",
"placeholderNames",
"=",
"$",
"route",
"->",
"getPlaceholderNames",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"placeholderNames",
")",
")",
"{",
"if",
"(",
"preg_match",
"(",
"'~(?:/|^)'",
".",
"$",
"route",
"->",
"getMatchExpression",
"(",
")",
".",
"'(?:/|$)~'",
",",
"$",
"path",
",",
"$",
"matches",
")",
")",
"{",
"array_shift",
"(",
"$",
"matches",
")",
";",
"return",
"array_combine",
"(",
"array_slice",
"(",
"$",
"placeholderNames",
",",
"0",
",",
"count",
"(",
"$",
"matches",
")",
")",
",",
"$",
"matches",
")",
";",
"}",
"}",
"return",
"[",
"]",
";",
"}"
] | check path against placeholders of route
and return associative array with placeholders which would have a value assigned
@param Route $route
@param string $path
@return array | [
"check",
"path",
"against",
"placeholders",
"of",
"route",
"and",
"return",
"associative",
"array",
"with",
"placeholders",
"which",
"would",
"have",
"a",
"value",
"assigned"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Routing/Router.php#L384-L398 | train |
Ydle/HubBundle | Manager/LogsManager.php | LogsManager.log | public function log($type, $text, $source='')
{
$log = new Logs();
$log->setType($type);
$log->setSource($source);
$log->setContent($text);
$this->em->persist($log);
$this->em->flush();
return $log;
} | php | public function log($type, $text, $source='')
{
$log = new Logs();
$log->setType($type);
$log->setSource($source);
$log->setContent($text);
$this->em->persist($log);
$this->em->flush();
return $log;
} | [
"public",
"function",
"log",
"(",
"$",
"type",
",",
"$",
"text",
",",
"$",
"source",
"=",
"''",
")",
"{",
"$",
"log",
"=",
"new",
"Logs",
"(",
")",
";",
"$",
"log",
"->",
"setType",
"(",
"$",
"type",
")",
";",
"$",
"log",
"->",
"setSource",
"(",
"$",
"source",
")",
";",
"$",
"log",
"->",
"setContent",
"(",
"$",
"text",
")",
";",
"$",
"this",
"->",
"em",
"->",
"persist",
"(",
"$",
"log",
")",
";",
"$",
"this",
"->",
"em",
"->",
"flush",
"(",
")",
";",
"return",
"$",
"log",
";",
"}"
] | Save a log in database
@param string $type
@param string $text
@return Logs | [
"Save",
"a",
"log",
"in",
"database"
] | 7fa423241246bcfd115f2ed3ad3997b4b63adb01 | https://github.com/Ydle/HubBundle/blob/7fa423241246bcfd115f2ed3ad3997b4b63adb01/Manager/LogsManager.php#L72-L83 | train |
agroff/Command | src/Groff/Command/Command.php | Command.run | final public function run()
{
$this->notify("run");
$this->addOptions();
$this->notify("options added");
$this->populateOptions();
$this->addHelpCommand();
$this->notify("options available");
if ($this->option("help")) {
return $this->printHelp();
}
$this->notify("pre main");
try {
$status = $this->main();
} catch (\Exception $e) {
$status = $this->catchMainException($e);
}
$this->notify("shutdown");
return $status;
} | php | final public function run()
{
$this->notify("run");
$this->addOptions();
$this->notify("options added");
$this->populateOptions();
$this->addHelpCommand();
$this->notify("options available");
if ($this->option("help")) {
return $this->printHelp();
}
$this->notify("pre main");
try {
$status = $this->main();
} catch (\Exception $e) {
$status = $this->catchMainException($e);
}
$this->notify("shutdown");
return $status;
} | [
"final",
"public",
"function",
"run",
"(",
")",
"{",
"$",
"this",
"->",
"notify",
"(",
"\"run\"",
")",
";",
"$",
"this",
"->",
"addOptions",
"(",
")",
";",
"$",
"this",
"->",
"notify",
"(",
"\"options added\"",
")",
";",
"$",
"this",
"->",
"populateOptions",
"(",
")",
";",
"$",
"this",
"->",
"addHelpCommand",
"(",
")",
";",
"$",
"this",
"->",
"notify",
"(",
"\"options available\"",
")",
";",
"if",
"(",
"$",
"this",
"->",
"option",
"(",
"\"help\"",
")",
")",
"{",
"return",
"$",
"this",
"->",
"printHelp",
"(",
")",
";",
"}",
"$",
"this",
"->",
"notify",
"(",
"\"pre main\"",
")",
";",
"try",
"{",
"$",
"status",
"=",
"$",
"this",
"->",
"main",
"(",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"$",
"status",
"=",
"$",
"this",
"->",
"catchMainException",
"(",
"$",
"e",
")",
";",
"}",
"$",
"this",
"->",
"notify",
"(",
"\"shutdown\"",
")",
";",
"return",
"$",
"status",
";",
"}"
] | This is an instance of the template method pattern. It runs the entire Cli Command
but leaves the `main` method abstract to ensure it is implemented in the
subclass. An optional addOptions hook is also provided here.
@return int Status code. 0 for success, other values indicate an error. | [
"This",
"is",
"an",
"instance",
"of",
"the",
"template",
"method",
"pattern",
".",
"It",
"runs",
"the",
"entire",
"Cli",
"Command",
"but",
"leaves",
"the",
"main",
"method",
"abstract",
"to",
"ensure",
"it",
"is",
"implemented",
"in",
"the",
"subclass",
".",
"An",
"optional",
"addOptions",
"hook",
"is",
"also",
"provided",
"here",
"."
] | e71d3af3cfbf83f7fca9aa89e9b4bf03dc9f4c40 | https://github.com/agroff/Command/blob/e71d3af3cfbf83f7fca9aa89e9b4bf03dc9f4c40/src/Groff/Command/Command.php#L98-L127 | train |
agroff/Command | src/Groff/Command/Command.php | Command.option | final public function option($query)
{
try {
$option = $this->options->find($query);
$value = $option->getValue();
} catch (ObjectDoesNotExistException $e) {
$value = false;
}
return $value;
} | php | final public function option($query)
{
try {
$option = $this->options->find($query);
$value = $option->getValue();
} catch (ObjectDoesNotExistException $e) {
$value = false;
}
return $value;
} | [
"final",
"public",
"function",
"option",
"(",
"$",
"query",
")",
"{",
"try",
"{",
"$",
"option",
"=",
"$",
"this",
"->",
"options",
"->",
"find",
"(",
"$",
"query",
")",
";",
"$",
"value",
"=",
"$",
"option",
"->",
"getValue",
"(",
")",
";",
"}",
"catch",
"(",
"ObjectDoesNotExistException",
"$",
"e",
")",
"{",
"$",
"value",
"=",
"false",
";",
"}",
"return",
"$",
"value",
";",
"}"
] | Returns an option's value. Facade of OptionCollection.
@param $query string An option's name or alias
@return mixed | [
"Returns",
"an",
"option",
"s",
"value",
".",
"Facade",
"of",
"OptionCollection",
"."
] | e71d3af3cfbf83f7fca9aa89e9b4bf03dc9f4c40 | https://github.com/agroff/Command/blob/e71d3af3cfbf83f7fca9aa89e9b4bf03dc9f4c40/src/Groff/Command/Command.php#L161-L172 | train |
agroff/Command | src/Groff/Command/Command.php | Command.getRawOptions | protected function getRawOptions()
{
global $argv;
if (!is_array($this->rawOptions)) {
$this->setRawOptions($argv);
}
return $this->rawOptions;
} | php | protected function getRawOptions()
{
global $argv;
if (!is_array($this->rawOptions)) {
$this->setRawOptions($argv);
}
return $this->rawOptions;
} | [
"protected",
"function",
"getRawOptions",
"(",
")",
"{",
"global",
"$",
"argv",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"this",
"->",
"rawOptions",
")",
")",
"{",
"$",
"this",
"->",
"setRawOptions",
"(",
"$",
"argv",
")",
";",
"}",
"return",
"$",
"this",
"->",
"rawOptions",
";",
"}"
] | Provides CLI arguments. Abstracted since it uses an ugly global variable.
Also allows a subclass to provide its own options.
@return array | [
"Provides",
"CLI",
"arguments",
".",
"Abstracted",
"since",
"it",
"uses",
"an",
"ugly",
"global",
"variable",
".",
"Also",
"allows",
"a",
"subclass",
"to",
"provide",
"its",
"own",
"options",
"."
] | e71d3af3cfbf83f7fca9aa89e9b4bf03dc9f4c40 | https://github.com/agroff/Command/blob/e71d3af3cfbf83f7fca9aa89e9b4bf03dc9f4c40/src/Groff/Command/Command.php#L226-L235 | train |
agroff/Command | src/Groff/Command/Command.php | Command.populateOptions | private function populateOptions()
{
$flatOptions = $this->getRawOptions();
$this->parser->parseInput($flatOptions);
$parsed = $this->parser->getOptions();
foreach ($parsed as $optionName => $optionValue) {
//ignores any options the user sent which were not defined
$this->options->setValueIfExists($optionName, $optionValue);
}
} | php | private function populateOptions()
{
$flatOptions = $this->getRawOptions();
$this->parser->parseInput($flatOptions);
$parsed = $this->parser->getOptions();
foreach ($parsed as $optionName => $optionValue) {
//ignores any options the user sent which were not defined
$this->options->setValueIfExists($optionName, $optionValue);
}
} | [
"private",
"function",
"populateOptions",
"(",
")",
"{",
"$",
"flatOptions",
"=",
"$",
"this",
"->",
"getRawOptions",
"(",
")",
";",
"$",
"this",
"->",
"parser",
"->",
"parseInput",
"(",
"$",
"flatOptions",
")",
";",
"$",
"parsed",
"=",
"$",
"this",
"->",
"parser",
"->",
"getOptions",
"(",
")",
";",
"foreach",
"(",
"$",
"parsed",
"as",
"$",
"optionName",
"=>",
"$",
"optionValue",
")",
"{",
"//ignores any options the user sent which were not defined",
"$",
"this",
"->",
"options",
"->",
"setValueIfExists",
"(",
"$",
"optionName",
",",
"$",
"optionValue",
")",
";",
"}",
"}"
] | Gets parsed options and uses them to populate options in the options collection | [
"Gets",
"parsed",
"options",
"and",
"uses",
"them",
"to",
"populate",
"options",
"in",
"the",
"options",
"collection"
] | e71d3af3cfbf83f7fca9aa89e9b4bf03dc9f4c40 | https://github.com/agroff/Command/blob/e71d3af3cfbf83f7fca9aa89e9b4bf03dc9f4c40/src/Groff/Command/Command.php#L245-L257 | train |
agroff/Command | src/Groff/Command/Command.php | Command.printHelp | final protected function printHelp()
{
$script = $this->parser->getScriptName();
$this->printUsage($script);
$this->printDescription();
/** @var $option Option */
foreach ($this->options as $option) {
echo " " . $option . "\n";
}
echo "\n";
$this->notify("output");
$this->notify("shutdown");
return 0;
} | php | final protected function printHelp()
{
$script = $this->parser->getScriptName();
$this->printUsage($script);
$this->printDescription();
/** @var $option Option */
foreach ($this->options as $option) {
echo " " . $option . "\n";
}
echo "\n";
$this->notify("output");
$this->notify("shutdown");
return 0;
} | [
"final",
"protected",
"function",
"printHelp",
"(",
")",
"{",
"$",
"script",
"=",
"$",
"this",
"->",
"parser",
"->",
"getScriptName",
"(",
")",
";",
"$",
"this",
"->",
"printUsage",
"(",
"$",
"script",
")",
";",
"$",
"this",
"->",
"printDescription",
"(",
")",
";",
"/** @var $option Option */",
"foreach",
"(",
"$",
"this",
"->",
"options",
"as",
"$",
"option",
")",
"{",
"echo",
"\" \"",
".",
"$",
"option",
".",
"\"\\n\"",
";",
"}",
"echo",
"\"\\n\"",
";",
"$",
"this",
"->",
"notify",
"(",
"\"output\"",
")",
";",
"$",
"this",
"->",
"notify",
"(",
"\"shutdown\"",
")",
";",
"return",
"0",
";",
"}"
] | Prints help output
@return int Status code | [
"Prints",
"help",
"output"
] | e71d3af3cfbf83f7fca9aa89e9b4bf03dc9f4c40 | https://github.com/agroff/Command/blob/e71d3af3cfbf83f7fca9aa89e9b4bf03dc9f4c40/src/Groff/Command/Command.php#L269-L289 | train |
squareproton/Bond | src/Bond/Container/FindFilterComponentFactory.php | FindFilterComponentFactory.getReflClassFromComparisonValue | public function getReflClassFromComparisonValue( $value )
{
if( is_array($value) ) {
$class = $this->namespace . '\\FindFilterComponent\\PropertyAccessArrayEquality';
} elseif ( is_object($value) and $value instanceof Container ) {
$class = $this->namespace . '\\FindFilterComponent\\PropertyAccessContainerEquality';
} else {
$class = $this->namespace . '\\FindFilterComponent\\PropertyAccessScalarEquality';
}
return new ReflectionClass($class);
} | php | public function getReflClassFromComparisonValue( $value )
{
if( is_array($value) ) {
$class = $this->namespace . '\\FindFilterComponent\\PropertyAccessArrayEquality';
} elseif ( is_object($value) and $value instanceof Container ) {
$class = $this->namespace . '\\FindFilterComponent\\PropertyAccessContainerEquality';
} else {
$class = $this->namespace . '\\FindFilterComponent\\PropertyAccessScalarEquality';
}
return new ReflectionClass($class);
} | [
"public",
"function",
"getReflClassFromComparisonValue",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"namespace",
".",
"'\\\\FindFilterComponent\\\\PropertyAccessArrayEquality'",
";",
"}",
"elseif",
"(",
"is_object",
"(",
"$",
"value",
")",
"and",
"$",
"value",
"instanceof",
"Container",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"namespace",
".",
"'\\\\FindFilterComponent\\\\PropertyAccessContainerEquality'",
";",
"}",
"else",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"namespace",
".",
"'\\\\FindFilterComponent\\\\PropertyAccessScalarEquality'",
";",
"}",
"return",
"new",
"ReflectionClass",
"(",
"$",
"class",
")",
";",
"}"
] | Init the correct type of FindFilterComponent based what is passed
@param mixed $value
@return ReflectionClass of the FindFilterComponent | [
"Init",
"the",
"correct",
"type",
"of",
"FindFilterComponent",
"based",
"what",
"is",
"passed"
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Container/FindFilterComponentFactory.php#L85-L96 | train |
squareproton/Bond | src/Bond/Container/FindFilterComponentFactory.php | FindFilterComponentFactory.getHelper | private function getHelper( \ReflectionClass $propertyMapper, $name, $operation, $value )
{
$mapper = $propertyMapper->newInstance($name);
$instance = $this->getReflClassFromComparisonValue($value)
->newInstance($mapper, $operation, $value);
return $instance;
} | php | private function getHelper( \ReflectionClass $propertyMapper, $name, $operation, $value )
{
$mapper = $propertyMapper->newInstance($name);
$instance = $this->getReflClassFromComparisonValue($value)
->newInstance($mapper, $operation, $value);
return $instance;
} | [
"private",
"function",
"getHelper",
"(",
"\\",
"ReflectionClass",
"$",
"propertyMapper",
",",
"$",
"name",
",",
"$",
"operation",
",",
"$",
"value",
")",
"{",
"$",
"mapper",
"=",
"$",
"propertyMapper",
"->",
"newInstance",
"(",
"$",
"name",
")",
";",
"$",
"instance",
"=",
"$",
"this",
"->",
"getReflClassFromComparisonValue",
"(",
"$",
"value",
")",
"->",
"newInstance",
"(",
"$",
"mapper",
",",
"$",
"operation",
",",
"$",
"value",
")",
";",
"return",
"$",
"instance",
";",
"}"
] | Return a new instance of a FindFilterComponent
@return Bond\Container\FindFilterComponent | [
"Return",
"a",
"new",
"instance",
"of",
"a",
"FindFilterComponent"
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Container/FindFilterComponentFactory.php#L102-L108 | train |
squareproton/Bond | src/Bond/Container/FindFilterComponentFactory.php | FindFilterComponentFactory.get | public function get( $name, $operation, $value)
{
$filterComponents = [];
foreach( $this->reflPropertyMappers as $propertyMapper ) {
$filterComponents[] = $this->getHelper( $propertyMapper, $name, $operation, $value );
}
// not a multi - just return the lone FindFilterComponent
if( 1 === count($filterComponents) ) {
return $filterComponents[0];
}
// is a multi - instantiate all the FindFilterComponents and build a FindFilterComponentMulti
return new FindFilterComponentMulti(
$filterComponents,
$operation,
$value
);
} | php | public function get( $name, $operation, $value)
{
$filterComponents = [];
foreach( $this->reflPropertyMappers as $propertyMapper ) {
$filterComponents[] = $this->getHelper( $propertyMapper, $name, $operation, $value );
}
// not a multi - just return the lone FindFilterComponent
if( 1 === count($filterComponents) ) {
return $filterComponents[0];
}
// is a multi - instantiate all the FindFilterComponents and build a FindFilterComponentMulti
return new FindFilterComponentMulti(
$filterComponents,
$operation,
$value
);
} | [
"public",
"function",
"get",
"(",
"$",
"name",
",",
"$",
"operation",
",",
"$",
"value",
")",
"{",
"$",
"filterComponents",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"reflPropertyMappers",
"as",
"$",
"propertyMapper",
")",
"{",
"$",
"filterComponents",
"[",
"]",
"=",
"$",
"this",
"->",
"getHelper",
"(",
"$",
"propertyMapper",
",",
"$",
"name",
",",
"$",
"operation",
",",
"$",
"value",
")",
";",
"}",
"// not a multi - just return the lone FindFilterComponent",
"if",
"(",
"1",
"===",
"count",
"(",
"$",
"filterComponents",
")",
")",
"{",
"return",
"$",
"filterComponents",
"[",
"0",
"]",
";",
"}",
"// is a multi - instantiate all the FindFilterComponents and build a FindFilterComponentMulti",
"return",
"new",
"FindFilterComponentMulti",
"(",
"$",
"filterComponents",
",",
"$",
"operation",
",",
"$",
"value",
")",
";",
"}"
] | Return a new instance of a FindFilterComponent but Multi-PropertyMapperAware
@return Bond\Container\FindFilterComponent | [
"Return",
"a",
"new",
"instance",
"of",
"a",
"FindFilterComponent",
"but",
"Multi",
"-",
"PropertyMapperAware"
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Container/FindFilterComponentFactory.php#L114-L134 | train |
squareproton/Bond | src/Bond/Container/FindFilterComponentFactory.php | FindFilterComponentFactory.getRegex | protected function getRegex()
{
if( !self::$regexDefault ) {
self::$regexDefault = implode(
'|',
array_map(
function($value){
return "(?<=[a-z0-9]){$value}(?=[A-Z])";
},
array_flip( self::$operations )
)
);
self::$regexDefault = "/".self::$regexDefault."/";
}
return self::$regexDefault;
} | php | protected function getRegex()
{
if( !self::$regexDefault ) {
self::$regexDefault = implode(
'|',
array_map(
function($value){
return "(?<=[a-z0-9]){$value}(?=[A-Z])";
},
array_flip( self::$operations )
)
);
self::$regexDefault = "/".self::$regexDefault."/";
}
return self::$regexDefault;
} | [
"protected",
"function",
"getRegex",
"(",
")",
"{",
"if",
"(",
"!",
"self",
"::",
"$",
"regexDefault",
")",
"{",
"self",
"::",
"$",
"regexDefault",
"=",
"implode",
"(",
"'|'",
",",
"array_map",
"(",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"\"(?<=[a-z0-9]){$value}(?=[A-Z])\"",
";",
"}",
",",
"array_flip",
"(",
"self",
"::",
"$",
"operations",
")",
")",
")",
";",
"self",
"::",
"$",
"regexDefault",
"=",
"\"/\"",
".",
"self",
"::",
"$",
"regexDefault",
".",
"\"/\"",
";",
"}",
"return",
"self",
"::",
"$",
"regexDefault",
";",
"}"
] | Get the regular expression for identifying delimiters and tags within
@return regex | [
"Get",
"the",
"regular",
"expression",
"for",
"identifying",
"delimiters",
"and",
"tags",
"within"
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Container/FindFilterComponentFactory.php#L197-L215 | train |
Vectrex/vxPHP | src/Template/Filter/ImageCache.php | ImageCache.sanitizeActions | private function sanitizeActions($actionsString) {
$actions = [];
$actionsString = strtolower($actionsString);
// with duplicate actions the latter ones overwrite previous ones
foreach(explode('|', $actionsString) as $action) {
$action = trim($action);
$actions[strstr($action, ' ', true)] = $action;
}
return $actions;
} | php | private function sanitizeActions($actionsString) {
$actions = [];
$actionsString = strtolower($actionsString);
// with duplicate actions the latter ones overwrite previous ones
foreach(explode('|', $actionsString) as $action) {
$action = trim($action);
$actions[strstr($action, ' ', true)] = $action;
}
return $actions;
} | [
"private",
"function",
"sanitizeActions",
"(",
"$",
"actionsString",
")",
"{",
"$",
"actions",
"=",
"[",
"]",
";",
"$",
"actionsString",
"=",
"strtolower",
"(",
"$",
"actionsString",
")",
";",
"// with duplicate actions the latter ones overwrite previous ones",
"foreach",
"(",
"explode",
"(",
"'|'",
",",
"$",
"actionsString",
")",
"as",
"$",
"action",
")",
"{",
"$",
"action",
"=",
"trim",
"(",
"$",
"action",
")",
";",
"$",
"actions",
"[",
"strstr",
"(",
"$",
"action",
",",
"' '",
",",
"true",
")",
"]",
"=",
"$",
"action",
";",
"}",
"return",
"$",
"actions",
";",
"}"
] | turns actions string into array
avoid duplicate actions
@param string $actionsString
@return array | [
"turns",
"actions",
"string",
"into",
"array",
"avoid",
"duplicate",
"actions"
] | 295c21b00e7ef6085efcdf5b64fabb28d499b5a6 | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Template/Filter/ImageCache.php#L292-L307 | train |
locomotivemtl/charcoal-config | src/Charcoal/Config/FileAwareTrait.php | FileAwareTrait.loadFile | public function loadFile($path)
{
if (!is_string($path)) {
throw new InvalidArgumentException(
'File must be a string'
);
}
if (!file_exists($path)) {
throw new InvalidArgumentException(
sprintf('File "%s" does not exist', $path)
);
}
$ext = pathinfo($path, PATHINFO_EXTENSION);
switch ($ext) {
case 'php':
return $this->loadPhpFile($path);
case 'json':
return $this->loadJsonFile($path);
case 'ini':
return $this->loadIniFile($path);
case 'yml':
case 'yaml':
return $this->loadYamlFile($path);
}
$validConfigExts = [ 'ini', 'json', 'php', 'yml' ];
throw new InvalidArgumentException(sprintf(
'Unsupported file format for "%s"; must be one of "%s"',
$path,
implode('", "', $validConfigExts)
));
} | php | public function loadFile($path)
{
if (!is_string($path)) {
throw new InvalidArgumentException(
'File must be a string'
);
}
if (!file_exists($path)) {
throw new InvalidArgumentException(
sprintf('File "%s" does not exist', $path)
);
}
$ext = pathinfo($path, PATHINFO_EXTENSION);
switch ($ext) {
case 'php':
return $this->loadPhpFile($path);
case 'json':
return $this->loadJsonFile($path);
case 'ini':
return $this->loadIniFile($path);
case 'yml':
case 'yaml':
return $this->loadYamlFile($path);
}
$validConfigExts = [ 'ini', 'json', 'php', 'yml' ];
throw new InvalidArgumentException(sprintf(
'Unsupported file format for "%s"; must be one of "%s"',
$path,
implode('", "', $validConfigExts)
));
} | [
"public",
"function",
"loadFile",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'File must be a string'",
")",
";",
"}",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'File \"%s\" does not exist'",
",",
"$",
"path",
")",
")",
";",
"}",
"$",
"ext",
"=",
"pathinfo",
"(",
"$",
"path",
",",
"PATHINFO_EXTENSION",
")",
";",
"switch",
"(",
"$",
"ext",
")",
"{",
"case",
"'php'",
":",
"return",
"$",
"this",
"->",
"loadPhpFile",
"(",
"$",
"path",
")",
";",
"case",
"'json'",
":",
"return",
"$",
"this",
"->",
"loadJsonFile",
"(",
"$",
"path",
")",
";",
"case",
"'ini'",
":",
"return",
"$",
"this",
"->",
"loadIniFile",
"(",
"$",
"path",
")",
";",
"case",
"'yml'",
":",
"case",
"'yaml'",
":",
"return",
"$",
"this",
"->",
"loadYamlFile",
"(",
"$",
"path",
")",
";",
"}",
"$",
"validConfigExts",
"=",
"[",
"'ini'",
",",
"'json'",
",",
"'php'",
",",
"'yml'",
"]",
";",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Unsupported file format for \"%s\"; must be one of \"%s\"'",
",",
"$",
"path",
",",
"implode",
"(",
"'\", \"'",
",",
"$",
"validConfigExts",
")",
")",
")",
";",
"}"
] | Loads a configuration file.
@param string $path A path to a supported file.
@throws InvalidArgumentException If the path is invalid.
@return array An array on success. | [
"Loads",
"a",
"configuration",
"file",
"."
] | 722b34955360c287dea8fffb3b5491866ce5f6cb | https://github.com/locomotivemtl/charcoal-config/blob/722b34955360c287dea8fffb3b5491866ce5f6cb/src/Charcoal/Config/FileAwareTrait.php#L33-L69 | train |
locomotivemtl/charcoal-config | src/Charcoal/Config/FileAwareTrait.php | FileAwareTrait.loadIniFile | private function loadIniFile($path)
{
$data = parse_ini_file($path, true);
if ($data === false) {
throw new UnexpectedValueException(
sprintf('INI file "%s" is empty or invalid', $path)
);
}
return $data;
} | php | private function loadIniFile($path)
{
$data = parse_ini_file($path, true);
if ($data === false) {
throw new UnexpectedValueException(
sprintf('INI file "%s" is empty or invalid', $path)
);
}
return $data;
} | [
"private",
"function",
"loadIniFile",
"(",
"$",
"path",
")",
"{",
"$",
"data",
"=",
"parse_ini_file",
"(",
"$",
"path",
",",
"true",
")",
";",
"if",
"(",
"$",
"data",
"===",
"false",
")",
"{",
"throw",
"new",
"UnexpectedValueException",
"(",
"sprintf",
"(",
"'INI file \"%s\" is empty or invalid'",
",",
"$",
"path",
")",
")",
";",
"}",
"return",
"$",
"data",
";",
"}"
] | Load an INI file as an array.
@param string $path A path to an INI file.
@throws UnexpectedValueException If the file can not correctly be parsed into an array.
@return array An array on success. | [
"Load",
"an",
"INI",
"file",
"as",
"an",
"array",
"."
] | 722b34955360c287dea8fffb3b5491866ce5f6cb | https://github.com/locomotivemtl/charcoal-config/blob/722b34955360c287dea8fffb3b5491866ce5f6cb/src/Charcoal/Config/FileAwareTrait.php#L78-L88 | train |
locomotivemtl/charcoal-config | src/Charcoal/Config/FileAwareTrait.php | FileAwareTrait.loadPhpFile | private function loadPhpFile($path)
{
try {
$data = include $path;
} catch (Exception $e) {
$message = sprintf('PHP file "%s" could not be parsed: %s', $path, $e->getMessage());
throw new UnexpectedValueException($message, 0, $e);
} catch (Throwable $e) {
$message = sprintf('PHP file "%s" could not be parsed: %s', $path, $e->getMessage());
throw new UnexpectedValueException($message, 0, $e);
}
if (is_array($data) || ($data instanceof Traversable)) {
return $data;
}
return [];
} | php | private function loadPhpFile($path)
{
try {
$data = include $path;
} catch (Exception $e) {
$message = sprintf('PHP file "%s" could not be parsed: %s', $path, $e->getMessage());
throw new UnexpectedValueException($message, 0, $e);
} catch (Throwable $e) {
$message = sprintf('PHP file "%s" could not be parsed: %s', $path, $e->getMessage());
throw new UnexpectedValueException($message, 0, $e);
}
if (is_array($data) || ($data instanceof Traversable)) {
return $data;
}
return [];
} | [
"private",
"function",
"loadPhpFile",
"(",
"$",
"path",
")",
"{",
"try",
"{",
"$",
"data",
"=",
"include",
"$",
"path",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"$",
"message",
"=",
"sprintf",
"(",
"'PHP file \"%s\" could not be parsed: %s'",
",",
"$",
"path",
",",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"throw",
"new",
"UnexpectedValueException",
"(",
"$",
"message",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"catch",
"(",
"Throwable",
"$",
"e",
")",
"{",
"$",
"message",
"=",
"sprintf",
"(",
"'PHP file \"%s\" could not be parsed: %s'",
",",
"$",
"path",
",",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"throw",
"new",
"UnexpectedValueException",
"(",
"$",
"message",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"data",
")",
"||",
"(",
"$",
"data",
"instanceof",
"Traversable",
")",
")",
"{",
"return",
"$",
"data",
";",
"}",
"return",
"[",
"]",
";",
"}"
] | Load a PHP file, maybe as an array.
Note:
- The context of $this is bound to the current object.
- Data may be any value; the {@see self::addFile()} method will ignore
anything that isn't an (associative) array.
@param string $path A path to a PHP file.
@throws UnexpectedValueException If the file can not correctly be parsed.
@return array|Traversable An array or iterable object on success.
If the file is parsed as any other type, an empty array is returned. | [
"Load",
"a",
"PHP",
"file",
"maybe",
"as",
"an",
"array",
"."
] | 722b34955360c287dea8fffb3b5491866ce5f6cb | https://github.com/locomotivemtl/charcoal-config/blob/722b34955360c287dea8fffb3b5491866ce5f6cb/src/Charcoal/Config/FileAwareTrait.php#L132-L149 | train |
locomotivemtl/charcoal-config | src/Charcoal/Config/FileAwareTrait.php | FileAwareTrait.loadYamlFile | private function loadYamlFile($path)
{
if (!class_exists('Symfony\Component\Yaml\Parser')) {
throw new LogicException('YAML format requires the Symfony YAML component');
}
try {
$yaml = new YamlParser();
$data = $yaml->parseFile($path);
} catch (Exception $e) {
$message = sprintf('YAML file "%s" could not be parsed: %s', $path, $e->getMessage());
throw new UnexpectedValueException($message, 0, $e);
}
if (!is_array($data)) {
return [];
}
return $data;
} | php | private function loadYamlFile($path)
{
if (!class_exists('Symfony\Component\Yaml\Parser')) {
throw new LogicException('YAML format requires the Symfony YAML component');
}
try {
$yaml = new YamlParser();
$data = $yaml->parseFile($path);
} catch (Exception $e) {
$message = sprintf('YAML file "%s" could not be parsed: %s', $path, $e->getMessage());
throw new UnexpectedValueException($message, 0, $e);
}
if (!is_array($data)) {
return [];
}
return $data;
} | [
"private",
"function",
"loadYamlFile",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"'Symfony\\Component\\Yaml\\Parser'",
")",
")",
"{",
"throw",
"new",
"LogicException",
"(",
"'YAML format requires the Symfony YAML component'",
")",
";",
"}",
"try",
"{",
"$",
"yaml",
"=",
"new",
"YamlParser",
"(",
")",
";",
"$",
"data",
"=",
"$",
"yaml",
"->",
"parseFile",
"(",
"$",
"path",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"$",
"message",
"=",
"sprintf",
"(",
"'YAML file \"%s\" could not be parsed: %s'",
",",
"$",
"path",
",",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"throw",
"new",
"UnexpectedValueException",
"(",
"$",
"message",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"if",
"(",
"!",
"is_array",
"(",
"$",
"data",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"return",
"$",
"data",
";",
"}"
] | Load a YAML file as an array.
@param string $path A path to a YAML/YML file.
@throws LogicException If a YAML parser is unavailable.
@throws UnexpectedValueException If the file can not correctly be parsed into an array.
@return array An array on success.
If the file is parsed as any other type, an empty array is returned. | [
"Load",
"a",
"YAML",
"file",
"as",
"an",
"array",
"."
] | 722b34955360c287dea8fffb3b5491866ce5f6cb | https://github.com/locomotivemtl/charcoal-config/blob/722b34955360c287dea8fffb3b5491866ce5f6cb/src/Charcoal/Config/FileAwareTrait.php#L160-L179 | train |
as3io/As3ModlrBundle | DependencyInjection/ServiceLoaderManager.php | ServiceLoaderManager.initLoaders | private function initLoaders()
{
$namespace = sprintf('%s\\ServiceLoader', __NAMESPACE__);
$classes = ['MetadataCache', 'MetadataDrivers', 'MetadataFactory', 'Persisters', 'Rest', 'SearchClients'];
foreach ($classes as $class) {
$fqcn = sprintf('%s\\%s', $namespace, $class);
$this->addLoader(new $fqcn);
}
return $this;
} | php | private function initLoaders()
{
$namespace = sprintf('%s\\ServiceLoader', __NAMESPACE__);
$classes = ['MetadataCache', 'MetadataDrivers', 'MetadataFactory', 'Persisters', 'Rest', 'SearchClients'];
foreach ($classes as $class) {
$fqcn = sprintf('%s\\%s', $namespace, $class);
$this->addLoader(new $fqcn);
}
return $this;
} | [
"private",
"function",
"initLoaders",
"(",
")",
"{",
"$",
"namespace",
"=",
"sprintf",
"(",
"'%s\\\\ServiceLoader'",
",",
"__NAMESPACE__",
")",
";",
"$",
"classes",
"=",
"[",
"'MetadataCache'",
",",
"'MetadataDrivers'",
",",
"'MetadataFactory'",
",",
"'Persisters'",
",",
"'Rest'",
",",
"'SearchClients'",
"]",
";",
"foreach",
"(",
"$",
"classes",
"as",
"$",
"class",
")",
"{",
"$",
"fqcn",
"=",
"sprintf",
"(",
"'%s\\\\%s'",
",",
"$",
"namespace",
",",
"$",
"class",
")",
";",
"$",
"this",
"->",
"addLoader",
"(",
"new",
"$",
"fqcn",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Initializes all service loaders.
@return self | [
"Initializes",
"all",
"service",
"loaders",
"."
] | 7ce2abb7390c7eaf4081c5b7e00b96e7001774a4 | https://github.com/as3io/As3ModlrBundle/blob/7ce2abb7390c7eaf4081c5b7e00b96e7001774a4/DependencyInjection/ServiceLoaderManager.php#L53-L63 | train |
as3io/As3ModlrBundle | DependencyInjection/ServiceLoaderManager.php | ServiceLoaderManager.loadServices | public function loadServices(array $config)
{
foreach ($this->loaders as $loader) {
$loader->load($config, $this->container);
}
return $this;
} | php | public function loadServices(array $config)
{
foreach ($this->loaders as $loader) {
$loader->load($config, $this->container);
}
return $this;
} | [
"public",
"function",
"loadServices",
"(",
"array",
"$",
"config",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"loaders",
"as",
"$",
"loader",
")",
"{",
"$",
"loader",
"->",
"load",
"(",
"$",
"config",
",",
"$",
"this",
"->",
"container",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Loads services from all loaders.
@param array $config
@return self | [
"Loads",
"services",
"from",
"all",
"loaders",
"."
] | 7ce2abb7390c7eaf4081c5b7e00b96e7001774a4 | https://github.com/as3io/As3ModlrBundle/blob/7ce2abb7390c7eaf4081c5b7e00b96e7001774a4/DependencyInjection/ServiceLoaderManager.php#L71-L77 | train |
guni12/comment | src/Comments/CommController.php | CommController.toRender | public function toRender($title, $crud, $data)
{
$view = $this->di->get("view");
$pageRender = $this->di->get("pageRender");
$view->add($crud, $data);
$tempfix = "";
$pageRender->renderPage($tempfix, ["title" => $title]);
} | php | public function toRender($title, $crud, $data)
{
$view = $this->di->get("view");
$pageRender = $this->di->get("pageRender");
$view->add($crud, $data);
$tempfix = "";
$pageRender->renderPage($tempfix, ["title" => $title]);
} | [
"public",
"function",
"toRender",
"(",
"$",
"title",
",",
"$",
"crud",
",",
"$",
"data",
")",
"{",
"$",
"view",
"=",
"$",
"this",
"->",
"di",
"->",
"get",
"(",
"\"view\"",
")",
";",
"$",
"pageRender",
"=",
"$",
"this",
"->",
"di",
"->",
"get",
"(",
"\"pageRender\"",
")",
";",
"$",
"view",
"->",
"add",
"(",
"$",
"crud",
",",
"$",
"data",
")",
";",
"$",
"tempfix",
"=",
"\"\"",
";",
"$",
"pageRender",
"->",
"renderPage",
"(",
"$",
"tempfix",
",",
"[",
"\"title\"",
"=>",
"$",
"title",
"]",
")",
";",
"}"
] | Sends data to view
@param string $title
@param string $crud, path to view
@param array $data, htmlcontent to view | [
"Sends",
"data",
"to",
"view"
] | f9c2f3e2093fea414867f548c5f5e07f96c55bfd | https://github.com/guni12/comment/blob/f9c2f3e2093fea414867f548c5f5e07f96c55bfd/src/Comments/CommController.php#L34-L41 | train |
Dhii/config | src/PathSegmentSeparatorAwareTrait.php | PathSegmentSeparatorAwareTrait._setPathSegmentSeparator | protected function _setPathSegmentSeparator($separator)
{
if (
!($separator instanceof Stringable) &&
!is_string($separator) &&
!is_null($separator)
) {
throw $this->_createInvalidArgumentException($this->__('Invalid path segment separator'), null, null, $separator);
}
$this->pathSegmentSeparator = $separator;
} | php | protected function _setPathSegmentSeparator($separator)
{
if (
!($separator instanceof Stringable) &&
!is_string($separator) &&
!is_null($separator)
) {
throw $this->_createInvalidArgumentException($this->__('Invalid path segment separator'), null, null, $separator);
}
$this->pathSegmentSeparator = $separator;
} | [
"protected",
"function",
"_setPathSegmentSeparator",
"(",
"$",
"separator",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"separator",
"instanceof",
"Stringable",
")",
"&&",
"!",
"is_string",
"(",
"$",
"separator",
")",
"&&",
"!",
"is_null",
"(",
"$",
"separator",
")",
")",
"{",
"throw",
"$",
"this",
"->",
"_createInvalidArgumentException",
"(",
"$",
"this",
"->",
"__",
"(",
"'Invalid path segment separator'",
")",
",",
"null",
",",
"null",
",",
"$",
"separator",
")",
";",
"}",
"$",
"this",
"->",
"pathSegmentSeparator",
"=",
"$",
"separator",
";",
"}"
] | Assigns the separator of segments in a string path.
@since [*next-version*]
@param string|Stringable|null $separator The separator.
@throws InvalidArgumentException If the separator is invalid. | [
"Assigns",
"the",
"separator",
"of",
"segments",
"in",
"a",
"string",
"path",
"."
] | 1ab9a7ccf9c0ebd7c6fcbce600b4c00b52b2fdcf | https://github.com/Dhii/config/blob/1ab9a7ccf9c0ebd7c6fcbce600b4c00b52b2fdcf/src/PathSegmentSeparatorAwareTrait.php#L39-L50 | train |
theopera/framework | src/Component/Authorization/AccessControlList.php | AccessControlList.hasAccess | public function hasAccess(UserInterface $user, string $permission) : bool
{
return $this->provider->hasRolePermission($user->getRole(), $permission);
} | php | public function hasAccess(UserInterface $user, string $permission) : bool
{
return $this->provider->hasRolePermission($user->getRole(), $permission);
} | [
"public",
"function",
"hasAccess",
"(",
"UserInterface",
"$",
"user",
",",
"string",
"$",
"permission",
")",
":",
"bool",
"{",
"return",
"$",
"this",
"->",
"provider",
"->",
"hasRolePermission",
"(",
"$",
"user",
"->",
"getRole",
"(",
")",
",",
"$",
"permission",
")",
";",
"}"
] | Does the given user have access to the provided permission
@param UserInterface $user
@param string $permission
@return bool | [
"Does",
"the",
"given",
"user",
"have",
"access",
"to",
"the",
"provided",
"permission"
] | fa6165d3891a310faa580c81dee49a63c150c711 | https://github.com/theopera/framework/blob/fa6165d3891a310faa580c81dee49a63c150c711/src/Component/Authorization/AccessControlList.php#L40-L43 | train |
SagittariusX/Beluga.IO | src/Beluga/IO/FolderAccessError.php | FolderAccessError.Read | public static function Read(
string $package, string $folder, string $message = null, int $code = \E_USER_ERROR, \Throwable $previous = null )
: FolderAccessError
{
return new FolderAccessError(
$package,
$folder,
static::ACCESS_READ,
$message,
$code,
$previous
);
} | php | public static function Read(
string $package, string $folder, string $message = null, int $code = \E_USER_ERROR, \Throwable $previous = null )
: FolderAccessError
{
return new FolderAccessError(
$package,
$folder,
static::ACCESS_READ,
$message,
$code,
$previous
);
} | [
"public",
"static",
"function",
"Read",
"(",
"string",
"$",
"package",
",",
"string",
"$",
"folder",
",",
"string",
"$",
"message",
"=",
"null",
",",
"int",
"$",
"code",
"=",
"\\",
"E_USER_ERROR",
",",
"\\",
"Throwable",
"$",
"previous",
"=",
"null",
")",
":",
"FolderAccessError",
"{",
"return",
"new",
"FolderAccessError",
"(",
"$",
"package",
",",
"$",
"folder",
",",
"static",
"::",
"ACCESS_READ",
",",
"$",
"message",
",",
"$",
"code",
",",
"$",
"previous",
")",
";",
"}"
] | Init a new \Beluga\IO\FolderAccessError for folder read mode.
@param string $package
@param string $folder The folder where reading fails.
@param string $message The optional error message.
@param integer $code A optional error code (Defaults to \E_USER_ERROR)
@param \Throwable $previous A Optional previous exception.
@return \Beluga\IO\FolderAccessError | [
"Init",
"a",
"new",
"\\",
"Beluga",
"\\",
"IO",
"\\",
"FolderAccessError",
"for",
"folder",
"read",
"mode",
"."
] | c8af09a1b3cc8a955e43c89b70779d11b30ae29e | https://github.com/SagittariusX/Beluga.IO/blob/c8af09a1b3cc8a955e43c89b70779d11b30ae29e/src/Beluga/IO/FolderAccessError.php#L123-L135 | train |
SagittariusX/Beluga.IO | src/Beluga/IO/FolderAccessError.php | FolderAccessError.Write | public static function Write(
string $package, string $folder, string $message = null, int $code = \E_USER_ERROR, \Throwable $previous = null )
: FolderAccessError
{
return new FolderAccessError(
$package,
$folder,
static::ACCESS_WRITE,
$message,
$code,
$previous
);
} | php | public static function Write(
string $package, string $folder, string $message = null, int $code = \E_USER_ERROR, \Throwable $previous = null )
: FolderAccessError
{
return new FolderAccessError(
$package,
$folder,
static::ACCESS_WRITE,
$message,
$code,
$previous
);
} | [
"public",
"static",
"function",
"Write",
"(",
"string",
"$",
"package",
",",
"string",
"$",
"folder",
",",
"string",
"$",
"message",
"=",
"null",
",",
"int",
"$",
"code",
"=",
"\\",
"E_USER_ERROR",
",",
"\\",
"Throwable",
"$",
"previous",
"=",
"null",
")",
":",
"FolderAccessError",
"{",
"return",
"new",
"FolderAccessError",
"(",
"$",
"package",
",",
"$",
"folder",
",",
"static",
"::",
"ACCESS_WRITE",
",",
"$",
"message",
",",
"$",
"code",
",",
"$",
"previous",
")",
";",
"}"
] | Init a new \Beluga\IO\FolderAccessError for folder write mode.
@param string $package
@param string $folder The folder where reading fails.
@param string $message The optional error message.
@param integer $code A optional error code (Defaults to \E_USER_ERROR)
@param \Throwable $previous A Optional previous exception.
@return \Beluga\IO\FolderAccessError | [
"Init",
"a",
"new",
"\\",
"Beluga",
"\\",
"IO",
"\\",
"FolderAccessError",
"for",
"folder",
"write",
"mode",
"."
] | c8af09a1b3cc8a955e43c89b70779d11b30ae29e | https://github.com/SagittariusX/Beluga.IO/blob/c8af09a1b3cc8a955e43c89b70779d11b30ae29e/src/Beluga/IO/FolderAccessError.php#L147-L159 | train |
horntell/php-sdk | lib/guzzle/GuzzleHttp/Adapter/StreamAdapter.php | StreamAdapter.getSaveToBody | private function getSaveToBody(
RequestInterface $request,
StreamInterface $stream
) {
if ($saveTo = $request->getConfig()['save_to']) {
// Stream the response into the destination stream
$saveTo = is_string($saveTo)
? new Stream(Utils::open($saveTo, 'r+'))
: Stream::factory($saveTo);
} else {
// Stream into the default temp stream
$saveTo = Stream::factory();
}
Utils::copyToStream($stream, $saveTo);
$saveTo->seek(0);
$stream->close();
return $saveTo;
} | php | private function getSaveToBody(
RequestInterface $request,
StreamInterface $stream
) {
if ($saveTo = $request->getConfig()['save_to']) {
// Stream the response into the destination stream
$saveTo = is_string($saveTo)
? new Stream(Utils::open($saveTo, 'r+'))
: Stream::factory($saveTo);
} else {
// Stream into the default temp stream
$saveTo = Stream::factory();
}
Utils::copyToStream($stream, $saveTo);
$saveTo->seek(0);
$stream->close();
return $saveTo;
} | [
"private",
"function",
"getSaveToBody",
"(",
"RequestInterface",
"$",
"request",
",",
"StreamInterface",
"$",
"stream",
")",
"{",
"if",
"(",
"$",
"saveTo",
"=",
"$",
"request",
"->",
"getConfig",
"(",
")",
"[",
"'save_to'",
"]",
")",
"{",
"// Stream the response into the destination stream",
"$",
"saveTo",
"=",
"is_string",
"(",
"$",
"saveTo",
")",
"?",
"new",
"Stream",
"(",
"Utils",
"::",
"open",
"(",
"$",
"saveTo",
",",
"'r+'",
")",
")",
":",
"Stream",
"::",
"factory",
"(",
"$",
"saveTo",
")",
";",
"}",
"else",
"{",
"// Stream into the default temp stream",
"$",
"saveTo",
"=",
"Stream",
"::",
"factory",
"(",
")",
";",
"}",
"Utils",
"::",
"copyToStream",
"(",
"$",
"stream",
",",
"$",
"saveTo",
")",
";",
"$",
"saveTo",
"->",
"seek",
"(",
"0",
")",
";",
"$",
"stream",
"->",
"close",
"(",
")",
";",
"return",
"$",
"saveTo",
";",
"}"
] | Drain the stream into the destination stream | [
"Drain",
"the",
"stream",
"into",
"the",
"destination",
"stream"
] | e5205e9396a21b754d5651a8aa5898da5922a1b7 | https://github.com/horntell/php-sdk/blob/e5205e9396a21b754d5651a8aa5898da5922a1b7/lib/guzzle/GuzzleHttp/Adapter/StreamAdapter.php#L116-L135 | train |
horntell/php-sdk | lib/guzzle/GuzzleHttp/Adapter/StreamAdapter.php | StreamAdapter.createStream | private function createStream(
RequestInterface $request,
&$http_response_header
) {
static $methods;
if (!$methods) {
$methods = array_flip(get_class_methods(__CLASS__));
}
$params = [];
$options = $this->getDefaultOptions($request);
foreach ($request->getConfig()->toArray() as $key => $value) {
$method = "add_{$key}";
if (isset($methods[$method])) {
$this->{$method}($request, $options, $value, $params);
}
}
$this->applyCustomOptions($request, $options);
$context = $this->createStreamContext($request, $options, $params);
return $this->createStreamResource(
$request,
$options,
$context,
$http_response_header
);
} | php | private function createStream(
RequestInterface $request,
&$http_response_header
) {
static $methods;
if (!$methods) {
$methods = array_flip(get_class_methods(__CLASS__));
}
$params = [];
$options = $this->getDefaultOptions($request);
foreach ($request->getConfig()->toArray() as $key => $value) {
$method = "add_{$key}";
if (isset($methods[$method])) {
$this->{$method}($request, $options, $value, $params);
}
}
$this->applyCustomOptions($request, $options);
$context = $this->createStreamContext($request, $options, $params);
return $this->createStreamResource(
$request,
$options,
$context,
$http_response_header
);
} | [
"private",
"function",
"createStream",
"(",
"RequestInterface",
"$",
"request",
",",
"&",
"$",
"http_response_header",
")",
"{",
"static",
"$",
"methods",
";",
"if",
"(",
"!",
"$",
"methods",
")",
"{",
"$",
"methods",
"=",
"array_flip",
"(",
"get_class_methods",
"(",
"__CLASS__",
")",
")",
";",
"}",
"$",
"params",
"=",
"[",
"]",
";",
"$",
"options",
"=",
"$",
"this",
"->",
"getDefaultOptions",
"(",
"$",
"request",
")",
";",
"foreach",
"(",
"$",
"request",
"->",
"getConfig",
"(",
")",
"->",
"toArray",
"(",
")",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"method",
"=",
"\"add_{$key}\"",
";",
"if",
"(",
"isset",
"(",
"$",
"methods",
"[",
"$",
"method",
"]",
")",
")",
"{",
"$",
"this",
"->",
"{",
"$",
"method",
"}",
"(",
"$",
"request",
",",
"$",
"options",
",",
"$",
"value",
",",
"$",
"params",
")",
";",
"}",
"}",
"$",
"this",
"->",
"applyCustomOptions",
"(",
"$",
"request",
",",
"$",
"options",
")",
";",
"$",
"context",
"=",
"$",
"this",
"->",
"createStreamContext",
"(",
"$",
"request",
",",
"$",
"options",
",",
"$",
"params",
")",
";",
"return",
"$",
"this",
"->",
"createStreamResource",
"(",
"$",
"request",
",",
"$",
"options",
",",
"$",
"context",
",",
"$",
"http_response_header",
")",
";",
"}"
] | Create the stream for the request with the context options.
@param RequestInterface $request Request being sent
@param mixed $http_response_header Populated by stream wrapper
@return resource | [
"Create",
"the",
"stream",
"for",
"the",
"request",
"with",
"the",
"context",
"options",
"."
] | e5205e9396a21b754d5651a8aa5898da5922a1b7 | https://github.com/horntell/php-sdk/blob/e5205e9396a21b754d5651a8aa5898da5922a1b7/lib/guzzle/GuzzleHttp/Adapter/StreamAdapter.php#L192-L219 | train |
perryflynn/PerrysLambda | src/PerrysLambda/IO/File.php | File.openDir | public function openDir()
{
if(!$this->isDir())
{
throw new IOException("Not a directory");
}
$dirconv = DirectoryConverter::fromPath($this);
$dirconv->setRoot($this->getRootDirectory());
$type = $this->getDirectoryType();
return new $type($dirconv);
} | php | public function openDir()
{
if(!$this->isDir())
{
throw new IOException("Not a directory");
}
$dirconv = DirectoryConverter::fromPath($this);
$dirconv->setRoot($this->getRootDirectory());
$type = $this->getDirectoryType();
return new $type($dirconv);
} | [
"public",
"function",
"openDir",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isDir",
"(",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Not a directory\"",
")",
";",
"}",
"$",
"dirconv",
"=",
"DirectoryConverter",
"::",
"fromPath",
"(",
"$",
"this",
")",
";",
"$",
"dirconv",
"->",
"setRoot",
"(",
"$",
"this",
"->",
"getRootDirectory",
"(",
")",
")",
";",
"$",
"type",
"=",
"$",
"this",
"->",
"getDirectoryType",
"(",
")",
";",
"return",
"new",
"$",
"type",
"(",
"$",
"dirconv",
")",
";",
"}"
] | Open new Directory instance
@return \PerrysLambda\IO\Directory | [
"Open",
"new",
"Directory",
"instance"
] | 9f1734ae4689d73278b887f9354dfd31428e96de | https://github.com/perryflynn/PerrysLambda/blob/9f1734ae4689d73278b887f9354dfd31428e96de/src/PerrysLambda/IO/File.php#L138-L150 | train |
pluf/tenant | src/Tenant/Views/BankBackend.php | Tenant_Views_BankBackend.get | public function get($request, $match, $p)
{
$backend = parent::getObject($request, $match, $p);
if ($backend->tenant !== Tenant_Shortcuts_GetMainTenant()->id) {
throw new Pluf_HTTP_Error404("Object not found (" . $p['model'] . "," . $backend->id . ")");
}
return $backend;
} | php | public function get($request, $match, $p)
{
$backend = parent::getObject($request, $match, $p);
if ($backend->tenant !== Tenant_Shortcuts_GetMainTenant()->id) {
throw new Pluf_HTTP_Error404("Object not found (" . $p['model'] . "," . $backend->id . ")");
}
return $backend;
} | [
"public",
"function",
"get",
"(",
"$",
"request",
",",
"$",
"match",
",",
"$",
"p",
")",
"{",
"$",
"backend",
"=",
"parent",
"::",
"getObject",
"(",
"$",
"request",
",",
"$",
"match",
",",
"$",
"p",
")",
";",
"if",
"(",
"$",
"backend",
"->",
"tenant",
"!==",
"Tenant_Shortcuts_GetMainTenant",
"(",
")",
"->",
"id",
")",
"{",
"throw",
"new",
"Pluf_HTTP_Error404",
"(",
"\"Object not found (\"",
".",
"$",
"p",
"[",
"'model'",
"]",
".",
"\",\"",
".",
"$",
"backend",
"->",
"id",
".",
"\")\"",
")",
";",
"}",
"return",
"$",
"backend",
";",
"}"
] | Returns bank-backend determined by given id.
This method returns backend if and only if backend with given id blongs to main tenant
else it throws not found exception
@param Pluf_HTTP_Request $request
@param array $match
@param array $p | [
"Returns",
"bank",
"-",
"backend",
"determined",
"by",
"given",
"id",
".",
"This",
"method",
"returns",
"backend",
"if",
"and",
"only",
"if",
"backend",
"with",
"given",
"id",
"blongs",
"to",
"main",
"tenant",
"else",
"it",
"throws",
"not",
"found",
"exception"
] | a06359c52b9a257b5a0a186264e8770acfc54b73 | https://github.com/pluf/tenant/blob/a06359c52b9a257b5a0a186264e8770acfc54b73/src/Tenant/Views/BankBackend.php#L39-L46 | train |
brightnucleus/options-store | src/OptionsStore.php | OptionsStore.set | public function set(string $key, $value): Option
{
$option = $this->repository->find($key);
return $option->setValue($value);
} | php | public function set(string $key, $value): Option
{
$option = $this->repository->find($key);
return $option->setValue($value);
} | [
"public",
"function",
"set",
"(",
"string",
"$",
"key",
",",
"$",
"value",
")",
":",
"Option",
"{",
"$",
"option",
"=",
"$",
"this",
"->",
"repository",
"->",
"find",
"(",
"$",
"key",
")",
";",
"return",
"$",
"option",
"->",
"setValue",
"(",
"$",
"value",
")",
";",
"}"
] | Set the value for a specific key.
@since 0.1.0
@param string $key Option key to set the value of.
@param mixed $value New value to set the option to.
@return Option Modified Option object. | [
"Set",
"the",
"value",
"for",
"a",
"specific",
"key",
"."
] | 9a9ef2a160bbacd69fe3e9db0be8ed89e6905ef1 | https://github.com/brightnucleus/options-store/blob/9a9ef2a160bbacd69fe3e9db0be8ed89e6905ef1/src/OptionsStore.php#L114-L119 | train |
mossphp/moss-storage | Moss/Storage/Model/Definition/Relation/AbstractRelation.php | AbstractRelation.containerName | protected function containerName($container = null)
{
if ($container !== null) {
return $container;
}
$pos = strrpos($this->entity, '\\');
if ($pos === false) {
return $this->entity;
}
return substr($this->entity, strrpos($this->entity, '\\') + 1);
} | php | protected function containerName($container = null)
{
if ($container !== null) {
return $container;
}
$pos = strrpos($this->entity, '\\');
if ($pos === false) {
return $this->entity;
}
return substr($this->entity, strrpos($this->entity, '\\') + 1);
} | [
"protected",
"function",
"containerName",
"(",
"$",
"container",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"container",
"!==",
"null",
")",
"{",
"return",
"$",
"container",
";",
"}",
"$",
"pos",
"=",
"strrpos",
"(",
"$",
"this",
"->",
"entity",
",",
"'\\\\'",
")",
";",
"if",
"(",
"$",
"pos",
"===",
"false",
")",
"{",
"return",
"$",
"this",
"->",
"entity",
";",
"}",
"return",
"substr",
"(",
"$",
"this",
"->",
"entity",
",",
"strrpos",
"(",
"$",
"this",
"->",
"entity",
",",
"'\\\\'",
")",
"+",
"1",
")",
";",
"}"
] | Returns container name or builds it from namespaced class name if passed name is empty string
@param null|string $container
@return string | [
"Returns",
"container",
"name",
"or",
"builds",
"it",
"from",
"namespaced",
"class",
"name",
"if",
"passed",
"name",
"is",
"empty",
"string"
] | 0d123e7ae6bbfce1e2a18e73bf70997277b430c1 | https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Model/Definition/Relation/AbstractRelation.php#L46-L58 | train |
mossphp/moss-storage | Moss/Storage/Model/Definition/Relation/AbstractRelation.php | AbstractRelation.assignKeys | protected function assignKeys(array $keys, array &$container)
{
foreach ($keys as $local => $foreign) {
$this->assertField($local);
$this->assertField($foreign);
$container[$local] = $foreign;
}
} | php | protected function assignKeys(array $keys, array &$container)
{
foreach ($keys as $local => $foreign) {
$this->assertField($local);
$this->assertField($foreign);
$container[$local] = $foreign;
}
} | [
"protected",
"function",
"assignKeys",
"(",
"array",
"$",
"keys",
",",
"array",
"&",
"$",
"container",
")",
"{",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"local",
"=>",
"$",
"foreign",
")",
"{",
"$",
"this",
"->",
"assertField",
"(",
"$",
"local",
")",
";",
"$",
"this",
"->",
"assertField",
"(",
"$",
"foreign",
")",
";",
"$",
"container",
"[",
"$",
"local",
"]",
"=",
"$",
"foreign",
";",
"}",
"}"
] | Assigns key pairs to passed container
@param array $keys
@param array $container | [
"Assigns",
"key",
"pairs",
"to",
"passed",
"container"
] | 0d123e7ae6bbfce1e2a18e73bf70997277b430c1 | https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Model/Definition/Relation/AbstractRelation.php#L66-L74 | train |
mossphp/moss-storage | Moss/Storage/Model/Definition/Relation/AbstractRelation.php | AbstractRelation.assertTroughKeys | protected function assertTroughKeys($inKeys, $outKeys)
{
if (empty($inKeys) || empty($outKeys)) {
throw new DefinitionException(sprintf('Invalid keys for relation "%s", must be two arrays with key-value pairs', $this->entity, count($inKeys)));
}
if (count($inKeys) !== count($outKeys)) {
throw new DefinitionException(sprintf('Both key arrays for relation "%s", must have the same number of elements', $this->entity));
}
} | php | protected function assertTroughKeys($inKeys, $outKeys)
{
if (empty($inKeys) || empty($outKeys)) {
throw new DefinitionException(sprintf('Invalid keys for relation "%s", must be two arrays with key-value pairs', $this->entity, count($inKeys)));
}
if (count($inKeys) !== count($outKeys)) {
throw new DefinitionException(sprintf('Both key arrays for relation "%s", must have the same number of elements', $this->entity));
}
} | [
"protected",
"function",
"assertTroughKeys",
"(",
"$",
"inKeys",
",",
"$",
"outKeys",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"inKeys",
")",
"||",
"empty",
"(",
"$",
"outKeys",
")",
")",
"{",
"throw",
"new",
"DefinitionException",
"(",
"sprintf",
"(",
"'Invalid keys for relation \"%s\", must be two arrays with key-value pairs'",
",",
"$",
"this",
"->",
"entity",
",",
"count",
"(",
"$",
"inKeys",
")",
")",
")",
";",
"}",
"if",
"(",
"count",
"(",
"$",
"inKeys",
")",
"!==",
"count",
"(",
"$",
"outKeys",
")",
")",
"{",
"throw",
"new",
"DefinitionException",
"(",
"sprintf",
"(",
"'Both key arrays for relation \"%s\", must have the same number of elements'",
",",
"$",
"this",
"->",
"entity",
")",
")",
";",
"}",
"}"
] | Asserts trough keys, must be same number in both arrays
@param array $inKeys
@param array $outKeys
@throws DefinitionException | [
"Asserts",
"trough",
"keys",
"must",
"be",
"same",
"number",
"in",
"both",
"arrays"
] | 0d123e7ae6bbfce1e2a18e73bf70997277b430c1 | https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Model/Definition/Relation/AbstractRelation.php#L99-L108 | train |
mossphp/moss-storage | Moss/Storage/Model/Definition/Relation/AbstractRelation.php | AbstractRelation.assertField | protected function assertField($field)
{
if (empty($field)) {
throw new DefinitionException(sprintf('Invalid field name for relation "%s.%s" can not be empty', $this->entity, $field));
}
if (is_numeric($field)) {
throw new DefinitionException(sprintf('Invalid field name for relation "%s.%s" can not be numeric', $this->entity, $field));
}
if (!is_string($field)) {
throw new DefinitionException(sprintf('Invalid field name for relation "%s.%s" must be string, %s given', $this->entity, $field, $this->getType($field)));
}
} | php | protected function assertField($field)
{
if (empty($field)) {
throw new DefinitionException(sprintf('Invalid field name for relation "%s.%s" can not be empty', $this->entity, $field));
}
if (is_numeric($field)) {
throw new DefinitionException(sprintf('Invalid field name for relation "%s.%s" can not be numeric', $this->entity, $field));
}
if (!is_string($field)) {
throw new DefinitionException(sprintf('Invalid field name for relation "%s.%s" must be string, %s given', $this->entity, $field, $this->getType($field)));
}
} | [
"protected",
"function",
"assertField",
"(",
"$",
"field",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"field",
")",
")",
"{",
"throw",
"new",
"DefinitionException",
"(",
"sprintf",
"(",
"'Invalid field name for relation \"%s.%s\" can not be empty'",
",",
"$",
"this",
"->",
"entity",
",",
"$",
"field",
")",
")",
";",
"}",
"if",
"(",
"is_numeric",
"(",
"$",
"field",
")",
")",
"{",
"throw",
"new",
"DefinitionException",
"(",
"sprintf",
"(",
"'Invalid field name for relation \"%s.%s\" can not be numeric'",
",",
"$",
"this",
"->",
"entity",
",",
"$",
"field",
")",
")",
";",
"}",
"if",
"(",
"!",
"is_string",
"(",
"$",
"field",
")",
")",
"{",
"throw",
"new",
"DefinitionException",
"(",
"sprintf",
"(",
"'Invalid field name for relation \"%s.%s\" must be string, %s given'",
",",
"$",
"this",
"->",
"entity",
",",
"$",
"field",
",",
"$",
"this",
"->",
"getType",
"(",
"$",
"field",
")",
")",
")",
";",
"}",
"}"
] | Asserts field name
@param string $field
@throws DefinitionException | [
"Asserts",
"field",
"name"
] | 0d123e7ae6bbfce1e2a18e73bf70997277b430c1 | https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Model/Definition/Relation/AbstractRelation.php#L117-L130 | train |
makinacorpus/drupal-apubsub | src/Admin/FormatterListForm.php | FormatterListForm.disableSubmit | public function disableSubmit(array &$form, FormStateInterface $form_state)
{
$types = array();
foreach ($form_state->getValue('types') as $type => $selected) {
if ($type === $selected) {
$types[] = $type;
}
}
if (empty($types)) {
drupal_set_message($this->t("Nothing to do"));
return;
}
$disabled = variable_get(APB_VAR_ENABLED_TYPES, []);
$disabled += $types;
if (empty($disabled)) {
variable_set(APB_VAR_ENABLED_TYPES, null);
} else {
variable_set(APB_VAR_ENABLED_TYPES, array_unique($disabled));
}
drupal_set_message($this->t("Disabled selected types"));
} | php | public function disableSubmit(array &$form, FormStateInterface $form_state)
{
$types = array();
foreach ($form_state->getValue('types') as $type => $selected) {
if ($type === $selected) {
$types[] = $type;
}
}
if (empty($types)) {
drupal_set_message($this->t("Nothing to do"));
return;
}
$disabled = variable_get(APB_VAR_ENABLED_TYPES, []);
$disabled += $types;
if (empty($disabled)) {
variable_set(APB_VAR_ENABLED_TYPES, null);
} else {
variable_set(APB_VAR_ENABLED_TYPES, array_unique($disabled));
}
drupal_set_message($this->t("Disabled selected types"));
} | [
"public",
"function",
"disableSubmit",
"(",
"array",
"&",
"$",
"form",
",",
"FormStateInterface",
"$",
"form_state",
")",
"{",
"$",
"types",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"form_state",
"->",
"getValue",
"(",
"'types'",
")",
"as",
"$",
"type",
"=>",
"$",
"selected",
")",
"{",
"if",
"(",
"$",
"type",
"===",
"$",
"selected",
")",
"{",
"$",
"types",
"[",
"]",
"=",
"$",
"type",
";",
"}",
"}",
"if",
"(",
"empty",
"(",
"$",
"types",
")",
")",
"{",
"drupal_set_message",
"(",
"$",
"this",
"->",
"t",
"(",
"\"Nothing to do\"",
")",
")",
";",
"return",
";",
"}",
"$",
"disabled",
"=",
"variable_get",
"(",
"APB_VAR_ENABLED_TYPES",
",",
"[",
"]",
")",
";",
"$",
"disabled",
"+=",
"$",
"types",
";",
"if",
"(",
"empty",
"(",
"$",
"disabled",
")",
")",
"{",
"variable_set",
"(",
"APB_VAR_ENABLED_TYPES",
",",
"null",
")",
";",
"}",
"else",
"{",
"variable_set",
"(",
"APB_VAR_ENABLED_TYPES",
",",
"array_unique",
"(",
"$",
"disabled",
")",
")",
";",
"}",
"drupal_set_message",
"(",
"$",
"this",
"->",
"t",
"(",
"\"Disabled selected types\"",
")",
")",
";",
"}"
] | Notification types admin form disable selected submit handler | [
"Notification",
"types",
"admin",
"form",
"disable",
"selected",
"submit",
"handler"
] | 534fbecf67c880996ae02210c0bfdb3e0d3699b6 | https://github.com/makinacorpus/drupal-apubsub/blob/534fbecf67c880996ae02210c0bfdb3e0d3699b6/src/Admin/FormatterListForm.php#L127-L151 | train |
squareproton/Bond | src/Bond/Repository.php | Repository.find | public function find( $key, $disableLateLoading = null )
{
// $disableLateLoading default value management
if( !is_bool( $disableLateLoading ) ) {
$disableLateLoading = false;
}
// empty key
if( is_null( $key ) or !is_scalar( $key ) or strlen( trim( $key ) ) === 0 ) {
return null;
}
$class = $this->entityClass;
try {
return $this->entityFactory( $key, $disableLateLoading );
} catch( \Exception $e ) {
return null;
}
} | php | public function find( $key, $disableLateLoading = null )
{
// $disableLateLoading default value management
if( !is_bool( $disableLateLoading ) ) {
$disableLateLoading = false;
}
// empty key
if( is_null( $key ) or !is_scalar( $key ) or strlen( trim( $key ) ) === 0 ) {
return null;
}
$class = $this->entityClass;
try {
return $this->entityFactory( $key, $disableLateLoading );
} catch( \Exception $e ) {
return null;
}
} | [
"public",
"function",
"find",
"(",
"$",
"key",
",",
"$",
"disableLateLoading",
"=",
"null",
")",
"{",
"// $disableLateLoading default value management",
"if",
"(",
"!",
"is_bool",
"(",
"$",
"disableLateLoading",
")",
")",
"{",
"$",
"disableLateLoading",
"=",
"false",
";",
"}",
"// empty key",
"if",
"(",
"is_null",
"(",
"$",
"key",
")",
"or",
"!",
"is_scalar",
"(",
"$",
"key",
")",
"or",
"strlen",
"(",
"trim",
"(",
"$",
"key",
")",
")",
"===",
"0",
")",
"{",
"return",
"null",
";",
"}",
"$",
"class",
"=",
"$",
"this",
"->",
"entityClass",
";",
"try",
"{",
"return",
"$",
"this",
"->",
"entityFactory",
"(",
"$",
"key",
",",
"$",
"disableLateLoading",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"return",
"null",
";",
"}",
"}"
] | Lookup a entity based on it's 'primary key' or key column
This will either return null or a Entity
@param mixed $key
@param bool $disableLateLoading | [
"Lookup",
"a",
"entity",
"based",
"on",
"it",
"s",
"primary",
"key",
"or",
"key",
"column",
"This",
"will",
"either",
"return",
"null",
"or",
"a",
"Entity"
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository.php#L167-L188 | train |
squareproton/Bond | src/Bond/Repository.php | Repository.entityFactory | private function entityFactory()
{
// this is a little tortuous but some constructor flows require the EntityManager
// as this point in the refactor I'm unwilling to modify the constructor of the Entity
// TODO. Fix this. Constructor injection
$entity = $this->reflEntityClass->newInstanceWithoutConstructor();
// add the entityManager
if( $this->reflEntityManagerPropertyOfEntity ) {
$this->reflEntityManagerPropertyOfEntity->setValue($entity, $this->entityManager);
}
// call the original constructor
call_user_func_array( [$entity, '__construct'], func_get_args() );
return $entity;
} | php | private function entityFactory()
{
// this is a little tortuous but some constructor flows require the EntityManager
// as this point in the refactor I'm unwilling to modify the constructor of the Entity
// TODO. Fix this. Constructor injection
$entity = $this->reflEntityClass->newInstanceWithoutConstructor();
// add the entityManager
if( $this->reflEntityManagerPropertyOfEntity ) {
$this->reflEntityManagerPropertyOfEntity->setValue($entity, $this->entityManager);
}
// call the original constructor
call_user_func_array( [$entity, '__construct'], func_get_args() );
return $entity;
} | [
"private",
"function",
"entityFactory",
"(",
")",
"{",
"// this is a little tortuous but some constructor flows require the EntityManager",
"// as this point in the refactor I'm unwilling to modify the constructor of the Entity",
"// TODO. Fix this. Constructor injection",
"$",
"entity",
"=",
"$",
"this",
"->",
"reflEntityClass",
"->",
"newInstanceWithoutConstructor",
"(",
")",
";",
"// add the entityManager",
"if",
"(",
"$",
"this",
"->",
"reflEntityManagerPropertyOfEntity",
")",
"{",
"$",
"this",
"->",
"reflEntityManagerPropertyOfEntity",
"->",
"setValue",
"(",
"$",
"entity",
",",
"$",
"this",
"->",
"entityManager",
")",
";",
"}",
"// call the original constructor",
"call_user_func_array",
"(",
"[",
"$",
"entity",
",",
"'__construct'",
"]",
",",
"func_get_args",
"(",
")",
")",
";",
"return",
"$",
"entity",
";",
"}"
] | Temp helper method which actually does the instantiation work and ensure our Entity has a link to the EntityManager
@return Bond\Base | [
"Temp",
"helper",
"method",
"which",
"actually",
"does",
"the",
"instantiation",
"work",
"and",
"ensure",
"our",
"Entity",
"has",
"a",
"link",
"to",
"the",
"EntityManager"
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository.php#L239-L252 | train |
squareproton/Bond | src/Bond/Repository.php | Repository.make | public function make( array $data = null )
{
if( !$this->makeableSafetyCheck() ) {
return null;
}
$entity = $this->entityFactory();
if( $data !== null ) {
$entity->set(
$data,
// as data is a array the second argument doesn't make much sense here
null,
// set the inital values and see that the correct input validation happens
$entity->inputValidate
);
}
return $entity;
} | php | public function make( array $data = null )
{
if( !$this->makeableSafetyCheck() ) {
return null;
}
$entity = $this->entityFactory();
if( $data !== null ) {
$entity->set(
$data,
// as data is a array the second argument doesn't make much sense here
null,
// set the inital values and see that the correct input validation happens
$entity->inputValidate
);
}
return $entity;
} | [
"public",
"function",
"make",
"(",
"array",
"$",
"data",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"makeableSafetyCheck",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"entity",
"=",
"$",
"this",
"->",
"entityFactory",
"(",
")",
";",
"if",
"(",
"$",
"data",
"!==",
"null",
")",
"{",
"$",
"entity",
"->",
"set",
"(",
"$",
"data",
",",
"// as data is a array the second argument doesn't make much sense here",
"null",
",",
"// set the inital values and see that the correct input validation happens",
"$",
"entity",
"->",
"inputValidate",
")",
";",
"}",
"return",
"$",
"entity",
";",
"}"
] | Returns a new entity of the correct type.
@return Base | [
"Returns",
"a",
"new",
"entity",
"of",
"the",
"correct",
"type",
"."
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository.php#L258-L277 | train |
squareproton/Bond | src/Bond/Repository.php | Repository.makeableSafetyCheck | protected function makeableSafetyCheck()
{
// makeable check
switch( $this->makeable ) {
case self::MAKEABLE_DISABLE:
return false;
case self::MAKEABLE_EXCEPTION:
throw new EntityNotMakeableException("Making objects of this type is restricted. Are you using a view or some other derived data.");
}
return true;
} | php | protected function makeableSafetyCheck()
{
// makeable check
switch( $this->makeable ) {
case self::MAKEABLE_DISABLE:
return false;
case self::MAKEABLE_EXCEPTION:
throw new EntityNotMakeableException("Making objects of this type is restricted. Are you using a view or some other derived data.");
}
return true;
} | [
"protected",
"function",
"makeableSafetyCheck",
"(",
")",
"{",
"// makeable check",
"switch",
"(",
"$",
"this",
"->",
"makeable",
")",
"{",
"case",
"self",
"::",
"MAKEABLE_DISABLE",
":",
"return",
"false",
";",
"case",
"self",
"::",
"MAKEABLE_EXCEPTION",
":",
"throw",
"new",
"EntityNotMakeableException",
"(",
"\"Making objects of this type is restricted. Are you using a view or some other derived data.\"",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Check to see if a repository is makeable
@return bool; | [
"Check",
"to",
"see",
"if",
"a",
"repository",
"is",
"makeable"
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository.php#L283-L293 | train |
squareproton/Bond | src/Bond/Repository.php | Repository.hasReference | public function hasReference( $reference, &$referenceDetail = null )
{
$referenceDetail = null;
foreach( $this->__get('references') as $name => $detail ) {
if( $name == $reference or $detail[0] == $reference ) {
$referenceDetail = $detail;
return $name;
}
}
return null;
} | php | public function hasReference( $reference, &$referenceDetail = null )
{
$referenceDetail = null;
foreach( $this->__get('references') as $name => $detail ) {
if( $name == $reference or $detail[0] == $reference ) {
$referenceDetail = $detail;
return $name;
}
}
return null;
} | [
"public",
"function",
"hasReference",
"(",
"$",
"reference",
",",
"&",
"$",
"referenceDetail",
"=",
"null",
")",
"{",
"$",
"referenceDetail",
"=",
"null",
";",
"foreach",
"(",
"$",
"this",
"->",
"__get",
"(",
"'references'",
")",
"as",
"$",
"name",
"=>",
"$",
"detail",
")",
"{",
"if",
"(",
"$",
"name",
"==",
"$",
"reference",
"or",
"$",
"detail",
"[",
"0",
"]",
"==",
"$",
"reference",
")",
"{",
"$",
"referenceDetail",
"=",
"$",
"detail",
";",
"return",
"$",
"name",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Check if Entity has link
@param mixed $reference
@param mixed $referenceDetail
@return boolean | [
"Check",
"if",
"Entity",
"has",
"link"
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository.php#L441-L457 | train |
squareproton/Bond | src/Bond/Repository.php | Repository.referencesGet | public function referencesGet( $entityOrContainer, $reference, $source = null )
{
if( !( $entityOrContainer instanceof Base || $entityOrContainer instanceof Container ) ) {
throw new \InvalidArgumentException("You can only lookup references by Entity or Container");
}
if( !$this->hasReference( $reference, $detail ) ) {
throw new EntityReferenceException( $this, $reference );;
}
$foreignRepo = $this->entityManager->getRepository( $detail[0] );
$filterComponent = $this->getFindFilterFactory($source)
->get( $detail[1], null, $entityOrContainer );
// find one / find all
if( $entityOrContainer instanceof Container ) {
$findQty = FindFilterComponentFactory::FIND_ALL;
} else {
$findQty = $detail[2] ? FindFilterComponentFactory::FIND_ALL : FindFilterComponentFactory::FIND_ONE;
}
return $foreignRepo->findByFilterComponents(
$findQty,
array( $detail[1] => $filterComponent ),
$source
);
} | php | public function referencesGet( $entityOrContainer, $reference, $source = null )
{
if( !( $entityOrContainer instanceof Base || $entityOrContainer instanceof Container ) ) {
throw new \InvalidArgumentException("You can only lookup references by Entity or Container");
}
if( !$this->hasReference( $reference, $detail ) ) {
throw new EntityReferenceException( $this, $reference );;
}
$foreignRepo = $this->entityManager->getRepository( $detail[0] );
$filterComponent = $this->getFindFilterFactory($source)
->get( $detail[1], null, $entityOrContainer );
// find one / find all
if( $entityOrContainer instanceof Container ) {
$findQty = FindFilterComponentFactory::FIND_ALL;
} else {
$findQty = $detail[2] ? FindFilterComponentFactory::FIND_ALL : FindFilterComponentFactory::FIND_ONE;
}
return $foreignRepo->findByFilterComponents(
$findQty,
array( $detail[1] => $filterComponent ),
$source
);
} | [
"public",
"function",
"referencesGet",
"(",
"$",
"entityOrContainer",
",",
"$",
"reference",
",",
"$",
"source",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"entityOrContainer",
"instanceof",
"Base",
"||",
"$",
"entityOrContainer",
"instanceof",
"Container",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"You can only lookup references by Entity or Container\"",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"hasReference",
"(",
"$",
"reference",
",",
"$",
"detail",
")",
")",
"{",
"throw",
"new",
"EntityReferenceException",
"(",
"$",
"this",
",",
"$",
"reference",
")",
";",
";",
"}",
"$",
"foreignRepo",
"=",
"$",
"this",
"->",
"entityManager",
"->",
"getRepository",
"(",
"$",
"detail",
"[",
"0",
"]",
")",
";",
"$",
"filterComponent",
"=",
"$",
"this",
"->",
"getFindFilterFactory",
"(",
"$",
"source",
")",
"->",
"get",
"(",
"$",
"detail",
"[",
"1",
"]",
",",
"null",
",",
"$",
"entityOrContainer",
")",
";",
"// find one / find all",
"if",
"(",
"$",
"entityOrContainer",
"instanceof",
"Container",
")",
"{",
"$",
"findQty",
"=",
"FindFilterComponentFactory",
"::",
"FIND_ALL",
";",
"}",
"else",
"{",
"$",
"findQty",
"=",
"$",
"detail",
"[",
"2",
"]",
"?",
"FindFilterComponentFactory",
"::",
"FIND_ALL",
":",
"FindFilterComponentFactory",
"::",
"FIND_ONE",
";",
"}",
"return",
"$",
"foreignRepo",
"->",
"findByFilterComponents",
"(",
"$",
"findQty",
",",
"array",
"(",
"$",
"detail",
"[",
"1",
"]",
"=>",
"$",
"filterComponent",
")",
",",
"$",
"source",
")",
";",
"}"
] | Get all references
@param Base|Container $entityOrContainer - Starting Entity.
@param mixed $foreignEntity - The type of target Entity we want to retrieve.
@param int $source - The source of the links, either PERSISTED, UNPERSISTED, CHANGED or ALL.
@return Entity|Container|null - whatever is apropriate for the link type. | [
"Get",
"all",
"references"
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository.php#L468-L497 | train |
squareproton/Bond | src/Bond/Repository.php | Repository.hasLink | public function hasLink( $link, &$linkDetail = null )
{
$links = $this->__get('links');
if( isset($links[$link])) {
$linkDetail = $links[$link];
return $link;
}
foreach( $links as $via => $linkDetail ){
if( in_array( $link, $linkDetail->foreignEntities ) ) {
return $via;
}
}
return false;
} | php | public function hasLink( $link, &$linkDetail = null )
{
$links = $this->__get('links');
if( isset($links[$link])) {
$linkDetail = $links[$link];
return $link;
}
foreach( $links as $via => $linkDetail ){
if( in_array( $link, $linkDetail->foreignEntities ) ) {
return $via;
}
}
return false;
} | [
"public",
"function",
"hasLink",
"(",
"$",
"link",
",",
"&",
"$",
"linkDetail",
"=",
"null",
")",
"{",
"$",
"links",
"=",
"$",
"this",
"->",
"__get",
"(",
"'links'",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"links",
"[",
"$",
"link",
"]",
")",
")",
"{",
"$",
"linkDetail",
"=",
"$",
"links",
"[",
"$",
"link",
"]",
";",
"return",
"$",
"link",
";",
"}",
"foreach",
"(",
"$",
"links",
"as",
"$",
"via",
"=>",
"$",
"linkDetail",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"link",
",",
"$",
"linkDetail",
"->",
"foreignEntities",
")",
")",
"{",
"return",
"$",
"via",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Check if Entity has a named link
@param mixed $linkName or $foreignEntity
@param mixed $linkDetail - Link information
@return mixed | [
"Check",
"if",
"Entity",
"has",
"a",
"named",
"link"
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository.php#L506-L524 | train |
squareproton/Bond | src/Bond/Repository.php | Repository.findByApiKey | public function findByApiKey( $value )
{
$apiOptions = $this->__get('apiOptions');
if( !isset( $apiOptions['findByKey'] ) ) {
return $this->find( $value, true );
}
$property = $apiOptions['findByKey'];
$filter = $this->getFindFilterFactory()
->get( $property, null, $value );
return $this->findByFilterComponents(
FindFilterComponentFactory::FIND_ONE,
array( $property => $filter ),
self::ALL
);
} | php | public function findByApiKey( $value )
{
$apiOptions = $this->__get('apiOptions');
if( !isset( $apiOptions['findByKey'] ) ) {
return $this->find( $value, true );
}
$property = $apiOptions['findByKey'];
$filter = $this->getFindFilterFactory()
->get( $property, null, $value );
return $this->findByFilterComponents(
FindFilterComponentFactory::FIND_ONE,
array( $property => $filter ),
self::ALL
);
} | [
"public",
"function",
"findByApiKey",
"(",
"$",
"value",
")",
"{",
"$",
"apiOptions",
"=",
"$",
"this",
"->",
"__get",
"(",
"'apiOptions'",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"apiOptions",
"[",
"'findByKey'",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"find",
"(",
"$",
"value",
",",
"true",
")",
";",
"}",
"$",
"property",
"=",
"$",
"apiOptions",
"[",
"'findByKey'",
"]",
";",
"$",
"filter",
"=",
"$",
"this",
"->",
"getFindFilterFactory",
"(",
")",
"->",
"get",
"(",
"$",
"property",
",",
"null",
",",
"$",
"value",
")",
";",
"return",
"$",
"this",
"->",
"findByFilterComponents",
"(",
"FindFilterComponentFactory",
"::",
"FIND_ONE",
",",
"array",
"(",
"$",
"property",
"=>",
"$",
"filter",
")",
",",
"self",
"::",
"ALL",
")",
";",
"}"
] | Look up a entity based on it's api key
@param mixed $value
@return entity | | [
"Look",
"up",
"a",
"entity",
"based",
"on",
"it",
"s",
"api",
"key"
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository.php#L590-L610 | train |
squareproton/Bond | src/Bond/Repository.php | Repository.getFindFilterFactory | private function getFindFilterFactory( $source = 0 )
{
$propertyMappers = [ PropertyMapperEntityData::class ];
if( $source & Base::INITIAL ) {
$propertyMappers[] = [ PropertyMapperEntityInitial::class ];
}
return new FindFilterComponentFactory( $propertyMappers );
} | php | private function getFindFilterFactory( $source = 0 )
{
$propertyMappers = [ PropertyMapperEntityData::class ];
if( $source & Base::INITIAL ) {
$propertyMappers[] = [ PropertyMapperEntityInitial::class ];
}
return new FindFilterComponentFactory( $propertyMappers );
} | [
"private",
"function",
"getFindFilterFactory",
"(",
"$",
"source",
"=",
"0",
")",
"{",
"$",
"propertyMappers",
"=",
"[",
"PropertyMapperEntityData",
"::",
"class",
"]",
";",
"if",
"(",
"$",
"source",
"&",
"Base",
"::",
"INITIAL",
")",
"{",
"$",
"propertyMappers",
"[",
"]",
"=",
"[",
"PropertyMapperEntityInitial",
"::",
"class",
"]",
";",
"}",
"return",
"new",
"FindFilterComponentFactory",
"(",
"$",
"propertyMappers",
")",
";",
"}"
] | Instantiate a appropriate FindFilterFactory
@param int Bitfield Bond\Entity\Base::INITIAL and possibly others
@return Bond\Container\FindFilterFactory | [
"Instantiate",
"a",
"appropriate",
"FindFilterFactory"
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository.php#L734-L741 | train |
squareproton/Bond | src/Bond/Repository.php | Repository.findByFilterComponentsSourceSetup | protected function findByFilterComponentsSourceSetup( $source )
{
// Set source defaults
if( !( $source & ( self::PERSISTED | self::UNPERSISTED ) ) ) {
$source += self::PERSISTED + self::UNPERSISTED;
}
if( !( $source & ( self::CHANGED | self::UNCHANGED ) ) ) {
$source += self::CHANGED + self::UNCHANGED;
}
if( !( $source & ( self::WITH_CHILDREN | self::NO_CHILDREN ) ) ) {
$source += self::WITH_CHILDREN;
}
if( !( $source & ( Base::DATA | Base::INITIAL ) ) ) {
$source += Base::DATA;
}
return $source;
} | php | protected function findByFilterComponentsSourceSetup( $source )
{
// Set source defaults
if( !( $source & ( self::PERSISTED | self::UNPERSISTED ) ) ) {
$source += self::PERSISTED + self::UNPERSISTED;
}
if( !( $source & ( self::CHANGED | self::UNCHANGED ) ) ) {
$source += self::CHANGED + self::UNCHANGED;
}
if( !( $source & ( self::WITH_CHILDREN | self::NO_CHILDREN ) ) ) {
$source += self::WITH_CHILDREN;
}
if( !( $source & ( Base::DATA | Base::INITIAL ) ) ) {
$source += Base::DATA;
}
return $source;
} | [
"protected",
"function",
"findByFilterComponentsSourceSetup",
"(",
"$",
"source",
")",
"{",
"// Set source defaults",
"if",
"(",
"!",
"(",
"$",
"source",
"&",
"(",
"self",
"::",
"PERSISTED",
"|",
"self",
"::",
"UNPERSISTED",
")",
")",
")",
"{",
"$",
"source",
"+=",
"self",
"::",
"PERSISTED",
"+",
"self",
"::",
"UNPERSISTED",
";",
"}",
"if",
"(",
"!",
"(",
"$",
"source",
"&",
"(",
"self",
"::",
"CHANGED",
"|",
"self",
"::",
"UNCHANGED",
")",
")",
")",
"{",
"$",
"source",
"+=",
"self",
"::",
"CHANGED",
"+",
"self",
"::",
"UNCHANGED",
";",
"}",
"if",
"(",
"!",
"(",
"$",
"source",
"&",
"(",
"self",
"::",
"WITH_CHILDREN",
"|",
"self",
"::",
"NO_CHILDREN",
")",
")",
")",
"{",
"$",
"source",
"+=",
"self",
"::",
"WITH_CHILDREN",
";",
"}",
"if",
"(",
"!",
"(",
"$",
"source",
"&",
"(",
"Base",
"::",
"DATA",
"|",
"Base",
"::",
"INITIAL",
")",
")",
")",
"{",
"$",
"source",
"+=",
"Base",
"::",
"DATA",
";",
"}",
"return",
"$",
"source",
";",
"}"
] | Set source defaults.
Helper method of findByFilterComponents
@param mixed $source | [
"Set",
"source",
"defaults",
".",
"Helper",
"method",
"of",
"findByFilterComponents"
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository.php#L748-L770 | train |
squareproton/Bond | src/Bond/Repository.php | Repository.findByFilterComponentsFormatReturnValue | public function findByFilterComponentsFormatReturnValue( $qty, Container $output )
{
if( $qty === FindFilterComponentFactory::FIND_ALL ) {
return $output;
}
switch( $count = count( $output ) ) {
case 0:
return null;
case 1:
return $output->pop();
}
throw new IncompatibleQtyException( "{$count} entities found - can't return 'one'" );
} | php | public function findByFilterComponentsFormatReturnValue( $qty, Container $output )
{
if( $qty === FindFilterComponentFactory::FIND_ALL ) {
return $output;
}
switch( $count = count( $output ) ) {
case 0:
return null;
case 1:
return $output->pop();
}
throw new IncompatibleQtyException( "{$count} entities found - can't return 'one'" );
} | [
"public",
"function",
"findByFilterComponentsFormatReturnValue",
"(",
"$",
"qty",
",",
"Container",
"$",
"output",
")",
"{",
"if",
"(",
"$",
"qty",
"===",
"FindFilterComponentFactory",
"::",
"FIND_ALL",
")",
"{",
"return",
"$",
"output",
";",
"}",
"switch",
"(",
"$",
"count",
"=",
"count",
"(",
"$",
"output",
")",
")",
"{",
"case",
"0",
":",
"return",
"null",
";",
"case",
"1",
":",
"return",
"$",
"output",
"->",
"pop",
"(",
")",
";",
"}",
"throw",
"new",
"IncompatibleQtyException",
"(",
"\"{$count} entities found - can't return 'one'\"",
")",
";",
"}"
] | Format the return value of a findByFilterComponents query
@param self::FIND_ALL|FIND_ONE $qty
@param Container $output
@return Container | [
"Format",
"the",
"return",
"value",
"of",
"a",
"findByFilterComponents",
"query"
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository.php#L778-L794 | train |
squareproton/Bond | src/Bond/Repository.php | Repository.findByFilterComponentsDatabase | protected function findByFilterComponentsDatabase( array $filterComponents, $source )
{
// hit the database and find something
$query = $this->buildQuery( $this->db, $filterComponents );
// get records from database
$result = $this->db->query( $query )->fetch( Result::FLATTEN_PREVENT );
$isChangedFilterCallback = $this->getFilterByIsChangedCallback($source);
$output = $this->initByDatas( $result )
->filter($isChangedFilterCallback)
->each(function($entity){
$entity->startDataInitialStore();
});
// add records from child tables if they exist
if( $source & self::WITH_CHILDREN ) {
foreach ( $this->children as $child ) {
$childRepo = $this->entityManager->getRepository($child);
$output->add(
$childRepo->findByFilterComponentsDatabase(
$filterComponents,
$source
)
);
}
}
return $output;
} | php | protected function findByFilterComponentsDatabase( array $filterComponents, $source )
{
// hit the database and find something
$query = $this->buildQuery( $this->db, $filterComponents );
// get records from database
$result = $this->db->query( $query )->fetch( Result::FLATTEN_PREVENT );
$isChangedFilterCallback = $this->getFilterByIsChangedCallback($source);
$output = $this->initByDatas( $result )
->filter($isChangedFilterCallback)
->each(function($entity){
$entity->startDataInitialStore();
});
// add records from child tables if they exist
if( $source & self::WITH_CHILDREN ) {
foreach ( $this->children as $child ) {
$childRepo = $this->entityManager->getRepository($child);
$output->add(
$childRepo->findByFilterComponentsDatabase(
$filterComponents,
$source
)
);
}
}
return $output;
} | [
"protected",
"function",
"findByFilterComponentsDatabase",
"(",
"array",
"$",
"filterComponents",
",",
"$",
"source",
")",
"{",
"// hit the database and find something",
"$",
"query",
"=",
"$",
"this",
"->",
"buildQuery",
"(",
"$",
"this",
"->",
"db",
",",
"$",
"filterComponents",
")",
";",
"// get records from database",
"$",
"result",
"=",
"$",
"this",
"->",
"db",
"->",
"query",
"(",
"$",
"query",
")",
"->",
"fetch",
"(",
"Result",
"::",
"FLATTEN_PREVENT",
")",
";",
"$",
"isChangedFilterCallback",
"=",
"$",
"this",
"->",
"getFilterByIsChangedCallback",
"(",
"$",
"source",
")",
";",
"$",
"output",
"=",
"$",
"this",
"->",
"initByDatas",
"(",
"$",
"result",
")",
"->",
"filter",
"(",
"$",
"isChangedFilterCallback",
")",
"->",
"each",
"(",
"function",
"(",
"$",
"entity",
")",
"{",
"$",
"entity",
"->",
"startDataInitialStore",
"(",
")",
";",
"}",
")",
";",
"// add records from child tables if they exist",
"if",
"(",
"$",
"source",
"&",
"self",
"::",
"WITH_CHILDREN",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"children",
"as",
"$",
"child",
")",
"{",
"$",
"childRepo",
"=",
"$",
"this",
"->",
"entityManager",
"->",
"getRepository",
"(",
"$",
"child",
")",
";",
"$",
"output",
"->",
"add",
"(",
"$",
"childRepo",
"->",
"findByFilterComponentsDatabase",
"(",
"$",
"filterComponents",
",",
"$",
"source",
")",
")",
";",
"}",
"}",
"return",
"$",
"output",
";",
"}"
] | Find a entity having been passed the filters.
@param array $filterComponents
@return Base|Container | [
"Find",
"a",
"entity",
"having",
"been",
"passed",
"the",
"filters",
"."
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository.php#L802-L834 | train |
squareproton/Bond | src/Bond/Repository.php | Repository.buildQuery | protected function buildQuery( QuoteInterface $db, $filterComponents )
{
// primary keys
$filterTags = array();
$dataTypes = $this->dataTypesGet();
// have we got components that we can't handle
if( $dataTypesMissing = array_diff( array_keys( $filterComponents ), array_keys( $dataTypes ) ) ) {
throw new \LogicException(
sprintf(
"The following keys `%s` don't exist in %s. You can't find a entity with this.",
implode(',', $dataTypesMissing ),
$this->table
)
);
}
// add the datatype tag to the filter component
foreach( $filterComponents as $name => $component ) {
$component->tag = $dataTypes[$name]->toQueryTag();
}
$data = array();
# system column tableoid can tell us which table a row comes from
# http://www.postgresql.org/docs/9.1/static/ddl-inherit.html
$sql = sprintf(
"SELECT * FROM ONLY %s %s",
$db->quoteIdent( $this->table ),
$this->buildQueryWhereClause( $db, $filterComponents, $data )
);
$query = new Query( $sql, $data );
return $query;
} | php | protected function buildQuery( QuoteInterface $db, $filterComponents )
{
// primary keys
$filterTags = array();
$dataTypes = $this->dataTypesGet();
// have we got components that we can't handle
if( $dataTypesMissing = array_diff( array_keys( $filterComponents ), array_keys( $dataTypes ) ) ) {
throw new \LogicException(
sprintf(
"The following keys `%s` don't exist in %s. You can't find a entity with this.",
implode(',', $dataTypesMissing ),
$this->table
)
);
}
// add the datatype tag to the filter component
foreach( $filterComponents as $name => $component ) {
$component->tag = $dataTypes[$name]->toQueryTag();
}
$data = array();
# system column tableoid can tell us which table a row comes from
# http://www.postgresql.org/docs/9.1/static/ddl-inherit.html
$sql = sprintf(
"SELECT * FROM ONLY %s %s",
$db->quoteIdent( $this->table ),
$this->buildQueryWhereClause( $db, $filterComponents, $data )
);
$query = new Query( $sql, $data );
return $query;
} | [
"protected",
"function",
"buildQuery",
"(",
"QuoteInterface",
"$",
"db",
",",
"$",
"filterComponents",
")",
"{",
"// primary keys",
"$",
"filterTags",
"=",
"array",
"(",
")",
";",
"$",
"dataTypes",
"=",
"$",
"this",
"->",
"dataTypesGet",
"(",
")",
";",
"// have we got components that we can't handle",
"if",
"(",
"$",
"dataTypesMissing",
"=",
"array_diff",
"(",
"array_keys",
"(",
"$",
"filterComponents",
")",
",",
"array_keys",
"(",
"$",
"dataTypes",
")",
")",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"sprintf",
"(",
"\"The following keys `%s` don't exist in %s. You can't find a entity with this.\"",
",",
"implode",
"(",
"','",
",",
"$",
"dataTypesMissing",
")",
",",
"$",
"this",
"->",
"table",
")",
")",
";",
"}",
"// add the datatype tag to the filter component",
"foreach",
"(",
"$",
"filterComponents",
"as",
"$",
"name",
"=>",
"$",
"component",
")",
"{",
"$",
"component",
"->",
"tag",
"=",
"$",
"dataTypes",
"[",
"$",
"name",
"]",
"->",
"toQueryTag",
"(",
")",
";",
"}",
"$",
"data",
"=",
"array",
"(",
")",
";",
"# system column tableoid can tell us which table a row comes from",
"# http://www.postgresql.org/docs/9.1/static/ddl-inherit.html",
"$",
"sql",
"=",
"sprintf",
"(",
"\"SELECT * FROM ONLY %s %s\"",
",",
"$",
"db",
"->",
"quoteIdent",
"(",
"$",
"this",
"->",
"table",
")",
",",
"$",
"this",
"->",
"buildQueryWhereClause",
"(",
"$",
"db",
",",
"$",
"filterComponents",
",",
"$",
"data",
")",
")",
";",
"$",
"query",
"=",
"new",
"Query",
"(",
"$",
"sql",
",",
"$",
"data",
")",
";",
"return",
"$",
"query",
";",
"}"
] | Build a Query object
@param array $filterComponents
@return Bond\Pg\Query | [
"Build",
"a",
"Query",
"object"
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository.php#L921-L958 | train |
squareproton/Bond | src/Bond/Repository.php | Repository.dataTypesGet | public function dataTypesGet( $filter = null )
{
// array of string
if( func_num_args() > 1 and \Bond\array_check( 'is_string', func_get_args() ) ) {
$filter = func_get_args();
}
// filter constants
if( is_int( $filter ) ) {
$dataTypes = array();
if( $filter & DataType::PRIMARY_KEYS ) {
$dataTypes += array_filter(
$this->dataTypes,
function( $dataType ) {
return $dataType->isPrimaryKey();
}
);
}
if( $filter & DataType::FORM_CHOICE_TEXT ) {
$dataTypes += array_filter(
$this->dataTypes,
function( $dataType ) {
return $dataType->isFormChoiceText();
}
);
}
if( $filter & DataType::AUTOCOMPLETE ) {
$dataTypes += array_filter(
$this->dataTypes,
function( $dataType ) {
return $dataType->isAutoComplete();
}
);
}
// todo. build a datatype from the $this->links et al
if( $filter & DataType::LINKS ) {
}
return $dataTypes;
}
if( is_string( $filter ) ) {
$filter = array( $filter );
}
if( is_array($filter) ) {
$result = array_intersect_key( $this->dataTypes, array_flip( $filter ) );
if ( count($result) != count($filter) ) {
throw new \InvalidArgumentException(
sprintf(
'Unknown columns "%s" passed to %s->dataTypesGet()',
implode( '","', array_diff( $filter, array_keys( $result ) ) ),
$this->entity
)
);
}
return $result;
}
if( $filter instanceof \Closure ) {
return array_filter( $this->dataTypes, $filter );
}
return $this->dataTypes;
} | php | public function dataTypesGet( $filter = null )
{
// array of string
if( func_num_args() > 1 and \Bond\array_check( 'is_string', func_get_args() ) ) {
$filter = func_get_args();
}
// filter constants
if( is_int( $filter ) ) {
$dataTypes = array();
if( $filter & DataType::PRIMARY_KEYS ) {
$dataTypes += array_filter(
$this->dataTypes,
function( $dataType ) {
return $dataType->isPrimaryKey();
}
);
}
if( $filter & DataType::FORM_CHOICE_TEXT ) {
$dataTypes += array_filter(
$this->dataTypes,
function( $dataType ) {
return $dataType->isFormChoiceText();
}
);
}
if( $filter & DataType::AUTOCOMPLETE ) {
$dataTypes += array_filter(
$this->dataTypes,
function( $dataType ) {
return $dataType->isAutoComplete();
}
);
}
// todo. build a datatype from the $this->links et al
if( $filter & DataType::LINKS ) {
}
return $dataTypes;
}
if( is_string( $filter ) ) {
$filter = array( $filter );
}
if( is_array($filter) ) {
$result = array_intersect_key( $this->dataTypes, array_flip( $filter ) );
if ( count($result) != count($filter) ) {
throw new \InvalidArgumentException(
sprintf(
'Unknown columns "%s" passed to %s->dataTypesGet()',
implode( '","', array_diff( $filter, array_keys( $result ) ) ),
$this->entity
)
);
}
return $result;
}
if( $filter instanceof \Closure ) {
return array_filter( $this->dataTypes, $filter );
}
return $this->dataTypes;
} | [
"public",
"function",
"dataTypesGet",
"(",
"$",
"filter",
"=",
"null",
")",
"{",
"// array of string",
"if",
"(",
"func_num_args",
"(",
")",
">",
"1",
"and",
"\\",
"Bond",
"\\",
"array_check",
"(",
"'is_string'",
",",
"func_get_args",
"(",
")",
")",
")",
"{",
"$",
"filter",
"=",
"func_get_args",
"(",
")",
";",
"}",
"// filter constants",
"if",
"(",
"is_int",
"(",
"$",
"filter",
")",
")",
"{",
"$",
"dataTypes",
"=",
"array",
"(",
")",
";",
"if",
"(",
"$",
"filter",
"&",
"DataType",
"::",
"PRIMARY_KEYS",
")",
"{",
"$",
"dataTypes",
"+=",
"array_filter",
"(",
"$",
"this",
"->",
"dataTypes",
",",
"function",
"(",
"$",
"dataType",
")",
"{",
"return",
"$",
"dataType",
"->",
"isPrimaryKey",
"(",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"$",
"filter",
"&",
"DataType",
"::",
"FORM_CHOICE_TEXT",
")",
"{",
"$",
"dataTypes",
"+=",
"array_filter",
"(",
"$",
"this",
"->",
"dataTypes",
",",
"function",
"(",
"$",
"dataType",
")",
"{",
"return",
"$",
"dataType",
"->",
"isFormChoiceText",
"(",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"$",
"filter",
"&",
"DataType",
"::",
"AUTOCOMPLETE",
")",
"{",
"$",
"dataTypes",
"+=",
"array_filter",
"(",
"$",
"this",
"->",
"dataTypes",
",",
"function",
"(",
"$",
"dataType",
")",
"{",
"return",
"$",
"dataType",
"->",
"isAutoComplete",
"(",
")",
";",
"}",
")",
";",
"}",
"// todo. build a datatype from the $this->links et al",
"if",
"(",
"$",
"filter",
"&",
"DataType",
"::",
"LINKS",
")",
"{",
"}",
"return",
"$",
"dataTypes",
";",
"}",
"if",
"(",
"is_string",
"(",
"$",
"filter",
")",
")",
"{",
"$",
"filter",
"=",
"array",
"(",
"$",
"filter",
")",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"filter",
")",
")",
"{",
"$",
"result",
"=",
"array_intersect_key",
"(",
"$",
"this",
"->",
"dataTypes",
",",
"array_flip",
"(",
"$",
"filter",
")",
")",
";",
"if",
"(",
"count",
"(",
"$",
"result",
")",
"!=",
"count",
"(",
"$",
"filter",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Unknown columns \"%s\" passed to %s->dataTypesGet()'",
",",
"implode",
"(",
"'\",\"'",
",",
"array_diff",
"(",
"$",
"filter",
",",
"array_keys",
"(",
"$",
"result",
")",
")",
")",
",",
"$",
"this",
"->",
"entity",
")",
")",
";",
"}",
"return",
"$",
"result",
";",
"}",
"if",
"(",
"$",
"filter",
"instanceof",
"\\",
"Closure",
")",
"{",
"return",
"array_filter",
"(",
"$",
"this",
"->",
"dataTypes",
",",
"$",
"filter",
")",
";",
"}",
"return",
"$",
"this",
"->",
"dataTypes",
";",
"}"
] | Helper function. Get dataTypes for this Entity.
@return array | [
"Helper",
"function",
".",
"Get",
"dataTypes",
"for",
"this",
"Entity",
"."
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository.php#L1065-L1139 | train |
squareproton/Bond | src/Bond/Repository.php | Repository.getFilterByIsChangedCallback | public function getFilterByIsChangedCallback( $source )
{
$changed = !( $source & self::CHANGED );
$unchanged = !( $source & self::UNCHANGED );
if( $changed and $unchanged ) {
return function() {
return false;
};
}
if( !$changed and !$unchanged ) {
return function() {
return true;
};
}
return function ($entity) use ( $changed ) {
return $entity->isChanged() !== $changed;
};
} | php | public function getFilterByIsChangedCallback( $source )
{
$changed = !( $source & self::CHANGED );
$unchanged = !( $source & self::UNCHANGED );
if( $changed and $unchanged ) {
return function() {
return false;
};
}
if( !$changed and !$unchanged ) {
return function() {
return true;
};
}
return function ($entity) use ( $changed ) {
return $entity->isChanged() !== $changed;
};
} | [
"public",
"function",
"getFilterByIsChangedCallback",
"(",
"$",
"source",
")",
"{",
"$",
"changed",
"=",
"!",
"(",
"$",
"source",
"&",
"self",
"::",
"CHANGED",
")",
";",
"$",
"unchanged",
"=",
"!",
"(",
"$",
"source",
"&",
"self",
"::",
"UNCHANGED",
")",
";",
"if",
"(",
"$",
"changed",
"and",
"$",
"unchanged",
")",
"{",
"return",
"function",
"(",
")",
"{",
"return",
"false",
";",
"}",
";",
"}",
"if",
"(",
"!",
"$",
"changed",
"and",
"!",
"$",
"unchanged",
")",
"{",
"return",
"function",
"(",
")",
"{",
"return",
"true",
";",
"}",
";",
"}",
"return",
"function",
"(",
"$",
"entity",
")",
"use",
"(",
"$",
"changed",
")",
"{",
"return",
"$",
"entity",
"->",
"isChanged",
"(",
")",
"!==",
"$",
"changed",
";",
"}",
";",
"}"
] | Filter entities by their changed status.
@param bool $changed. Remove entities which are changed
@param bool $uchanged. Remove unchanged entities
@return $this | [
"Filter",
"entities",
"by",
"their",
"changed",
"status",
"."
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository.php#L1147-L1169 | train |
squareproton/Bond | src/Bond/Repository.php | Repository.makeNewContainer | protected function makeNewContainer()
{
$container = new Container();
$container->classSet($this->entityClass);
$container->setPropertyMapper( PropertyMapperEntityData::class );
return $container;
} | php | protected function makeNewContainer()
{
$container = new Container();
$container->classSet($this->entityClass);
$container->setPropertyMapper( PropertyMapperEntityData::class );
return $container;
} | [
"protected",
"function",
"makeNewContainer",
"(",
")",
"{",
"$",
"container",
"=",
"new",
"Container",
"(",
")",
";",
"$",
"container",
"->",
"classSet",
"(",
"$",
"this",
"->",
"entityClass",
")",
";",
"$",
"container",
"->",
"setPropertyMapper",
"(",
"PropertyMapperEntityData",
"::",
"class",
")",
";",
"return",
"$",
"container",
";",
"}"
] | Get a new Container
@param string Class
@return Bond\Container | [
"Get",
"a",
"new",
"Container"
] | a04ad9dd1a35adeaec98237716c2a41ce02b4f1a | https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Repository.php#L1203-L1209 | train |
maddoger/yii2-cms-user | backend/controllers/RoleController.php | RoleController.actionCreate | public function actionCreate()
{
$model = new Role();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->name]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
} | php | public function actionCreate()
{
$model = new Role();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->name]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
} | [
"public",
"function",
"actionCreate",
"(",
")",
"{",
"$",
"model",
"=",
"new",
"Role",
"(",
")",
";",
"if",
"(",
"$",
"model",
"->",
"load",
"(",
"Yii",
"::",
"$",
"app",
"->",
"request",
"->",
"post",
"(",
")",
")",
"&&",
"$",
"model",
"->",
"save",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"redirect",
"(",
"[",
"'view'",
",",
"'id'",
"=>",
"$",
"model",
"->",
"name",
"]",
")",
";",
"}",
"else",
"{",
"return",
"$",
"this",
"->",
"render",
"(",
"'create'",
",",
"[",
"'model'",
"=>",
"$",
"model",
",",
"]",
")",
";",
"}",
"}"
] | Creates a new Role model.
If creation is successful, the browser will be redirected to the 'view' page.
@return mixed | [
"Creates",
"a",
"new",
"Role",
"model",
".",
"If",
"creation",
"is",
"successful",
"the",
"browser",
"will",
"be",
"redirected",
"to",
"the",
"view",
"page",
"."
] | 6792d1d0d2c0bf01fe87729985b5659de4c1aac1 | https://github.com/maddoger/yii2-cms-user/blob/6792d1d0d2c0bf01fe87729985b5659de4c1aac1/backend/controllers/RoleController.php#L99-L110 | train |
maddoger/yii2-cms-user | backend/controllers/RoleController.php | RoleController.findModel | protected function findModel($id)
{
if (($model = Role::findByName($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException(Yii::t('maddoger/user', 'The requested role does not exist.'));
}
} | php | protected function findModel($id)
{
if (($model = Role::findByName($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException(Yii::t('maddoger/user', 'The requested role does not exist.'));
}
} | [
"protected",
"function",
"findModel",
"(",
"$",
"id",
")",
"{",
"if",
"(",
"(",
"$",
"model",
"=",
"Role",
"::",
"findByName",
"(",
"$",
"id",
")",
")",
"!==",
"null",
")",
"{",
"return",
"$",
"model",
";",
"}",
"else",
"{",
"throw",
"new",
"NotFoundHttpException",
"(",
"Yii",
"::",
"t",
"(",
"'maddoger/user'",
",",
"'The requested role does not exist.'",
")",
")",
";",
"}",
"}"
] | Finds the Role model based on its primary key value.
If the model is not found, a 404 HTTP exception will be thrown.
@param string $id
@return Role the loaded model
@throws NotFoundHttpException if the model cannot be found | [
"Finds",
"the",
"Role",
"model",
"based",
"on",
"its",
"primary",
"key",
"value",
".",
"If",
"the",
"model",
"is",
"not",
"found",
"a",
"404",
"HTTP",
"exception",
"will",
"be",
"thrown",
"."
] | 6792d1d0d2c0bf01fe87729985b5659de4c1aac1 | https://github.com/maddoger/yii2-cms-user/blob/6792d1d0d2c0bf01fe87729985b5659de4c1aac1/backend/controllers/RoleController.php#L341-L348 | train |
zodream/database | src/Query/Builder.php | Builder.flush | public function flush($tag) {
$args = func_get_args();
foreach ($args as $item) {
if (in_array($item, $this->sequence)) {
$this->$item = [];
}
}
return $this;
} | php | public function flush($tag) {
$args = func_get_args();
foreach ($args as $item) {
if (in_array($item, $this->sequence)) {
$this->$item = [];
}
}
return $this;
} | [
"public",
"function",
"flush",
"(",
"$",
"tag",
")",
"{",
"$",
"args",
"=",
"func_get_args",
"(",
")",
";",
"foreach",
"(",
"$",
"args",
"as",
"$",
"item",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"item",
",",
"$",
"this",
"->",
"sequence",
")",
")",
"{",
"$",
"this",
"->",
"$",
"item",
"=",
"[",
"]",
";",
"}",
"}",
"return",
"$",
"this",
";",
"}"
] | MAKE LIKE 'SELECT' TO EMPTY ARRAY!
@param $tag
@return static | [
"MAKE",
"LIKE",
"SELECT",
"TO",
"EMPTY",
"ARRAY!"
] | 03712219c057799d07350a3a2650c55bcc92c28e | https://github.com/zodream/database/blob/03712219c057799d07350a3a2650c55bcc92c28e/src/Query/Builder.php#L94-L102 | train |
zodream/database | src/Query/Builder.php | Builder.getBindings | public function getBindings() {
$keys = func_num_args() < 1 ? array_keys($this->bindings) : func_get_args();
$args = [];
foreach ($keys as $item) {
if (!array_key_exists($item, $this->bindings)) {
continue;
}
$args = array_merge($args, $this->bindings[$item]);
}
return $args;
} | php | public function getBindings() {
$keys = func_num_args() < 1 ? array_keys($this->bindings) : func_get_args();
$args = [];
foreach ($keys as $item) {
if (!array_key_exists($item, $this->bindings)) {
continue;
}
$args = array_merge($args, $this->bindings[$item]);
}
return $args;
} | [
"public",
"function",
"getBindings",
"(",
")",
"{",
"$",
"keys",
"=",
"func_num_args",
"(",
")",
"<",
"1",
"?",
"array_keys",
"(",
"$",
"this",
"->",
"bindings",
")",
":",
"func_get_args",
"(",
")",
";",
"$",
"args",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"item",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"item",
",",
"$",
"this",
"->",
"bindings",
")",
")",
"{",
"continue",
";",
"}",
"$",
"args",
"=",
"array_merge",
"(",
"$",
"args",
",",
"$",
"this",
"->",
"bindings",
"[",
"$",
"item",
"]",
")",
";",
"}",
"return",
"$",
"args",
";",
"}"
] | Get the current query value bindings in a flattened array.
@return array | [
"Get",
"the",
"current",
"query",
"value",
"bindings",
"in",
"a",
"flattened",
"array",
"."
] | 03712219c057799d07350a3a2650c55bcc92c28e | https://github.com/zodream/database/blob/03712219c057799d07350a3a2650c55bcc92c28e/src/Query/Builder.php#L253-L263 | train |
sil-project/SeedBatchBundle | src/Entity/CertificationType.php | CertificationType.setLogo | public function setLogo($logo = null)
{
// @TODO: Ugly hack to avoid $form->handleRequest() changing this value from null to empty array
if (is_array($logo)) {
$logo = null;
}
$this->logo = $logo;
return $this;
} | php | public function setLogo($logo = null)
{
// @TODO: Ugly hack to avoid $form->handleRequest() changing this value from null to empty array
if (is_array($logo)) {
$logo = null;
}
$this->logo = $logo;
return $this;
} | [
"public",
"function",
"setLogo",
"(",
"$",
"logo",
"=",
"null",
")",
"{",
"// @TODO: Ugly hack to avoid $form->handleRequest() changing this value from null to empty array",
"if",
"(",
"is_array",
"(",
"$",
"logo",
")",
")",
"{",
"$",
"logo",
"=",
"null",
";",
"}",
"$",
"this",
"->",
"logo",
"=",
"$",
"logo",
";",
"return",
"$",
"this",
";",
"}"
] | Set logo.
@param \Librinfo\MediaBundle\Entity\File $logo
@return CertificationType | [
"Set",
"logo",
"."
] | a2640b5359fe31d3bdb9c9fa2f72141ac841729c | https://github.com/sil-project/SeedBatchBundle/blob/a2640b5359fe31d3bdb9c9fa2f72141ac841729c/src/Entity/CertificationType.php#L98-L108 | train |
enikeishik/ufoframework | src/Ufo/Modules/Controller.php | Controller.compose | public function compose(Section $section = null): Result
{
$this->container->set('section', $section);
if (null !== $section) {
$this->initParams();
$this->setParams($section->params);
$this->container->set('params', $this->params);
}
$this->setData($section);
return new Result($this->getView());
} | php | public function compose(Section $section = null): Result
{
$this->container->set('section', $section);
if (null !== $section) {
$this->initParams();
$this->setParams($section->params);
$this->container->set('params', $this->params);
}
$this->setData($section);
return new Result($this->getView());
} | [
"public",
"function",
"compose",
"(",
"Section",
"$",
"section",
"=",
"null",
")",
":",
"Result",
"{",
"$",
"this",
"->",
"container",
"->",
"set",
"(",
"'section'",
",",
"$",
"section",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"section",
")",
"{",
"$",
"this",
"->",
"initParams",
"(",
")",
";",
"$",
"this",
"->",
"setParams",
"(",
"$",
"section",
"->",
"params",
")",
";",
"$",
"this",
"->",
"container",
"->",
"set",
"(",
"'params'",
",",
"$",
"this",
"->",
"params",
")",
";",
"}",
"$",
"this",
"->",
"setData",
"(",
"$",
"section",
")",
";",
"return",
"new",
"Result",
"(",
"$",
"this",
"->",
"getView",
"(",
")",
")",
";",
"}"
] | Main controller method, compose all content.
@param \Ufo\Core\Section $section = null
@return \Ufo\Core\Result
@throws \Ufo\Core\ModuleParameterConflictException
@throws \Ufo\Core\ModuleParameterFormatException;
@throws \Ufo\Core\ModuleParameterUnknownException | [
"Main",
"controller",
"method",
"compose",
"all",
"content",
"."
] | fb44461bcb0506dbc3257724a2281f756594f62f | https://github.com/enikeishik/ufoframework/blob/fb44461bcb0506dbc3257724a2281f756594f62f/src/Ufo/Modules/Controller.php#L71-L84 | train |
enikeishik/ufoframework | src/Ufo/Modules/Controller.php | Controller.initParams | protected function initParams(): void
{
if (0 != count($this->params)) {
return;
}
$this->addParams([
Parameter::makeBool('isRoot', '', 'none', false, true),
Parameter::makeBool('isRss', 'rss', 'path', false, false),
Parameter::makeInt('itemId', '', 'path', false, 0),
Parameter::makeInt('page', 'page', 'path', true, 1),
]);
} | php | protected function initParams(): void
{
if (0 != count($this->params)) {
return;
}
$this->addParams([
Parameter::makeBool('isRoot', '', 'none', false, true),
Parameter::makeBool('isRss', 'rss', 'path', false, false),
Parameter::makeInt('itemId', '', 'path', false, 0),
Parameter::makeInt('page', 'page', 'path', true, 1),
]);
} | [
"protected",
"function",
"initParams",
"(",
")",
":",
"void",
"{",
"if",
"(",
"0",
"!=",
"count",
"(",
"$",
"this",
"->",
"params",
")",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"addParams",
"(",
"[",
"Parameter",
"::",
"makeBool",
"(",
"'isRoot'",
",",
"''",
",",
"'none'",
",",
"false",
",",
"true",
")",
",",
"Parameter",
"::",
"makeBool",
"(",
"'isRss'",
",",
"'rss'",
",",
"'path'",
",",
"false",
",",
"false",
")",
",",
"Parameter",
"::",
"makeInt",
"(",
"'itemId'",
",",
"''",
",",
"'path'",
",",
"false",
",",
"0",
")",
",",
"Parameter",
"::",
"makeInt",
"(",
"'page'",
",",
"'page'",
",",
"'path'",
",",
"true",
",",
"1",
")",
",",
"]",
")",
";",
"}"
] | Initialization of structures of module parameters with default values.
@return void | [
"Initialization",
"of",
"structures",
"of",
"module",
"parameters",
"with",
"default",
"values",
"."
] | fb44461bcb0506dbc3257724a2281f756594f62f | https://github.com/enikeishik/ufoframework/blob/fb44461bcb0506dbc3257724a2281f756594f62f/src/Ufo/Modules/Controller.php#L110-L122 | train |
enikeishik/ufoframework | src/Ufo/Modules/Controller.php | Controller.setDataFromModel | protected function setDataFromModel(ModelInterface $model): void
{
$this->container->set('model', $model);
foreach (get_class_methods($model) as $method) {
if (0 !== strpos($method, 'get')) {
continue;
}
$this->data[strtolower(substr($method, 3))] = $model->$method();
}
} | php | protected function setDataFromModel(ModelInterface $model): void
{
$this->container->set('model', $model);
foreach (get_class_methods($model) as $method) {
if (0 !== strpos($method, 'get')) {
continue;
}
$this->data[strtolower(substr($method, 3))] = $model->$method();
}
} | [
"protected",
"function",
"setDataFromModel",
"(",
"ModelInterface",
"$",
"model",
")",
":",
"void",
"{",
"$",
"this",
"->",
"container",
"->",
"set",
"(",
"'model'",
",",
"$",
"model",
")",
";",
"foreach",
"(",
"get_class_methods",
"(",
"$",
"model",
")",
"as",
"$",
"method",
")",
"{",
"if",
"(",
"0",
"!==",
"strpos",
"(",
"$",
"method",
",",
"'get'",
")",
")",
"{",
"continue",
";",
"}",
"$",
"this",
"->",
"data",
"[",
"strtolower",
"(",
"substr",
"(",
"$",
"method",
",",
"3",
")",
")",
"]",
"=",
"$",
"model",
"->",
"$",
"method",
"(",
")",
";",
"}",
"}"
] | This implementation calls all methods with prefix `get` from model.
Implementation may be overridden in inherited method
to call only necessary model methods dependently from parameters.
@param \Ufo\Modules\ModelInterface $model
@return void | [
"This",
"implementation",
"calls",
"all",
"methods",
"with",
"prefix",
"get",
"from",
"model",
".",
"Implementation",
"may",
"be",
"overridden",
"in",
"inherited",
"method",
"to",
"call",
"only",
"necessary",
"model",
"methods",
"dependently",
"from",
"parameters",
"."
] | fb44461bcb0506dbc3257724a2281f756594f62f | https://github.com/enikeishik/ufoframework/blob/fb44461bcb0506dbc3257724a2281f756594f62f/src/Ufo/Modules/Controller.php#L191-L202 | train |
enikeishik/ufoframework | src/Ufo/Modules/Controller.php | Controller.composeWidgets | public function composeWidgets(array $widgetsData): array
{
$container = clone $this->container;
unset($container->widget);
unset($container->widgets);
unset($container->model);
$widgetsResults = [];
foreach ($widgetsData as $place => $placeWidgets) {
$results = [];
foreach ($placeWidgets as $widget) {
if (
!($widget instanceof Widget)
|| empty($widget->vendor)
|| (empty($widget->module) && empty($widget->name))
) {
continue;
}
if (empty($widget->module)) {
$widgetControllerClass =
'\Ufo\Modules' .
'\\' . ucfirst($widget->vendor) .
'\Widgets' .
'\\' . ucfirst($widget->name) .
'\Controller';
} else {
$widgetControllerClass =
'\Ufo\Modules' .
'\\' . ucfirst($widget->vendor) .
'\\' . ucfirst($widget->module) .
'\Widget' . ucfirst($widget->name) . 'Controller';
}
$container->set('widget', $widget);
$container->set('data', get_object_vars($widget));
if (class_exists($widgetControllerClass)) {
$widgetController = new $widgetControllerClass();
if ($widgetController instanceof DIObjectInterface) {
$widgetController->inject($container);
}
$results[] = $widgetController->compose();
} else {
$defaultControllerClass = '\Ufo\Modules\Controller'; //defaultController
$defaultController = new $defaultControllerClass();
$defaultController->inject($container);
$result = $defaultController->compose();
$result->getView()->setTemplate($this->config->templateWidget); //change default template
$results[] = $result;
}
}
$view = new View($this->config->templateWidgets, ['widgets' => $results]);
$view->inject($this->container);
$widgetsResults[$place] = $view;
}
return $widgetsResults;
} | php | public function composeWidgets(array $widgetsData): array
{
$container = clone $this->container;
unset($container->widget);
unset($container->widgets);
unset($container->model);
$widgetsResults = [];
foreach ($widgetsData as $place => $placeWidgets) {
$results = [];
foreach ($placeWidgets as $widget) {
if (
!($widget instanceof Widget)
|| empty($widget->vendor)
|| (empty($widget->module) && empty($widget->name))
) {
continue;
}
if (empty($widget->module)) {
$widgetControllerClass =
'\Ufo\Modules' .
'\\' . ucfirst($widget->vendor) .
'\Widgets' .
'\\' . ucfirst($widget->name) .
'\Controller';
} else {
$widgetControllerClass =
'\Ufo\Modules' .
'\\' . ucfirst($widget->vendor) .
'\\' . ucfirst($widget->module) .
'\Widget' . ucfirst($widget->name) . 'Controller';
}
$container->set('widget', $widget);
$container->set('data', get_object_vars($widget));
if (class_exists($widgetControllerClass)) {
$widgetController = new $widgetControllerClass();
if ($widgetController instanceof DIObjectInterface) {
$widgetController->inject($container);
}
$results[] = $widgetController->compose();
} else {
$defaultControllerClass = '\Ufo\Modules\Controller'; //defaultController
$defaultController = new $defaultControllerClass();
$defaultController->inject($container);
$result = $defaultController->compose();
$result->getView()->setTemplate($this->config->templateWidget); //change default template
$results[] = $result;
}
}
$view = new View($this->config->templateWidgets, ['widgets' => $results]);
$view->inject($this->container);
$widgetsResults[$place] = $view;
}
return $widgetsResults;
} | [
"public",
"function",
"composeWidgets",
"(",
"array",
"$",
"widgetsData",
")",
":",
"array",
"{",
"$",
"container",
"=",
"clone",
"$",
"this",
"->",
"container",
";",
"unset",
"(",
"$",
"container",
"->",
"widget",
")",
";",
"unset",
"(",
"$",
"container",
"->",
"widgets",
")",
";",
"unset",
"(",
"$",
"container",
"->",
"model",
")",
";",
"$",
"widgetsResults",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"widgetsData",
"as",
"$",
"place",
"=>",
"$",
"placeWidgets",
")",
"{",
"$",
"results",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"placeWidgets",
"as",
"$",
"widget",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"widget",
"instanceof",
"Widget",
")",
"||",
"empty",
"(",
"$",
"widget",
"->",
"vendor",
")",
"||",
"(",
"empty",
"(",
"$",
"widget",
"->",
"module",
")",
"&&",
"empty",
"(",
"$",
"widget",
"->",
"name",
")",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"widget",
"->",
"module",
")",
")",
"{",
"$",
"widgetControllerClass",
"=",
"'\\Ufo\\Modules'",
".",
"'\\\\'",
".",
"ucfirst",
"(",
"$",
"widget",
"->",
"vendor",
")",
".",
"'\\Widgets'",
".",
"'\\\\'",
".",
"ucfirst",
"(",
"$",
"widget",
"->",
"name",
")",
".",
"'\\Controller'",
";",
"}",
"else",
"{",
"$",
"widgetControllerClass",
"=",
"'\\Ufo\\Modules'",
".",
"'\\\\'",
".",
"ucfirst",
"(",
"$",
"widget",
"->",
"vendor",
")",
".",
"'\\\\'",
".",
"ucfirst",
"(",
"$",
"widget",
"->",
"module",
")",
".",
"'\\Widget'",
".",
"ucfirst",
"(",
"$",
"widget",
"->",
"name",
")",
".",
"'Controller'",
";",
"}",
"$",
"container",
"->",
"set",
"(",
"'widget'",
",",
"$",
"widget",
")",
";",
"$",
"container",
"->",
"set",
"(",
"'data'",
",",
"get_object_vars",
"(",
"$",
"widget",
")",
")",
";",
"if",
"(",
"class_exists",
"(",
"$",
"widgetControllerClass",
")",
")",
"{",
"$",
"widgetController",
"=",
"new",
"$",
"widgetControllerClass",
"(",
")",
";",
"if",
"(",
"$",
"widgetController",
"instanceof",
"DIObjectInterface",
")",
"{",
"$",
"widgetController",
"->",
"inject",
"(",
"$",
"container",
")",
";",
"}",
"$",
"results",
"[",
"]",
"=",
"$",
"widgetController",
"->",
"compose",
"(",
")",
";",
"}",
"else",
"{",
"$",
"defaultControllerClass",
"=",
"'\\Ufo\\Modules\\Controller'",
";",
"//defaultController",
"$",
"defaultController",
"=",
"new",
"$",
"defaultControllerClass",
"(",
")",
";",
"$",
"defaultController",
"->",
"inject",
"(",
"$",
"container",
")",
";",
"$",
"result",
"=",
"$",
"defaultController",
"->",
"compose",
"(",
")",
";",
"$",
"result",
"->",
"getView",
"(",
")",
"->",
"setTemplate",
"(",
"$",
"this",
"->",
"config",
"->",
"templateWidget",
")",
";",
"//change default template",
"$",
"results",
"[",
"]",
"=",
"$",
"result",
";",
"}",
"}",
"$",
"view",
"=",
"new",
"View",
"(",
"$",
"this",
"->",
"config",
"->",
"templateWidgets",
",",
"[",
"'widgets'",
"=>",
"$",
"results",
"]",
")",
";",
"$",
"view",
"->",
"inject",
"(",
"$",
"this",
"->",
"container",
")",
";",
"$",
"widgetsResults",
"[",
"$",
"place",
"]",
"=",
"$",
"view",
";",
"}",
"return",
"$",
"widgetsResults",
";",
"}"
] | Create object for each widgets data item.
@param array $widgetsData
@return array | [
"Create",
"object",
"for",
"each",
"widgets",
"data",
"item",
"."
] | fb44461bcb0506dbc3257724a2281f756594f62f | https://github.com/enikeishik/ufoframework/blob/fb44461bcb0506dbc3257724a2281f756594f62f/src/Ufo/Modules/Controller.php#L263-L327 | train |
wb-crowdfusion/crowdfusion | system/context/ApplicationContext.php | ApplicationContext.setProperty | protected function setProperty($name, $value)
{
// adds both camelized key and unchanged key to properties
$this->properties[str_replace(' ', '', ltrim(ucwords(preg_replace('/[^A-Z^a-z^0-9]+/', ' ', 'z' . $name)), 'Z'))] = $value;
$this->properties[str_replace(' ', '', ucwords(preg_replace('/[^A-Z^a-z^0-9]+/', ' ', $name)))] = $value;
$this->properties[$name] = $value;
} | php | protected function setProperty($name, $value)
{
// adds both camelized key and unchanged key to properties
$this->properties[str_replace(' ', '', ltrim(ucwords(preg_replace('/[^A-Z^a-z^0-9]+/', ' ', 'z' . $name)), 'Z'))] = $value;
$this->properties[str_replace(' ', '', ucwords(preg_replace('/[^A-Z^a-z^0-9]+/', ' ', $name)))] = $value;
$this->properties[$name] = $value;
} | [
"protected",
"function",
"setProperty",
"(",
"$",
"name",
",",
"$",
"value",
")",
"{",
"// adds both camelized key and unchanged key to properties",
"$",
"this",
"->",
"properties",
"[",
"str_replace",
"(",
"' '",
",",
"''",
",",
"ltrim",
"(",
"ucwords",
"(",
"preg_replace",
"(",
"'/[^A-Z^a-z^0-9]+/'",
",",
"' '",
",",
"'z'",
".",
"$",
"name",
")",
")",
",",
"'Z'",
")",
")",
"]",
"=",
"$",
"value",
";",
"$",
"this",
"->",
"properties",
"[",
"str_replace",
"(",
"' '",
",",
"''",
",",
"ucwords",
"(",
"preg_replace",
"(",
"'/[^A-Z^a-z^0-9]+/'",
",",
"' '",
",",
"$",
"name",
")",
")",
")",
"]",
"=",
"$",
"value",
";",
"$",
"this",
"->",
"properties",
"[",
"$",
"name",
"]",
"=",
"$",
"value",
";",
"}"
] | Sets a property on this container.
@param $name
@param $value | [
"Sets",
"a",
"property",
"on",
"this",
"container",
"."
] | 8cad7988f046a6fefbed07d026cb4ae6706c1217 | https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/context/ApplicationContext.php#L880-L886 | train |
LeadPages/php_pages_component | src/Pages/LeadpagesPages.php | LeadpagesPages.getPages | public function getPages($cursor = false)
{
$queryArray = ['pageSize' => 200];
if ($cursor) {
$queryArray['cursor'] = $cursor;
}
try {
$response = $this->client->get(
$this->PagesUrl, [
'headers' => ['Authorization' => 'Bearer '. $this->login->apiKey],
'verify' => $this->certFile,
'query' => $queryArray
]);
$response = [
'code' => '200',
'response' => $response->getBody(),
'error' => false
];
} catch (ClientException $e) {
$response = $this->parseException($e);
} catch (ServerException $e) {
$response = $this->parseException($e);
} catch (ConnectException $e) {
$message = 'Can not connect to Leadpages Server:';
$response = $this->parseException($e, $message);
} catch (RequestException $e) {
$response = $this->parseException($e);
}
return $response;
} | php | public function getPages($cursor = false)
{
$queryArray = ['pageSize' => 200];
if ($cursor) {
$queryArray['cursor'] = $cursor;
}
try {
$response = $this->client->get(
$this->PagesUrl, [
'headers' => ['Authorization' => 'Bearer '. $this->login->apiKey],
'verify' => $this->certFile,
'query' => $queryArray
]);
$response = [
'code' => '200',
'response' => $response->getBody(),
'error' => false
];
} catch (ClientException $e) {
$response = $this->parseException($e);
} catch (ServerException $e) {
$response = $this->parseException($e);
} catch (ConnectException $e) {
$message = 'Can not connect to Leadpages Server:';
$response = $this->parseException($e, $message);
} catch (RequestException $e) {
$response = $this->parseException($e);
}
return $response;
} | [
"public",
"function",
"getPages",
"(",
"$",
"cursor",
"=",
"false",
")",
"{",
"$",
"queryArray",
"=",
"[",
"'pageSize'",
"=>",
"200",
"]",
";",
"if",
"(",
"$",
"cursor",
")",
"{",
"$",
"queryArray",
"[",
"'cursor'",
"]",
"=",
"$",
"cursor",
";",
"}",
"try",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"get",
"(",
"$",
"this",
"->",
"PagesUrl",
",",
"[",
"'headers'",
"=>",
"[",
"'Authorization'",
"=>",
"'Bearer '",
".",
"$",
"this",
"->",
"login",
"->",
"apiKey",
"]",
",",
"'verify'",
"=>",
"$",
"this",
"->",
"certFile",
",",
"'query'",
"=>",
"$",
"queryArray",
"]",
")",
";",
"$",
"response",
"=",
"[",
"'code'",
"=>",
"'200'",
",",
"'response'",
"=>",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"'error'",
"=>",
"false",
"]",
";",
"}",
"catch",
"(",
"ClientException",
"$",
"e",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"parseException",
"(",
"$",
"e",
")",
";",
"}",
"catch",
"(",
"ServerException",
"$",
"e",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"parseException",
"(",
"$",
"e",
")",
";",
"}",
"catch",
"(",
"ConnectException",
"$",
"e",
")",
"{",
"$",
"message",
"=",
"'Can not connect to Leadpages Server:'",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"parseException",
"(",
"$",
"e",
",",
"$",
"message",
")",
";",
"}",
"catch",
"(",
"RequestException",
"$",
"e",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"parseException",
"(",
"$",
"e",
")",
";",
"}",
"return",
"$",
"response",
";",
"}"
] | Base function get call get users pages
@param bool $cursor default false
@return array | [
"Base",
"function",
"get",
"call",
"get",
"users",
"pages"
] | 1be2742c402793ddacb3730d28058f6b418abeb4 | https://github.com/LeadPages/php_pages_component/blob/1be2742c402793ddacb3730d28058f6b418abeb4/src/Pages/LeadpagesPages.php#L51-L87 | train |
LeadPages/php_pages_component | src/Pages/LeadpagesPages.php | LeadpagesPages.getAllUserPages | public function getAllUserPages($returnResponse = array(), $cursor = false)
{
if (empty($this->login->apiKey)) {
$this->login->getApiKey();
}
//get & parse response
$response = $this->getPages($cursor);
$response = json_decode($response['response'], true);
if (empty($returnResponse) && empty($response['_items'])) {
echo '<p><strong>You appear to have no Leadpages created yet.</strong></p>
<p> Please login to <a href="https://my.leadpages.net" target="_blank">Leadpages</a>
and create a Leadpage to continue.</p>';
die();
}
//if we have more pages add these pages to returnResponse and pass it back into this method
//to run again
if ($response['_meta']['hasMore'] == 'true') {
$returnResponse[] = $response['_items'];
return $this->getAllUserPages($returnResponse, $response['_meta']['nextCursor']);
}
//once we run out of hasMore pages return the response with all pages returned
if (!$response['_meta']['hasMore']) {
/**
* add last result to return response
*/
$returnResponse[] = $response['_items'];
/**
* this maybe a bit hacky but for recursive and compatibility with other functions
* needed all items to be under one array under _items array
*/
if (isset($returnResponse) && count($returnResponse) > 0) {
$pages = array(
'_items' => array()
);
foreach ($returnResponse as $subarray) {
$pages['_items'] = array_merge($pages['_items'], $subarray);
}
//strip out unpublished pages
//sort pages asc by name
return $this->sortPages($this->stripB3NonPublished($pages));
}
}
} | php | public function getAllUserPages($returnResponse = array(), $cursor = false)
{
if (empty($this->login->apiKey)) {
$this->login->getApiKey();
}
//get & parse response
$response = $this->getPages($cursor);
$response = json_decode($response['response'], true);
if (empty($returnResponse) && empty($response['_items'])) {
echo '<p><strong>You appear to have no Leadpages created yet.</strong></p>
<p> Please login to <a href="https://my.leadpages.net" target="_blank">Leadpages</a>
and create a Leadpage to continue.</p>';
die();
}
//if we have more pages add these pages to returnResponse and pass it back into this method
//to run again
if ($response['_meta']['hasMore'] == 'true') {
$returnResponse[] = $response['_items'];
return $this->getAllUserPages($returnResponse, $response['_meta']['nextCursor']);
}
//once we run out of hasMore pages return the response with all pages returned
if (!$response['_meta']['hasMore']) {
/**
* add last result to return response
*/
$returnResponse[] = $response['_items'];
/**
* this maybe a bit hacky but for recursive and compatibility with other functions
* needed all items to be under one array under _items array
*/
if (isset($returnResponse) && count($returnResponse) > 0) {
$pages = array(
'_items' => array()
);
foreach ($returnResponse as $subarray) {
$pages['_items'] = array_merge($pages['_items'], $subarray);
}
//strip out unpublished pages
//sort pages asc by name
return $this->sortPages($this->stripB3NonPublished($pages));
}
}
} | [
"public",
"function",
"getAllUserPages",
"(",
"$",
"returnResponse",
"=",
"array",
"(",
")",
",",
"$",
"cursor",
"=",
"false",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"login",
"->",
"apiKey",
")",
")",
"{",
"$",
"this",
"->",
"login",
"->",
"getApiKey",
"(",
")",
";",
"}",
"//get & parse response",
"$",
"response",
"=",
"$",
"this",
"->",
"getPages",
"(",
"$",
"cursor",
")",
";",
"$",
"response",
"=",
"json_decode",
"(",
"$",
"response",
"[",
"'response'",
"]",
",",
"true",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"returnResponse",
")",
"&&",
"empty",
"(",
"$",
"response",
"[",
"'_items'",
"]",
")",
")",
"{",
"echo",
"'<p><strong>You appear to have no Leadpages created yet.</strong></p>\n <p> Please login to <a href=\"https://my.leadpages.net\" target=\"_blank\">Leadpages</a>\n and create a Leadpage to continue.</p>'",
";",
"die",
"(",
")",
";",
"}",
"//if we have more pages add these pages to returnResponse and pass it back into this method",
"//to run again",
"if",
"(",
"$",
"response",
"[",
"'_meta'",
"]",
"[",
"'hasMore'",
"]",
"==",
"'true'",
")",
"{",
"$",
"returnResponse",
"[",
"]",
"=",
"$",
"response",
"[",
"'_items'",
"]",
";",
"return",
"$",
"this",
"->",
"getAllUserPages",
"(",
"$",
"returnResponse",
",",
"$",
"response",
"[",
"'_meta'",
"]",
"[",
"'nextCursor'",
"]",
")",
";",
"}",
"//once we run out of hasMore pages return the response with all pages returned",
"if",
"(",
"!",
"$",
"response",
"[",
"'_meta'",
"]",
"[",
"'hasMore'",
"]",
")",
"{",
"/**\n * add last result to return response\n */",
"$",
"returnResponse",
"[",
"]",
"=",
"$",
"response",
"[",
"'_items'",
"]",
";",
"/**\n * this maybe a bit hacky but for recursive and compatibility with other functions\n * needed all items to be under one array under _items array\n */",
"if",
"(",
"isset",
"(",
"$",
"returnResponse",
")",
"&&",
"count",
"(",
"$",
"returnResponse",
")",
">",
"0",
")",
"{",
"$",
"pages",
"=",
"array",
"(",
"'_items'",
"=>",
"array",
"(",
")",
")",
";",
"foreach",
"(",
"$",
"returnResponse",
"as",
"$",
"subarray",
")",
"{",
"$",
"pages",
"[",
"'_items'",
"]",
"=",
"array_merge",
"(",
"$",
"pages",
"[",
"'_items'",
"]",
",",
"$",
"subarray",
")",
";",
"}",
"//strip out unpublished pages",
"//sort pages asc by name",
"return",
"$",
"this",
"->",
"sortPages",
"(",
"$",
"this",
"->",
"stripB3NonPublished",
"(",
"$",
"pages",
")",
")",
";",
"}",
"}",
"}"
] | Recursive function to get all of a users pages
@param array $returnResponse
@param bool $cursor
@return mixed | [
"Recursive",
"function",
"to",
"get",
"all",
"of",
"a",
"users",
"pages"
] | 1be2742c402793ddacb3730d28058f6b418abeb4 | https://github.com/LeadPages/php_pages_component/blob/1be2742c402793ddacb3730d28058f6b418abeb4/src/Pages/LeadpagesPages.php#L97-L146 | train |
LeadPages/php_pages_component | src/Pages/LeadpagesPages.php | LeadpagesPages.stripB3NonPublished | public function stripB3NonPublished($pages)
{
foreach ($pages['_items'] as $index => $page) {
if ($page['isBuilderThreePage'] && !$page['isBuilderThreePublished']) {
unset($pages['_items'][$index]);
}
}
return $pages;
} | php | public function stripB3NonPublished($pages)
{
foreach ($pages['_items'] as $index => $page) {
if ($page['isBuilderThreePage'] && !$page['isBuilderThreePublished']) {
unset($pages['_items'][$index]);
}
}
return $pages;
} | [
"public",
"function",
"stripB3NonPublished",
"(",
"$",
"pages",
")",
"{",
"foreach",
"(",
"$",
"pages",
"[",
"'_items'",
"]",
"as",
"$",
"index",
"=>",
"$",
"page",
")",
"{",
"if",
"(",
"$",
"page",
"[",
"'isBuilderThreePage'",
"]",
"&&",
"!",
"$",
"page",
"[",
"'isBuilderThreePublished'",
"]",
")",
"{",
"unset",
"(",
"$",
"pages",
"[",
"'_items'",
"]",
"[",
"$",
"index",
"]",
")",
";",
"}",
"}",
"return",
"$",
"pages",
";",
"}"
] | Remove non published B3 pages
@param mixed $pages
@return mixed | [
"Remove",
"non",
"published",
"B3",
"pages"
] | 1be2742c402793ddacb3730d28058f6b418abeb4 | https://github.com/LeadPages/php_pages_component/blob/1be2742c402793ddacb3730d28058f6b418abeb4/src/Pages/LeadpagesPages.php#L156-L165 | train |
LeadPages/php_pages_component | src/Pages/LeadpagesPages.php | LeadpagesPages.sortPages | public function sortPages($pages)
{
usort($pages['_items'], function ($a, $b) {
//need to convert them to lowercase strings for equal comparison
return strcmp(strtolower($a["name"]), strtolower($b["name"]));
});
return $pages;
} | php | public function sortPages($pages)
{
usort($pages['_items'], function ($a, $b) {
//need to convert them to lowercase strings for equal comparison
return strcmp(strtolower($a["name"]), strtolower($b["name"]));
});
return $pages;
} | [
"public",
"function",
"sortPages",
"(",
"$",
"pages",
")",
"{",
"usort",
"(",
"$",
"pages",
"[",
"'_items'",
"]",
",",
"function",
"(",
"$",
"a",
",",
"$",
"b",
")",
"{",
"//need to convert them to lowercase strings for equal comparison",
"return",
"strcmp",
"(",
"strtolower",
"(",
"$",
"a",
"[",
"\"name\"",
"]",
")",
",",
"strtolower",
"(",
"$",
"b",
"[",
"\"name\"",
"]",
")",
")",
";",
"}",
")",
";",
"return",
"$",
"pages",
";",
"}"
] | sort pages in alphabetical user
@param mixed $pages
@return mixed | [
"sort",
"pages",
"in",
"alphabetical",
"user"
] | 1be2742c402793ddacb3730d28058f6b418abeb4 | https://github.com/LeadPages/php_pages_component/blob/1be2742c402793ddacb3730d28058f6b418abeb4/src/Pages/LeadpagesPages.php#L174-L182 | train |
LeadPages/php_pages_component | src/Pages/LeadpagesPages.php | LeadpagesPages.getSinglePageDownloadUrl | public function getSinglePageDownloadUrl($pageId)
{
try {
$response = $this->client->get($this->PagesUrl . '/' . $pageId, [
'headers' => ['Authorization' => 'Bearer '. $this->login->apiKey],
'verify' => $this->certFile,
]);
$body = json_decode($response->getBody(), true);
$url = $body['_meta']['publishUrl'];
$responseText = ['url' => $url];
$response = [
'code' => '200',
'response' => json_encode($responseText),
'error' => false
];
} catch (ClientException $e) {
$httpResponse = $e->getResponse();
// 404 means their Leadpage in their account probably got deleted
if ($httpResponse->getStatusCode() == 404) {
$response = [
'code' => $httpResponse->getStatusCode(),
'response' => "
Your Leadpage could not be found! Please make sure it is published in your Leadpages Account <br />
<br />
Support Info:<br />
<strong>Page id:</strong> {$pageId} <br />
<strong>Page url:</strong> {$this->PagesUrl}/{$pageId}",
'error' => true
];
} else {
$message = 'Something went wrong, please contact Leadpages support.';
$response = $this->parseException($e);
}
} catch (ServerException $e) {
$response = $this->parseException($e);
} catch (ConnectException $e) {
$message = 'Can not connect to Leadpages Server:';
$response = $this->parseException($e, $message);
} catch (RequestException $e) {
$response = $this->parseException($e);
}
return $response;
} | php | public function getSinglePageDownloadUrl($pageId)
{
try {
$response = $this->client->get($this->PagesUrl . '/' . $pageId, [
'headers' => ['Authorization' => 'Bearer '. $this->login->apiKey],
'verify' => $this->certFile,
]);
$body = json_decode($response->getBody(), true);
$url = $body['_meta']['publishUrl'];
$responseText = ['url' => $url];
$response = [
'code' => '200',
'response' => json_encode($responseText),
'error' => false
];
} catch (ClientException $e) {
$httpResponse = $e->getResponse();
// 404 means their Leadpage in their account probably got deleted
if ($httpResponse->getStatusCode() == 404) {
$response = [
'code' => $httpResponse->getStatusCode(),
'response' => "
Your Leadpage could not be found! Please make sure it is published in your Leadpages Account <br />
<br />
Support Info:<br />
<strong>Page id:</strong> {$pageId} <br />
<strong>Page url:</strong> {$this->PagesUrl}/{$pageId}",
'error' => true
];
} else {
$message = 'Something went wrong, please contact Leadpages support.';
$response = $this->parseException($e);
}
} catch (ServerException $e) {
$response = $this->parseException($e);
} catch (ConnectException $e) {
$message = 'Can not connect to Leadpages Server:';
$response = $this->parseException($e, $message);
} catch (RequestException $e) {
$response = $this->parseException($e);
}
return $response;
} | [
"public",
"function",
"getSinglePageDownloadUrl",
"(",
"$",
"pageId",
")",
"{",
"try",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"get",
"(",
"$",
"this",
"->",
"PagesUrl",
".",
"'/'",
".",
"$",
"pageId",
",",
"[",
"'headers'",
"=>",
"[",
"'Authorization'",
"=>",
"'Bearer '",
".",
"$",
"this",
"->",
"login",
"->",
"apiKey",
"]",
",",
"'verify'",
"=>",
"$",
"this",
"->",
"certFile",
",",
"]",
")",
";",
"$",
"body",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"$",
"url",
"=",
"$",
"body",
"[",
"'_meta'",
"]",
"[",
"'publishUrl'",
"]",
";",
"$",
"responseText",
"=",
"[",
"'url'",
"=>",
"$",
"url",
"]",
";",
"$",
"response",
"=",
"[",
"'code'",
"=>",
"'200'",
",",
"'response'",
"=>",
"json_encode",
"(",
"$",
"responseText",
")",
",",
"'error'",
"=>",
"false",
"]",
";",
"}",
"catch",
"(",
"ClientException",
"$",
"e",
")",
"{",
"$",
"httpResponse",
"=",
"$",
"e",
"->",
"getResponse",
"(",
")",
";",
"// 404 means their Leadpage in their account probably got deleted",
"if",
"(",
"$",
"httpResponse",
"->",
"getStatusCode",
"(",
")",
"==",
"404",
")",
"{",
"$",
"response",
"=",
"[",
"'code'",
"=>",
"$",
"httpResponse",
"->",
"getStatusCode",
"(",
")",
",",
"'response'",
"=>",
"\"\n Your Leadpage could not be found! Please make sure it is published in your Leadpages Account <br />\n <br />\n Support Info:<br />\n <strong>Page id:</strong> {$pageId} <br />\n <strong>Page url:</strong> {$this->PagesUrl}/{$pageId}\"",
",",
"'error'",
"=>",
"true",
"]",
";",
"}",
"else",
"{",
"$",
"message",
"=",
"'Something went wrong, please contact Leadpages support.'",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"parseException",
"(",
"$",
"e",
")",
";",
"}",
"}",
"catch",
"(",
"ServerException",
"$",
"e",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"parseException",
"(",
"$",
"e",
")",
";",
"}",
"catch",
"(",
"ConnectException",
"$",
"e",
")",
"{",
"$",
"message",
"=",
"'Can not connect to Leadpages Server:'",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"parseException",
"(",
"$",
"e",
",",
"$",
"message",
")",
";",
"}",
"catch",
"(",
"RequestException",
"$",
"e",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"parseException",
"(",
"$",
"e",
")",
";",
"}",
"return",
"$",
"response",
";",
"}"
] | Get the url to download the page url from
@param string $pageId
@return array | [
"Get",
"the",
"url",
"to",
"download",
"the",
"page",
"url",
"from"
] | 1be2742c402793ddacb3730d28058f6b418abeb4 | https://github.com/LeadPages/php_pages_component/blob/1be2742c402793ddacb3730d28058f6b418abeb4/src/Pages/LeadpagesPages.php#L191-L241 | train |
LeadPages/php_pages_component | src/Pages/LeadpagesPages.php | LeadpagesPages.downloadPageHtml | public function downloadPageHtml($pageId, $isRetry = false)
{
if (is_null($this->login->apiKey)) {
$this->login->apiKey = $this->login->getApiKey();
}
$response = $this->getSinglePageDownloadUrl($pageId);
if ($response['error']) {
return $response;
}
$responseArray = json_decode($response['response'], true);
$url = $responseArray['url'];
if ($isRetry) {
$url = str_replace('https:', 'http:', $url);
}
$options = [
'verify' => !$isRetry ? $this->certFile : false,
];
foreach ($_COOKIE as $index => $value) {
if (strpos($index, 'splitTestV2URI') !== false) {
$options['cookies'] = [$index => $value];
}
}
try {
$html = $this->client->get($url, $options);
$response = [
'code' => 200,
'response' => $html->getBody()->getContents(),
];
if (count($this->getPageSplitTestCookie($html)) > 0) {
$response['splitTestCookie'] = $this->getPageSplitTestCookie($html);
}
} catch (ClientException $e) {
$response = $this->parseException($e);
} catch (RequestException $e) {
$response = $this->parseException($e);
if (!$isRetry) {
$response = $this->downloadPageHtml($pageId, true);
}
} catch (ServerException $e) {
$response = $this->parseException($e);
} catch (ConnectException $e) {
$message = 'Can not connect to Leadpages Server:';
$response = $this->parseException($e, $message);
}
return $response;
} | php | public function downloadPageHtml($pageId, $isRetry = false)
{
if (is_null($this->login->apiKey)) {
$this->login->apiKey = $this->login->getApiKey();
}
$response = $this->getSinglePageDownloadUrl($pageId);
if ($response['error']) {
return $response;
}
$responseArray = json_decode($response['response'], true);
$url = $responseArray['url'];
if ($isRetry) {
$url = str_replace('https:', 'http:', $url);
}
$options = [
'verify' => !$isRetry ? $this->certFile : false,
];
foreach ($_COOKIE as $index => $value) {
if (strpos($index, 'splitTestV2URI') !== false) {
$options['cookies'] = [$index => $value];
}
}
try {
$html = $this->client->get($url, $options);
$response = [
'code' => 200,
'response' => $html->getBody()->getContents(),
];
if (count($this->getPageSplitTestCookie($html)) > 0) {
$response['splitTestCookie'] = $this->getPageSplitTestCookie($html);
}
} catch (ClientException $e) {
$response = $this->parseException($e);
} catch (RequestException $e) {
$response = $this->parseException($e);
if (!$isRetry) {
$response = $this->downloadPageHtml($pageId, true);
}
} catch (ServerException $e) {
$response = $this->parseException($e);
} catch (ConnectException $e) {
$message = 'Can not connect to Leadpages Server:';
$response = $this->parseException($e, $message);
}
return $response;
} | [
"public",
"function",
"downloadPageHtml",
"(",
"$",
"pageId",
",",
"$",
"isRetry",
"=",
"false",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"login",
"->",
"apiKey",
")",
")",
"{",
"$",
"this",
"->",
"login",
"->",
"apiKey",
"=",
"$",
"this",
"->",
"login",
"->",
"getApiKey",
"(",
")",
";",
"}",
"$",
"response",
"=",
"$",
"this",
"->",
"getSinglePageDownloadUrl",
"(",
"$",
"pageId",
")",
";",
"if",
"(",
"$",
"response",
"[",
"'error'",
"]",
")",
"{",
"return",
"$",
"response",
";",
"}",
"$",
"responseArray",
"=",
"json_decode",
"(",
"$",
"response",
"[",
"'response'",
"]",
",",
"true",
")",
";",
"$",
"url",
"=",
"$",
"responseArray",
"[",
"'url'",
"]",
";",
"if",
"(",
"$",
"isRetry",
")",
"{",
"$",
"url",
"=",
"str_replace",
"(",
"'https:'",
",",
"'http:'",
",",
"$",
"url",
")",
";",
"}",
"$",
"options",
"=",
"[",
"'verify'",
"=>",
"!",
"$",
"isRetry",
"?",
"$",
"this",
"->",
"certFile",
":",
"false",
",",
"]",
";",
"foreach",
"(",
"$",
"_COOKIE",
"as",
"$",
"index",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"index",
",",
"'splitTestV2URI'",
")",
"!==",
"false",
")",
"{",
"$",
"options",
"[",
"'cookies'",
"]",
"=",
"[",
"$",
"index",
"=>",
"$",
"value",
"]",
";",
"}",
"}",
"try",
"{",
"$",
"html",
"=",
"$",
"this",
"->",
"client",
"->",
"get",
"(",
"$",
"url",
",",
"$",
"options",
")",
";",
"$",
"response",
"=",
"[",
"'code'",
"=>",
"200",
",",
"'response'",
"=>",
"$",
"html",
"->",
"getBody",
"(",
")",
"->",
"getContents",
"(",
")",
",",
"]",
";",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"getPageSplitTestCookie",
"(",
"$",
"html",
")",
")",
">",
"0",
")",
"{",
"$",
"response",
"[",
"'splitTestCookie'",
"]",
"=",
"$",
"this",
"->",
"getPageSplitTestCookie",
"(",
"$",
"html",
")",
";",
"}",
"}",
"catch",
"(",
"ClientException",
"$",
"e",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"parseException",
"(",
"$",
"e",
")",
";",
"}",
"catch",
"(",
"RequestException",
"$",
"e",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"parseException",
"(",
"$",
"e",
")",
";",
"if",
"(",
"!",
"$",
"isRetry",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"downloadPageHtml",
"(",
"$",
"pageId",
",",
"true",
")",
";",
"}",
"}",
"catch",
"(",
"ServerException",
"$",
"e",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"parseException",
"(",
"$",
"e",
")",
";",
"}",
"catch",
"(",
"ConnectException",
"$",
"e",
")",
"{",
"$",
"message",
"=",
"'Can not connect to Leadpages Server:'",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"parseException",
"(",
"$",
"e",
",",
"$",
"message",
")",
";",
"}",
"return",
"$",
"response",
";",
"}"
] | get url for page, then use a get request to get the html for the page
@todo refactor this
@todo at sometime this should be replaced with a single call to get the html this requires two calls
@param string $pageId Leadpages Page id not wordpress post_id
@param bool $isRetry true downgrades to http
@return mixed | [
"get",
"url",
"for",
"page",
"then",
"use",
"a",
"get",
"request",
"to",
"get",
"the",
"html",
"for",
"the",
"page"
] | 1be2742c402793ddacb3730d28058f6b418abeb4 | https://github.com/LeadPages/php_pages_component/blob/1be2742c402793ddacb3730d28058f6b418abeb4/src/Pages/LeadpagesPages.php#L254-L314 | train |
cinnamonlab/redis | src/Framework/Redis/Redis.php | Redis.connection | public function connection($name = 'default')
{
if ( ! isset($this) ) return self::getInstance()->clients[Config::get("redis.$name")];
return $this->clients[ Config::get("redis.$name") ];
} | php | public function connection($name = 'default')
{
if ( ! isset($this) ) return self::getInstance()->clients[Config::get("redis.$name")];
return $this->clients[ Config::get("redis.$name") ];
} | [
"public",
"function",
"connection",
"(",
"$",
"name",
"=",
"'default'",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
")",
")",
"return",
"self",
"::",
"getInstance",
"(",
")",
"->",
"clients",
"[",
"Config",
"::",
"get",
"(",
"\"redis.$name\"",
")",
"]",
";",
"return",
"$",
"this",
"->",
"clients",
"[",
"Config",
"::",
"get",
"(",
"\"redis.$name\"",
")",
"]",
";",
"}"
] | Get a specific Redis connection instance.
@param string $name
@return \Predis\ClientInterface|null | [
"Get",
"a",
"specific",
"Redis",
"connection",
"instance",
"."
] | 3b5841321441b26d624fb025b8f9a54c23aed40b | https://github.com/cinnamonlab/redis/blob/3b5841321441b26d624fb025b8f9a54c23aed40b/src/Framework/Redis/Redis.php#L79-L83 | train |
zapheus/zapheus | src/Http/Message/MessageFactory.php | MessageFactory.write | public function write($output)
{
$resource = fopen('php://temp', 'r+');
! $resource && $resource = null;
$stream = new Stream($resource);
$stream->write((string) $output);
$this->stream = $stream;
return $this;
} | php | public function write($output)
{
$resource = fopen('php://temp', 'r+');
! $resource && $resource = null;
$stream = new Stream($resource);
$stream->write((string) $output);
$this->stream = $stream;
return $this;
} | [
"public",
"function",
"write",
"(",
"$",
"output",
")",
"{",
"$",
"resource",
"=",
"fopen",
"(",
"'php://temp'",
",",
"'r+'",
")",
";",
"!",
"$",
"resource",
"&&",
"$",
"resource",
"=",
"null",
";",
"$",
"stream",
"=",
"new",
"Stream",
"(",
"$",
"resource",
")",
";",
"$",
"stream",
"->",
"write",
"(",
"(",
"string",
")",
"$",
"output",
")",
";",
"$",
"this",
"->",
"stream",
"=",
"$",
"stream",
";",
"return",
"$",
"this",
";",
"}"
] | Writes data directly to the stream.
@param string $output
@return self | [
"Writes",
"data",
"directly",
"to",
"the",
"stream",
"."
] | 96618b5cee7d20b6700d0475e4334ae4b5163a6b | https://github.com/zapheus/zapheus/blob/96618b5cee7d20b6700d0475e4334ae4b5163a6b/src/Http/Message/MessageFactory.php#L138-L151 | train |
AnonymPHP/Anonym-Database | Pagination/Render.php | Render.simpleRendeArray | public function simpleRendeArray()
{
$array = [];
$count = $this->paginator->getCount();
$url = $this->path;
$current = $this->paginator->getCurrentPage();
// create appends string
$appends = $this->createAppendString($this->paginator->getAppends());
// create fragments string
$fragments = $this->createFragmentsString($this->paginator->getFragments());
if ($count < $this->paginator->getPerPage()) {
$limit = 1;
} else {
$limit = ceil($count / $this->paginator->getPerPage());
}
if ($this->isAvaibleCurrentPage($current) && $current > 1) {
$previous = $current - 1;
$array[] = $this->buildChieldString('Previous', $this->buildFullChieldStrind($url, $appends), $this->pageName, $fragments, $previous);
}
if ($this->isAvaibleCurrentPage($current) && $current < $limit) {
$next = $current + 1;
$array[] = $this->buildChieldString('Next', $this->buildFullChieldStrind($url, $appends), $this->pageName, $fragments, $next);
}
return $array;
} | php | public function simpleRendeArray()
{
$array = [];
$count = $this->paginator->getCount();
$url = $this->path;
$current = $this->paginator->getCurrentPage();
// create appends string
$appends = $this->createAppendString($this->paginator->getAppends());
// create fragments string
$fragments = $this->createFragmentsString($this->paginator->getFragments());
if ($count < $this->paginator->getPerPage()) {
$limit = 1;
} else {
$limit = ceil($count / $this->paginator->getPerPage());
}
if ($this->isAvaibleCurrentPage($current) && $current > 1) {
$previous = $current - 1;
$array[] = $this->buildChieldString('Previous', $this->buildFullChieldStrind($url, $appends), $this->pageName, $fragments, $previous);
}
if ($this->isAvaibleCurrentPage($current) && $current < $limit) {
$next = $current + 1;
$array[] = $this->buildChieldString('Next', $this->buildFullChieldStrind($url, $appends), $this->pageName, $fragments, $next);
}
return $array;
} | [
"public",
"function",
"simpleRendeArray",
"(",
")",
"{",
"$",
"array",
"=",
"[",
"]",
";",
"$",
"count",
"=",
"$",
"this",
"->",
"paginator",
"->",
"getCount",
"(",
")",
";",
"$",
"url",
"=",
"$",
"this",
"->",
"path",
";",
"$",
"current",
"=",
"$",
"this",
"->",
"paginator",
"->",
"getCurrentPage",
"(",
")",
";",
"// create appends string",
"$",
"appends",
"=",
"$",
"this",
"->",
"createAppendString",
"(",
"$",
"this",
"->",
"paginator",
"->",
"getAppends",
"(",
")",
")",
";",
"// create fragments string",
"$",
"fragments",
"=",
"$",
"this",
"->",
"createFragmentsString",
"(",
"$",
"this",
"->",
"paginator",
"->",
"getFragments",
"(",
")",
")",
";",
"if",
"(",
"$",
"count",
"<",
"$",
"this",
"->",
"paginator",
"->",
"getPerPage",
"(",
")",
")",
"{",
"$",
"limit",
"=",
"1",
";",
"}",
"else",
"{",
"$",
"limit",
"=",
"ceil",
"(",
"$",
"count",
"/",
"$",
"this",
"->",
"paginator",
"->",
"getPerPage",
"(",
")",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"isAvaibleCurrentPage",
"(",
"$",
"current",
")",
"&&",
"$",
"current",
">",
"1",
")",
"{",
"$",
"previous",
"=",
"$",
"current",
"-",
"1",
";",
"$",
"array",
"[",
"]",
"=",
"$",
"this",
"->",
"buildChieldString",
"(",
"'Previous'",
",",
"$",
"this",
"->",
"buildFullChieldStrind",
"(",
"$",
"url",
",",
"$",
"appends",
")",
",",
"$",
"this",
"->",
"pageName",
",",
"$",
"fragments",
",",
"$",
"previous",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"isAvaibleCurrentPage",
"(",
"$",
"current",
")",
"&&",
"$",
"current",
"<",
"$",
"limit",
")",
"{",
"$",
"next",
"=",
"$",
"current",
"+",
"1",
";",
"$",
"array",
"[",
"]",
"=",
"$",
"this",
"->",
"buildChieldString",
"(",
"'Next'",
",",
"$",
"this",
"->",
"buildFullChieldStrind",
"(",
"$",
"url",
",",
"$",
"appends",
")",
",",
"$",
"this",
"->",
"pageName",
",",
"$",
"fragments",
",",
"$",
"next",
")",
";",
"}",
"return",
"$",
"array",
";",
"}"
] | create pagination with only previous and next buttons
@return array | [
"create",
"pagination",
"with",
"only",
"previous",
"and",
"next",
"buttons"
] | 4d034219e0e3eb2833fa53204e9f52a74a9a7e4b | https://github.com/AnonymPHP/Anonym-Database/blob/4d034219e0e3eb2833fa53204e9f52a74a9a7e4b/Pagination/Render.php#L136-L171 | train |
AnonymPHP/Anonym-Database | Pagination/Render.php | Render.createBeforeButton | private function createBeforeButton($current, $url, $class, $fragments)
{
if ($this->isAvaibleCurrentPage($current) && $current > 1) {
$page = $current - 1;
return $this->buildChieldString("«", $url, $class, $fragments, $page);
} else {
return false;
}
} | php | private function createBeforeButton($current, $url, $class, $fragments)
{
if ($this->isAvaibleCurrentPage($current) && $current > 1) {
$page = $current - 1;
return $this->buildChieldString("«", $url, $class, $fragments, $page);
} else {
return false;
}
} | [
"private",
"function",
"createBeforeButton",
"(",
"$",
"current",
",",
"$",
"url",
",",
"$",
"class",
",",
"$",
"fragments",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isAvaibleCurrentPage",
"(",
"$",
"current",
")",
"&&",
"$",
"current",
">",
"1",
")",
"{",
"$",
"page",
"=",
"$",
"current",
"-",
"1",
";",
"return",
"$",
"this",
"->",
"buildChieldString",
"(",
"\"«\"",
",",
"$",
"url",
",",
"$",
"class",
",",
"$",
"fragments",
",",
"$",
"page",
")",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | build before button string
@param int $current
@param string $url
@param string $class
@return bool|string | [
"build",
"before",
"button",
"string"
] | 4d034219e0e3eb2833fa53204e9f52a74a9a7e4b | https://github.com/AnonymPHP/Anonym-Database/blob/4d034219e0e3eb2833fa53204e9f52a74a9a7e4b/Pagination/Render.php#L193-L205 | train |
AnonymPHP/Anonym-Database | Pagination/Render.php | Render.createAfterButton | private function createAfterButton($current, $limit, $url, $class, $fragments)
{
if ($this->isAvaibleCurrentPage($current) && $current < $limit) {
$page = $current - 1;
return $this->buildChieldString("«", $url, $class, $fragments, $page);
} else {
return false;
}
} | php | private function createAfterButton($current, $limit, $url, $class, $fragments)
{
if ($this->isAvaibleCurrentPage($current) && $current < $limit) {
$page = $current - 1;
return $this->buildChieldString("«", $url, $class, $fragments, $page);
} else {
return false;
}
} | [
"private",
"function",
"createAfterButton",
"(",
"$",
"current",
",",
"$",
"limit",
",",
"$",
"url",
",",
"$",
"class",
",",
"$",
"fragments",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isAvaibleCurrentPage",
"(",
"$",
"current",
")",
"&&",
"$",
"current",
"<",
"$",
"limit",
")",
"{",
"$",
"page",
"=",
"$",
"current",
"-",
"1",
";",
"return",
"$",
"this",
"->",
"buildChieldString",
"(",
"\"«\"",
",",
"$",
"url",
",",
"$",
"class",
",",
"$",
"fragments",
",",
"$",
"page",
")",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | »
build next button string
@param int $current
@param int $limit
@param string $url
@param string $class
@return bool|string | [
"»",
";",
"build",
"next",
"button",
"string"
] | 4d034219e0e3eb2833fa53204e9f52a74a9a7e4b | https://github.com/AnonymPHP/Anonym-Database/blob/4d034219e0e3eb2833fa53204e9f52a74a9a7e4b/Pagination/Render.php#L216-L226 | train |
AnonymPHP/Anonym-Database | Pagination/Render.php | Render.buildChieldString | private function buildChieldString($page, $url, $pageName, $fragments, $i)
{
settype($page, 'string');
$add = $this->buildAddUrl($url);
$string = $url . $add . $i . $fragments;
return sprintf("<li><a href='%s' class='%s'>%s</a></li>", $string, $pageName, $page);
} | php | private function buildChieldString($page, $url, $pageName, $fragments, $i)
{
settype($page, 'string');
$add = $this->buildAddUrl($url);
$string = $url . $add . $i . $fragments;
return sprintf("<li><a href='%s' class='%s'>%s</a></li>", $string, $pageName, $page);
} | [
"private",
"function",
"buildChieldString",
"(",
"$",
"page",
",",
"$",
"url",
",",
"$",
"pageName",
",",
"$",
"fragments",
",",
"$",
"i",
")",
"{",
"settype",
"(",
"$",
"page",
",",
"'string'",
")",
";",
"$",
"add",
"=",
"$",
"this",
"->",
"buildAddUrl",
"(",
"$",
"url",
")",
";",
"$",
"string",
"=",
"$",
"url",
".",
"$",
"add",
".",
"$",
"i",
".",
"$",
"fragments",
";",
"return",
"sprintf",
"(",
"\"<li><a href='%s' class='%s'>%s</a></li>\"",
",",
"$",
"string",
",",
"$",
"pageName",
",",
"$",
"page",
")",
";",
"}"
] | create chield string
@param string $page
@param string $url
@return string | [
"create",
"chield",
"string"
] | 4d034219e0e3eb2833fa53204e9f52a74a9a7e4b | https://github.com/AnonymPHP/Anonym-Database/blob/4d034219e0e3eb2833fa53204e9f52a74a9a7e4b/Pagination/Render.php#L235-L242 | train |
SlabPHP/controllers | src/Page.php | Page.fetchSubTemplateName | protected function fetchSubTemplateName()
{
if (!empty($this->subTemplate)) return;
$className = get_called_class();
if (mb_strpos($className, 'Controllers') === false)
{
$this->system->log()->notice("Fully qualified Controller class name does not contain 'Controllers' so we can't automatically discern the sub template name.");
return;
}
$classSegments = explode('\\', $className);
$templateName = '';
while (($segment = array_pop($classSegments)) !== 'Controllers')
{
if (empty($templateName))
{
$templateName = strtolower($segment) . '.php';
}
else
{
$templateName = strtolower($segment) . DIRECTORY_SEPARATOR . $templateName;
}
}
$this->subTemplate = 'pages' . DIRECTORY_SEPARATOR . $templateName;
} | php | protected function fetchSubTemplateName()
{
if (!empty($this->subTemplate)) return;
$className = get_called_class();
if (mb_strpos($className, 'Controllers') === false)
{
$this->system->log()->notice("Fully qualified Controller class name does not contain 'Controllers' so we can't automatically discern the sub template name.");
return;
}
$classSegments = explode('\\', $className);
$templateName = '';
while (($segment = array_pop($classSegments)) !== 'Controllers')
{
if (empty($templateName))
{
$templateName = strtolower($segment) . '.php';
}
else
{
$templateName = strtolower($segment) . DIRECTORY_SEPARATOR . $templateName;
}
}
$this->subTemplate = 'pages' . DIRECTORY_SEPARATOR . $templateName;
} | [
"protected",
"function",
"fetchSubTemplateName",
"(",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"subTemplate",
")",
")",
"return",
";",
"$",
"className",
"=",
"get_called_class",
"(",
")",
";",
"if",
"(",
"mb_strpos",
"(",
"$",
"className",
",",
"'Controllers'",
")",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"system",
"->",
"log",
"(",
")",
"->",
"notice",
"(",
"\"Fully qualified Controller class name does not contain 'Controllers' so we can't automatically discern the sub template name.\"",
")",
";",
"return",
";",
"}",
"$",
"classSegments",
"=",
"explode",
"(",
"'\\\\'",
",",
"$",
"className",
")",
";",
"$",
"templateName",
"=",
"''",
";",
"while",
"(",
"(",
"$",
"segment",
"=",
"array_pop",
"(",
"$",
"classSegments",
")",
")",
"!==",
"'Controllers'",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"templateName",
")",
")",
"{",
"$",
"templateName",
"=",
"strtolower",
"(",
"$",
"segment",
")",
".",
"'.php'",
";",
"}",
"else",
"{",
"$",
"templateName",
"=",
"strtolower",
"(",
"$",
"segment",
")",
".",
"DIRECTORY_SEPARATOR",
".",
"$",
"templateName",
";",
"}",
"}",
"$",
"this",
"->",
"subTemplate",
"=",
"'pages'",
".",
"DIRECTORY_SEPARATOR",
".",
"$",
"templateName",
";",
"}"
] | Fetch sub template name | [
"Fetch",
"sub",
"template",
"name"
] | a1c4fded0265100a85904dd664b972a7f8687652 | https://github.com/SlabPHP/controllers/blob/a1c4fded0265100a85904dd664b972a7f8687652/src/Page.php#L126-L154 | train |
judus/minimal-database | src/Connectors/PDO.php | PDO.connection | public function connection($config = null, $forceConnect = false)
{
if ($this->connection && !$forceConnect) {
return $this->connection;
}
!isset($config) || $this->config($config);
$ref = new \ReflectionClass($this->getHandler());
try {
/** @var \PDO $connection */
$this->connection = $ref->newInstanceArgs([
$this->getConnectionString(),
$this->getUser(),
$this->getPassword(),
$this->getHandlerOptions()
]);
} catch (\PDOException $e) {
throw new DatabaseException($e->getMessage());
}
return $this->connection;
} | php | public function connection($config = null, $forceConnect = false)
{
if ($this->connection && !$forceConnect) {
return $this->connection;
}
!isset($config) || $this->config($config);
$ref = new \ReflectionClass($this->getHandler());
try {
/** @var \PDO $connection */
$this->connection = $ref->newInstanceArgs([
$this->getConnectionString(),
$this->getUser(),
$this->getPassword(),
$this->getHandlerOptions()
]);
} catch (\PDOException $e) {
throw new DatabaseException($e->getMessage());
}
return $this->connection;
} | [
"public",
"function",
"connection",
"(",
"$",
"config",
"=",
"null",
",",
"$",
"forceConnect",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"connection",
"&&",
"!",
"$",
"forceConnect",
")",
"{",
"return",
"$",
"this",
"->",
"connection",
";",
"}",
"!",
"isset",
"(",
"$",
"config",
")",
"||",
"$",
"this",
"->",
"config",
"(",
"$",
"config",
")",
";",
"$",
"ref",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"this",
"->",
"getHandler",
"(",
")",
")",
";",
"try",
"{",
"/** @var \\PDO $connection */",
"$",
"this",
"->",
"connection",
"=",
"$",
"ref",
"->",
"newInstanceArgs",
"(",
"[",
"$",
"this",
"->",
"getConnectionString",
"(",
")",
",",
"$",
"this",
"->",
"getUser",
"(",
")",
",",
"$",
"this",
"->",
"getPassword",
"(",
")",
",",
"$",
"this",
"->",
"getHandlerOptions",
"(",
")",
"]",
")",
";",
"}",
"catch",
"(",
"\\",
"PDOException",
"$",
"e",
")",
"{",
"throw",
"new",
"DatabaseException",
"(",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"connection",
";",
"}"
] | Returns a PDO connection
@param null $config
@param bool $forceConnect
@return \PDO
@throws DatabaseException | [
"Returns",
"a",
"PDO",
"connection"
] | e6f8cb46eab41c3f1b6cabe0da5ccd0926727279 | https://github.com/judus/minimal-database/blob/e6f8cb46eab41c3f1b6cabe0da5ccd0926727279/src/Connectors/PDO.php#L359-L383 | train |
KDF5000/EasyThink | src/ThinkPHP/Library/Vendor/Smarty/sysplugins/smarty_internal_compilebase.php | Smarty_Internal_CompileBase.closeTag | public function closeTag($compiler, $expectedTag)
{
if (count($compiler->_tag_stack) > 0) {
// get stacked info
list($_openTag, $_data) = array_pop($compiler->_tag_stack);
// open tag must match with the expected ones
if (in_array($_openTag, (array) $expectedTag)) {
if (is_null($_data)) {
// return opening tag
return $_openTag;
} else {
// return restored data
return $_data;
}
}
// wrong nesting of tags
$compiler->trigger_template_error("unclosed {" . $_openTag . "} tag");
return;
}
// wrong nesting of tags
$compiler->trigger_template_error("unexpected closing tag", $compiler->lex->taglineno);
return;
} | php | public function closeTag($compiler, $expectedTag)
{
if (count($compiler->_tag_stack) > 0) {
// get stacked info
list($_openTag, $_data) = array_pop($compiler->_tag_stack);
// open tag must match with the expected ones
if (in_array($_openTag, (array) $expectedTag)) {
if (is_null($_data)) {
// return opening tag
return $_openTag;
} else {
// return restored data
return $_data;
}
}
// wrong nesting of tags
$compiler->trigger_template_error("unclosed {" . $_openTag . "} tag");
return;
}
// wrong nesting of tags
$compiler->trigger_template_error("unexpected closing tag", $compiler->lex->taglineno);
return;
} | [
"public",
"function",
"closeTag",
"(",
"$",
"compiler",
",",
"$",
"expectedTag",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"compiler",
"->",
"_tag_stack",
")",
">",
"0",
")",
"{",
"// get stacked info",
"list",
"(",
"$",
"_openTag",
",",
"$",
"_data",
")",
"=",
"array_pop",
"(",
"$",
"compiler",
"->",
"_tag_stack",
")",
";",
"// open tag must match with the expected ones",
"if",
"(",
"in_array",
"(",
"$",
"_openTag",
",",
"(",
"array",
")",
"$",
"expectedTag",
")",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"_data",
")",
")",
"{",
"// return opening tag",
"return",
"$",
"_openTag",
";",
"}",
"else",
"{",
"// return restored data",
"return",
"$",
"_data",
";",
"}",
"}",
"// wrong nesting of tags",
"$",
"compiler",
"->",
"trigger_template_error",
"(",
"\"unclosed {\"",
".",
"$",
"_openTag",
".",
"\"} tag\"",
")",
";",
"return",
";",
"}",
"// wrong nesting of tags",
"$",
"compiler",
"->",
"trigger_template_error",
"(",
"\"unexpected closing tag\"",
",",
"$",
"compiler",
"->",
"lex",
"->",
"taglineno",
")",
";",
"return",
";",
"}"
] | Pop closing tag
Raise an error if this stack-top doesn't match with expected opening tags
@param object $compiler compiler object
@param array|string $expectedTag the expected opening tag names
@return mixed any type the opening tag's name or saved data | [
"Pop",
"closing",
"tag"
] | 86efc9c8a0d504e01e2fea55868227fdc8928841 | https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Vendor/Smarty/sysplugins/smarty_internal_compilebase.php#L150-L172 | train |
infusephp/cron | src/Libs/Lock.php | Lock.acquire | public function acquire($expires)
{
// do not lock if expiry time is 0
if ($expires <= 0) {
return true;
}
$k = $this->getName();
$this->lock = $this->factory->createLock($k, $expires);
return $this->lock->acquire();
} | php | public function acquire($expires)
{
// do not lock if expiry time is 0
if ($expires <= 0) {
return true;
}
$k = $this->getName();
$this->lock = $this->factory->createLock($k, $expires);
return $this->lock->acquire();
} | [
"public",
"function",
"acquire",
"(",
"$",
"expires",
")",
"{",
"// do not lock if expiry time is 0",
"if",
"(",
"$",
"expires",
"<=",
"0",
")",
"{",
"return",
"true",
";",
"}",
"$",
"k",
"=",
"$",
"this",
"->",
"getName",
"(",
")",
";",
"$",
"this",
"->",
"lock",
"=",
"$",
"this",
"->",
"factory",
"->",
"createLock",
"(",
"$",
"k",
",",
"$",
"expires",
")",
";",
"return",
"$",
"this",
"->",
"lock",
"->",
"acquire",
"(",
")",
";",
"}"
] | Attempts to acquire the global lock for this job.
@param int $expires time in seconds after which the lock expires
@return bool | [
"Attempts",
"to",
"acquire",
"the",
"global",
"lock",
"for",
"this",
"job",
"."
] | 783f6078b455a48415efeba0a6ee97ab17a3a903 | https://github.com/infusephp/cron/blob/783f6078b455a48415efeba0a6ee97ab17a3a903/src/Libs/Lock.php#L71-L82 | train |
rzajac/phptools | src/Helper/File.php | File.splitFile | public function splitFile($dstDir, $chunkSize = 2048)
{
$dstDir = rtrim($dstDir, DIRECTORY_SEPARATOR);
$srcFile = fopen($this->filePath, 'r');
$totalSize = filesize($this->filePath);
$chunksNo = ceil($totalSize / $chunkSize);
$lastChunkSize = $totalSize % $chunkSize;
// Chunk must be the same size as requested but the last chunk can be up to $chunkSize * 2
if ($lastChunkSize > 0 && $lastChunkSize < $chunkSize) {
$chunksNo -= 1;
}
$chunkNames = [];
$uniqueChunkName = uniqid();
for ($x = 1; $x <= $chunksNo; ++$x) {
// For the last chunk we send all bytes left
if ($x == $chunksNo) {
$chunkSize = -1;
}
$chunkName = $uniqueChunkName.'_'.$x;
$chunkNames[] = $chunkName;
$dstFilePath = $dstDir.DIRECTORY_SEPARATOR.$chunkName;
$dstFile = fopen($dstFilePath, 'wb');
stream_copy_to_stream($srcFile, $dstFile, $chunkSize);
fclose($dstFile);
}
fclose($srcFile);
return $chunkNames;
} | php | public function splitFile($dstDir, $chunkSize = 2048)
{
$dstDir = rtrim($dstDir, DIRECTORY_SEPARATOR);
$srcFile = fopen($this->filePath, 'r');
$totalSize = filesize($this->filePath);
$chunksNo = ceil($totalSize / $chunkSize);
$lastChunkSize = $totalSize % $chunkSize;
// Chunk must be the same size as requested but the last chunk can be up to $chunkSize * 2
if ($lastChunkSize > 0 && $lastChunkSize < $chunkSize) {
$chunksNo -= 1;
}
$chunkNames = [];
$uniqueChunkName = uniqid();
for ($x = 1; $x <= $chunksNo; ++$x) {
// For the last chunk we send all bytes left
if ($x == $chunksNo) {
$chunkSize = -1;
}
$chunkName = $uniqueChunkName.'_'.$x;
$chunkNames[] = $chunkName;
$dstFilePath = $dstDir.DIRECTORY_SEPARATOR.$chunkName;
$dstFile = fopen($dstFilePath, 'wb');
stream_copy_to_stream($srcFile, $dstFile, $chunkSize);
fclose($dstFile);
}
fclose($srcFile);
return $chunkNames;
} | [
"public",
"function",
"splitFile",
"(",
"$",
"dstDir",
",",
"$",
"chunkSize",
"=",
"2048",
")",
"{",
"$",
"dstDir",
"=",
"rtrim",
"(",
"$",
"dstDir",
",",
"DIRECTORY_SEPARATOR",
")",
";",
"$",
"srcFile",
"=",
"fopen",
"(",
"$",
"this",
"->",
"filePath",
",",
"'r'",
")",
";",
"$",
"totalSize",
"=",
"filesize",
"(",
"$",
"this",
"->",
"filePath",
")",
";",
"$",
"chunksNo",
"=",
"ceil",
"(",
"$",
"totalSize",
"/",
"$",
"chunkSize",
")",
";",
"$",
"lastChunkSize",
"=",
"$",
"totalSize",
"%",
"$",
"chunkSize",
";",
"// Chunk must be the same size as requested but the last chunk can be up to $chunkSize * 2",
"if",
"(",
"$",
"lastChunkSize",
">",
"0",
"&&",
"$",
"lastChunkSize",
"<",
"$",
"chunkSize",
")",
"{",
"$",
"chunksNo",
"-=",
"1",
";",
"}",
"$",
"chunkNames",
"=",
"[",
"]",
";",
"$",
"uniqueChunkName",
"=",
"uniqid",
"(",
")",
";",
"for",
"(",
"$",
"x",
"=",
"1",
";",
"$",
"x",
"<=",
"$",
"chunksNo",
";",
"++",
"$",
"x",
")",
"{",
"// For the last chunk we send all bytes left",
"if",
"(",
"$",
"x",
"==",
"$",
"chunksNo",
")",
"{",
"$",
"chunkSize",
"=",
"-",
"1",
";",
"}",
"$",
"chunkName",
"=",
"$",
"uniqueChunkName",
".",
"'_'",
".",
"$",
"x",
";",
"$",
"chunkNames",
"[",
"]",
"=",
"$",
"chunkName",
";",
"$",
"dstFilePath",
"=",
"$",
"dstDir",
".",
"DIRECTORY_SEPARATOR",
".",
"$",
"chunkName",
";",
"$",
"dstFile",
"=",
"fopen",
"(",
"$",
"dstFilePath",
",",
"'wb'",
")",
";",
"stream_copy_to_stream",
"(",
"$",
"srcFile",
",",
"$",
"dstFile",
",",
"$",
"chunkSize",
")",
";",
"fclose",
"(",
"$",
"dstFile",
")",
";",
"}",
"fclose",
"(",
"$",
"srcFile",
")",
";",
"return",
"$",
"chunkNames",
";",
"}"
] | Split file into chunks and save it to destination.
@param string $dstDir The destination folder path
@param int $chunkSize
@return array The array of chunk names | [
"Split",
"file",
"into",
"chunks",
"and",
"save",
"it",
"to",
"destination",
"."
] | 3cbece7645942d244603c14ba897d8a676ee3088 | https://github.com/rzajac/phptools/blob/3cbece7645942d244603c14ba897d8a676ee3088/src/Helper/File.php#L76-L112 | train |
yuncms/yuncms-core | helpers/UUIDHelper.php | UUIDHelper.v4 | public static function v4()
{
return
// 32 bits for "time_low"
bin2hex(Yii::$app->security->generateRandomKey(4)) . "-" .
// 16 bits for "time_mid"
bin2hex(Yii::$app->security->generateRandomKey(2)) . "-" .
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
dechex(mt_rand(0, 0x0fff) | 0x4000) . "-" .
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
dechex(mt_rand(0, 0x3fff) | 0x8000) . "-" .
// 48 bits for "node"
bin2hex(Yii::$app->security->generateRandomKey(6));
} | php | public static function v4()
{
return
// 32 bits for "time_low"
bin2hex(Yii::$app->security->generateRandomKey(4)) . "-" .
// 16 bits for "time_mid"
bin2hex(Yii::$app->security->generateRandomKey(2)) . "-" .
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
dechex(mt_rand(0, 0x0fff) | 0x4000) . "-" .
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
dechex(mt_rand(0, 0x3fff) | 0x8000) . "-" .
// 48 bits for "node"
bin2hex(Yii::$app->security->generateRandomKey(6));
} | [
"public",
"static",
"function",
"v4",
"(",
")",
"{",
"return",
"// 32 bits for \"time_low\"",
"bin2hex",
"(",
"Yii",
"::",
"$",
"app",
"->",
"security",
"->",
"generateRandomKey",
"(",
"4",
")",
")",
".",
"\"-\"",
".",
"// 16 bits for \"time_mid\"",
"bin2hex",
"(",
"Yii",
"::",
"$",
"app",
"->",
"security",
"->",
"generateRandomKey",
"(",
"2",
")",
")",
".",
"\"-\"",
".",
"// 16 bits for \"time_hi_and_version\",",
"// four most significant bits holds version number 4",
"dechex",
"(",
"mt_rand",
"(",
"0",
",",
"0x0fff",
")",
"|",
"0x4000",
")",
".",
"\"-\"",
".",
"// 16 bits, 8 bits for \"clk_seq_hi_res\",",
"// 8 bits for \"clk_seq_low\",",
"// two most significant bits holds zero and one for variant DCE1.1",
"dechex",
"(",
"mt_rand",
"(",
"0",
",",
"0x3fff",
")",
"|",
"0x8000",
")",
".",
"\"-\"",
".",
"// 48 bits for \"node\"",
"bin2hex",
"(",
"Yii",
"::",
"$",
"app",
"->",
"security",
"->",
"generateRandomKey",
"(",
"6",
")",
")",
";",
"}"
] | Creates an v4 UUID
@return string
@throws \yii\base\Exception | [
"Creates",
"an",
"v4",
"UUID"
] | bfaf61c38e48979036c3ede3a0f2beb637500df5 | https://github.com/yuncms/yuncms-core/blob/bfaf61c38e48979036c3ede3a0f2beb637500df5/helpers/UUIDHelper.php#L26-L42 | train |
stubbles/stubbles-peer | src/main/php/http/HttpUri.php | HttpUri.fromParts | public static function fromParts(
string $scheme,
string $host,
int $port = null,
string $path = '/',
string $queryString = null
): self {
return self::fromString(
$scheme
. '://'
. $host
. (null === $port ? '' : ':' . $port)
. $path
. ((null !== $queryString) ? (substr($queryString, 0, 1) !== '?' ? '?' . $queryString : $queryString) : $queryString)
);
} | php | public static function fromParts(
string $scheme,
string $host,
int $port = null,
string $path = '/',
string $queryString = null
): self {
return self::fromString(
$scheme
. '://'
. $host
. (null === $port ? '' : ':' . $port)
. $path
. ((null !== $queryString) ? (substr($queryString, 0, 1) !== '?' ? '?' . $queryString : $queryString) : $queryString)
);
} | [
"public",
"static",
"function",
"fromParts",
"(",
"string",
"$",
"scheme",
",",
"string",
"$",
"host",
",",
"int",
"$",
"port",
"=",
"null",
",",
"string",
"$",
"path",
"=",
"'/'",
",",
"string",
"$",
"queryString",
"=",
"null",
")",
":",
"self",
"{",
"return",
"self",
"::",
"fromString",
"(",
"$",
"scheme",
".",
"'://'",
".",
"$",
"host",
".",
"(",
"null",
"===",
"$",
"port",
"?",
"''",
":",
"':'",
".",
"$",
"port",
")",
".",
"$",
"path",
".",
"(",
"(",
"null",
"!==",
"$",
"queryString",
")",
"?",
"(",
"substr",
"(",
"$",
"queryString",
",",
"0",
",",
"1",
")",
"!==",
"'?'",
"?",
"'?'",
".",
"$",
"queryString",
":",
"$",
"queryString",
")",
":",
"$",
"queryString",
")",
")",
";",
"}"
] | creates http uri from given uri parts
@param string $scheme scheme of http uri, must be either http or https
@param string $host host name of http uri
@param int $port optional port of http uri
@param string $path optional path of http uri, defaults to /
@param string $queryString optional query string of http uri
@return \stubbles\peer\http\HttpUri
@since 4.0.0 | [
"creates",
"http",
"uri",
"from",
"given",
"uri",
"parts"
] | dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc | https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/http/HttpUri.php#L36-L51 | train |
stubbles/stubbles-peer | src/main/php/http/HttpUri.php | HttpUri.castFrom | public static function castFrom($value, string $name = 'Uri'): self
{
if ($value instanceof self) {
return $value;
}
if (is_string($value)) {
return self::fromString($value);
}
throw new \InvalidArgumentException(
$name . ' must be a string containing a HTTP URI or an instance of '
. get_class() . ', but was '
. (is_object($value) ? get_class($value) : gettype($value))
);
} | php | public static function castFrom($value, string $name = 'Uri'): self
{
if ($value instanceof self) {
return $value;
}
if (is_string($value)) {
return self::fromString($value);
}
throw new \InvalidArgumentException(
$name . ' must be a string containing a HTTP URI or an instance of '
. get_class() . ', but was '
. (is_object($value) ? get_class($value) : gettype($value))
);
} | [
"public",
"static",
"function",
"castFrom",
"(",
"$",
"value",
",",
"string",
"$",
"name",
"=",
"'Uri'",
")",
":",
"self",
"{",
"if",
"(",
"$",
"value",
"instanceof",
"self",
")",
"{",
"return",
"$",
"value",
";",
"}",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"return",
"self",
"::",
"fromString",
"(",
"$",
"value",
")",
";",
"}",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"$",
"name",
".",
"' must be a string containing a HTTP URI or an instance of '",
".",
"get_class",
"(",
")",
".",
"', but was '",
".",
"(",
"is_object",
"(",
"$",
"value",
")",
"?",
"get_class",
"(",
"$",
"value",
")",
":",
"gettype",
"(",
"$",
"value",
")",
")",
")",
";",
"}"
] | casts given value to an instance of HttpUri
@param string|\stubbles\peer\http\HttpUri $value value to cast to HttpUri
@param string $name optional name of parameter to cast from
@return \stubbles\peer\http\HttpUri
@throws \InvalidArgumentException
@since 4.0.0 | [
"casts",
"given",
"value",
"to",
"an",
"instance",
"of",
"HttpUri"
] | dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc | https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/http/HttpUri.php#L88-L103 | train |
stubbles/stubbles-peer | src/main/php/http/HttpUri.php | HttpUri.isValidForRfc | private function isValidForRfc(string $rfc): bool
{
if ($this->parsedUri->hasUser() && Http::RFC_7230 === $rfc) {
throw new MalformedUri(
'The URI ' . $this->parsedUri->asString()
. ' is not a valid HTTP URI according to ' . Http::RFC_7230
. ': contains userinfo, but this is disallowed'
);
}
return $this->isSyntacticallyValid();
} | php | private function isValidForRfc(string $rfc): bool
{
if ($this->parsedUri->hasUser() && Http::RFC_7230 === $rfc) {
throw new MalformedUri(
'The URI ' . $this->parsedUri->asString()
. ' is not a valid HTTP URI according to ' . Http::RFC_7230
. ': contains userinfo, but this is disallowed'
);
}
return $this->isSyntacticallyValid();
} | [
"private",
"function",
"isValidForRfc",
"(",
"string",
"$",
"rfc",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"this",
"->",
"parsedUri",
"->",
"hasUser",
"(",
")",
"&&",
"Http",
"::",
"RFC_7230",
"===",
"$",
"rfc",
")",
"{",
"throw",
"new",
"MalformedUri",
"(",
"'The URI '",
".",
"$",
"this",
"->",
"parsedUri",
"->",
"asString",
"(",
")",
".",
"' is not a valid HTTP URI according to '",
".",
"Http",
"::",
"RFC_7230",
".",
"': contains userinfo, but this is disallowed'",
")",
";",
"}",
"return",
"$",
"this",
"->",
"isSyntacticallyValid",
"(",
")",
";",
"}"
] | checks if uri is valid according to given rfc
@param string $rfc
@return bool
@throws \stubbles\peer\MalformedUri | [
"checks",
"if",
"uri",
"is",
"valid",
"according",
"to",
"given",
"rfc"
] | dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc | https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/http/HttpUri.php#L112-L123 | train |
stubbles/stubbles-peer | src/main/php/http/HttpUri.php | HttpUri.exists | public static function exists($httpUri, callable $checkWith = null): bool
{
if ($httpUri instanceof self) {
return $httpUri->hasDnsRecord($checkWith);
}
if (empty($httpUri) || !is_string($httpUri)) {
return false;
}
try {
return self::fromString($httpUri)->hasDnsRecord($checkWith);
} catch (MalformedUri $murle) {
return false;
}
} | php | public static function exists($httpUri, callable $checkWith = null): bool
{
if ($httpUri instanceof self) {
return $httpUri->hasDnsRecord($checkWith);
}
if (empty($httpUri) || !is_string($httpUri)) {
return false;
}
try {
return self::fromString($httpUri)->hasDnsRecord($checkWith);
} catch (MalformedUri $murle) {
return false;
}
} | [
"public",
"static",
"function",
"exists",
"(",
"$",
"httpUri",
",",
"callable",
"$",
"checkWith",
"=",
"null",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"httpUri",
"instanceof",
"self",
")",
"{",
"return",
"$",
"httpUri",
"->",
"hasDnsRecord",
"(",
"$",
"checkWith",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"httpUri",
")",
"||",
"!",
"is_string",
"(",
"$",
"httpUri",
")",
")",
"{",
"return",
"false",
";",
"}",
"try",
"{",
"return",
"self",
"::",
"fromString",
"(",
"$",
"httpUri",
")",
"->",
"hasDnsRecord",
"(",
"$",
"checkWith",
")",
";",
"}",
"catch",
"(",
"MalformedUri",
"$",
"murle",
")",
"{",
"return",
"false",
";",
"}",
"}"
] | checks whether given http uri exists, i.e. has a DNS entry
@param string $httpUri
@param callable $checkWith optional function to check dns record with
@return bool
@since 7.1.0 | [
"checks",
"whether",
"given",
"http",
"uri",
"exists",
"i",
".",
"e",
".",
"has",
"a",
"DNS",
"entry"
] | dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc | https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/http/HttpUri.php#L133-L148 | train |
stubbles/stubbles-peer | src/main/php/http/HttpUri.php | HttpUri.isValid | public static function isValid($httpUri): bool
{
if ($httpUri instanceof self) {
return true;
}
if (empty($httpUri) || !is_string($httpUri)) {
return false;
}
try {
self::fromString($httpUri);
} catch (MalformedUri $murle) {
return false;
}
return true;
} | php | public static function isValid($httpUri): bool
{
if ($httpUri instanceof self) {
return true;
}
if (empty($httpUri) || !is_string($httpUri)) {
return false;
}
try {
self::fromString($httpUri);
} catch (MalformedUri $murle) {
return false;
}
return true;
} | [
"public",
"static",
"function",
"isValid",
"(",
"$",
"httpUri",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"httpUri",
"instanceof",
"self",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"httpUri",
")",
"||",
"!",
"is_string",
"(",
"$",
"httpUri",
")",
")",
"{",
"return",
"false",
";",
"}",
"try",
"{",
"self",
"::",
"fromString",
"(",
"$",
"httpUri",
")",
";",
"}",
"catch",
"(",
"MalformedUri",
"$",
"murle",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | checks whether given http uri is syntactically valid
@param mixed $httpUri
@return bool
@since 7.1.0 | [
"checks",
"whether",
"given",
"http",
"uri",
"is",
"syntactically",
"valid"
] | dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc | https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/http/HttpUri.php#L157-L174 | train |
stubbles/stubbles-peer | src/main/php/http/HttpUri.php | HttpUri.isSyntacticallyValid | protected function isSyntacticallyValid(): bool
{
if (!parent::isSyntacticallyValid()) {
return false;
}
if (!$this->parsedUri->schemeEquals(Http::SCHEME)
&& !$this->parsedUri->schemeEquals(Http::SCHEME_SSL)) {
return false;
}
return true;
} | php | protected function isSyntacticallyValid(): bool
{
if (!parent::isSyntacticallyValid()) {
return false;
}
if (!$this->parsedUri->schemeEquals(Http::SCHEME)
&& !$this->parsedUri->schemeEquals(Http::SCHEME_SSL)) {
return false;
}
return true;
} | [
"protected",
"function",
"isSyntacticallyValid",
"(",
")",
":",
"bool",
"{",
"if",
"(",
"!",
"parent",
"::",
"isSyntacticallyValid",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"parsedUri",
"->",
"schemeEquals",
"(",
"Http",
"::",
"SCHEME",
")",
"&&",
"!",
"$",
"this",
"->",
"parsedUri",
"->",
"schemeEquals",
"(",
"Http",
"::",
"SCHEME_SSL",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Checks whether URI is a correct URI.
@return bool | [
"Checks",
"whether",
"URI",
"is",
"a",
"correct",
"URI",
"."
] | dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc | https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/http/HttpUri.php#L181-L193 | train |
stubbles/stubbles-peer | src/main/php/http/HttpUri.php | HttpUri.hasDnsRecord | public function hasDnsRecord(callable $checkWith = null): bool
{
$checkdnsrr = null === $checkWith ? 'checkdnsrr': $checkWith;
if ($this->parsedUri->isLocalHost()
|| $checkdnsrr($this->parsedUri->hostname(), 'A')
|| $checkdnsrr($this->parsedUri->hostname(), 'AAAA')
|| $checkdnsrr($this->parsedUri->hostname(), 'CNAME')) {
return true;
}
return false;
} | php | public function hasDnsRecord(callable $checkWith = null): bool
{
$checkdnsrr = null === $checkWith ? 'checkdnsrr': $checkWith;
if ($this->parsedUri->isLocalHost()
|| $checkdnsrr($this->parsedUri->hostname(), 'A')
|| $checkdnsrr($this->parsedUri->hostname(), 'AAAA')
|| $checkdnsrr($this->parsedUri->hostname(), 'CNAME')) {
return true;
}
return false;
} | [
"public",
"function",
"hasDnsRecord",
"(",
"callable",
"$",
"checkWith",
"=",
"null",
")",
":",
"bool",
"{",
"$",
"checkdnsrr",
"=",
"null",
"===",
"$",
"checkWith",
"?",
"'checkdnsrr'",
":",
"$",
"checkWith",
";",
"if",
"(",
"$",
"this",
"->",
"parsedUri",
"->",
"isLocalHost",
"(",
")",
"||",
"$",
"checkdnsrr",
"(",
"$",
"this",
"->",
"parsedUri",
"->",
"hostname",
"(",
")",
",",
"'A'",
")",
"||",
"$",
"checkdnsrr",
"(",
"$",
"this",
"->",
"parsedUri",
"->",
"hostname",
"(",
")",
",",
"'AAAA'",
")",
"||",
"$",
"checkdnsrr",
"(",
"$",
"this",
"->",
"parsedUri",
"->",
"hostname",
"(",
")",
",",
"'CNAME'",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | checks whether host of uri is listed in dns
@param callable $checkWith optional function to check dns record with
@return bool | [
"checks",
"whether",
"host",
"of",
"uri",
"is",
"listed",
"in",
"dns"
] | dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc | https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/http/HttpUri.php#L201-L212 | train |
stubbles/stubbles-peer | src/main/php/http/HttpUri.php | HttpUri.hasDefaultPort | public function hasDefaultPort(): bool
{
if (!$this->parsedUri->hasPort()) {
return true;
}
if ($this->isHttp() && $this->parsedUri->portEquals(Http::PORT)) {
return true;
}
if ($this->isHttps() && $this->parsedUri->portEquals(Http::PORT_SSL)) {
return true;
}
return false;
} | php | public function hasDefaultPort(): bool
{
if (!$this->parsedUri->hasPort()) {
return true;
}
if ($this->isHttp() && $this->parsedUri->portEquals(Http::PORT)) {
return true;
}
if ($this->isHttps() && $this->parsedUri->portEquals(Http::PORT_SSL)) {
return true;
}
return false;
} | [
"public",
"function",
"hasDefaultPort",
"(",
")",
":",
"bool",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"parsedUri",
"->",
"hasPort",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"isHttp",
"(",
")",
"&&",
"$",
"this",
"->",
"parsedUri",
"->",
"portEquals",
"(",
"Http",
"::",
"PORT",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"isHttps",
"(",
")",
"&&",
"$",
"this",
"->",
"parsedUri",
"->",
"portEquals",
"(",
"Http",
"::",
"PORT_SSL",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | checks whether the uri uses a default port or not
Default ports are 80 for http and 443 for https
@return bool | [
"checks",
"whether",
"the",
"uri",
"uses",
"a",
"default",
"port",
"or",
"not"
] | dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc | https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/http/HttpUri.php#L231-L246 | train |
stubbles/stubbles-peer | src/main/php/http/HttpUri.php | HttpUri.toHttp | public function toHttp(int $port = null): self
{
if ($this->isHttp()) {
if (null !== $port && !$this->parsedUri->portEquals($port)) {
return new ConstructedHttpUri($this->parsedUri->transpose(['port' => $port]));
}
return $this;
}
$changes = ['scheme' => Http::SCHEME];
if ($this->parsedUri->hasPort()) {
$changes['port'] = $port;
}
return new ConstructedHttpUri($this->parsedUri->transpose($changes));
} | php | public function toHttp(int $port = null): self
{
if ($this->isHttp()) {
if (null !== $port && !$this->parsedUri->portEquals($port)) {
return new ConstructedHttpUri($this->parsedUri->transpose(['port' => $port]));
}
return $this;
}
$changes = ['scheme' => Http::SCHEME];
if ($this->parsedUri->hasPort()) {
$changes['port'] = $port;
}
return new ConstructedHttpUri($this->parsedUri->transpose($changes));
} | [
"public",
"function",
"toHttp",
"(",
"int",
"$",
"port",
"=",
"null",
")",
":",
"self",
"{",
"if",
"(",
"$",
"this",
"->",
"isHttp",
"(",
")",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"port",
"&&",
"!",
"$",
"this",
"->",
"parsedUri",
"->",
"portEquals",
"(",
"$",
"port",
")",
")",
"{",
"return",
"new",
"ConstructedHttpUri",
"(",
"$",
"this",
"->",
"parsedUri",
"->",
"transpose",
"(",
"[",
"'port'",
"=>",
"$",
"port",
"]",
")",
")",
";",
"}",
"return",
"$",
"this",
";",
"}",
"$",
"changes",
"=",
"[",
"'scheme'",
"=>",
"Http",
"::",
"SCHEME",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"parsedUri",
"->",
"hasPort",
"(",
")",
")",
"{",
"$",
"changes",
"[",
"'port'",
"]",
"=",
"$",
"port",
";",
"}",
"return",
"new",
"ConstructedHttpUri",
"(",
"$",
"this",
"->",
"parsedUri",
"->",
"transpose",
"(",
"$",
"changes",
")",
")",
";",
"}"
] | transposes uri to http
@param int $port optional new port to use, defaults to 80
@return \stubbles\peer\http\HttpUri
@since 2.0.0 | [
"transposes",
"uri",
"to",
"http"
] | dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc | https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/http/HttpUri.php#L307-L323 | train |
stubbles/stubbles-peer | src/main/php/http/HttpUri.php | HttpUri.toHttps | public function toHttps(int $port = null): self
{
if ($this->isHttps()) {
if (null !== $port && !$this->parsedUri->portEquals($port)) {
return new ConstructedHttpUri($this->parsedUri->transpose(['port' => $port]));
}
return $this;
}
$changes = ['scheme' => Http::SCHEME_SSL];
if ($this->parsedUri->hasPort()) {
$changes['port'] = $port;
}
return new ConstructedHttpUri($this->parsedUri->transpose($changes));
} | php | public function toHttps(int $port = null): self
{
if ($this->isHttps()) {
if (null !== $port && !$this->parsedUri->portEquals($port)) {
return new ConstructedHttpUri($this->parsedUri->transpose(['port' => $port]));
}
return $this;
}
$changes = ['scheme' => Http::SCHEME_SSL];
if ($this->parsedUri->hasPort()) {
$changes['port'] = $port;
}
return new ConstructedHttpUri($this->parsedUri->transpose($changes));
} | [
"public",
"function",
"toHttps",
"(",
"int",
"$",
"port",
"=",
"null",
")",
":",
"self",
"{",
"if",
"(",
"$",
"this",
"->",
"isHttps",
"(",
")",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"port",
"&&",
"!",
"$",
"this",
"->",
"parsedUri",
"->",
"portEquals",
"(",
"$",
"port",
")",
")",
"{",
"return",
"new",
"ConstructedHttpUri",
"(",
"$",
"this",
"->",
"parsedUri",
"->",
"transpose",
"(",
"[",
"'port'",
"=>",
"$",
"port",
"]",
")",
")",
";",
"}",
"return",
"$",
"this",
";",
"}",
"$",
"changes",
"=",
"[",
"'scheme'",
"=>",
"Http",
"::",
"SCHEME_SSL",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"parsedUri",
"->",
"hasPort",
"(",
")",
")",
"{",
"$",
"changes",
"[",
"'port'",
"]",
"=",
"$",
"port",
";",
"}",
"return",
"new",
"ConstructedHttpUri",
"(",
"$",
"this",
"->",
"parsedUri",
"->",
"transpose",
"(",
"$",
"changes",
")",
")",
";",
"}"
] | transposes uri to https
@param int $port optional new port to use, defaults to 443
@return \stubbles\peer\http\HttpUri
@since 2.0.0 | [
"transposes",
"uri",
"to",
"https"
] | dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc | https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/http/HttpUri.php#L332-L348 | train |
stubbles/stubbles-peer | src/main/php/http/HttpUri.php | HttpUri.createSocket | public function createSocket(): Socket
{
return new Socket(
$this->hostname(),
$this->port(),
(($this->isHttps()) ? ('ssl://') : (null))
);
} | php | public function createSocket(): Socket
{
return new Socket(
$this->hostname(),
$this->port(),
(($this->isHttps()) ? ('ssl://') : (null))
);
} | [
"public",
"function",
"createSocket",
"(",
")",
":",
"Socket",
"{",
"return",
"new",
"Socket",
"(",
"$",
"this",
"->",
"hostname",
"(",
")",
",",
"$",
"this",
"->",
"port",
"(",
")",
",",
"(",
"(",
"$",
"this",
"->",
"isHttps",
"(",
")",
")",
"?",
"(",
"'ssl://'",
")",
":",
"(",
"null",
")",
")",
")",
";",
"}"
] | creates a socket to this uri
@return \stubbles\peer\Socket
@since 6.0.0 | [
"creates",
"a",
"socket",
"to",
"this",
"uri"
] | dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc | https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/http/HttpUri.php#L375-L382 | train |
stubbles/stubbles-peer | src/main/php/http/HttpUri.php | HttpUri.openSocket | public function openSocket(int $timeout = 5, callable $openWith = null): Stream
{
$socket = $this->createSocket();
if (null !== $openWith) {
$socket->openWith($openWith);
}
return $socket->connect()->setTimeout($timeout);
} | php | public function openSocket(int $timeout = 5, callable $openWith = null): Stream
{
$socket = $this->createSocket();
if (null !== $openWith) {
$socket->openWith($openWith);
}
return $socket->connect()->setTimeout($timeout);
} | [
"public",
"function",
"openSocket",
"(",
"int",
"$",
"timeout",
"=",
"5",
",",
"callable",
"$",
"openWith",
"=",
"null",
")",
":",
"Stream",
"{",
"$",
"socket",
"=",
"$",
"this",
"->",
"createSocket",
"(",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"openWith",
")",
"{",
"$",
"socket",
"->",
"openWith",
"(",
"$",
"openWith",
")",
";",
"}",
"return",
"$",
"socket",
"->",
"connect",
"(",
")",
"->",
"setTimeout",
"(",
"$",
"timeout",
")",
";",
"}"
] | opens socket to this uri
@param int $timeout connection timeout
@param callable $openWith optional open port with this function
@return \stubbles\peer\Stream
@since 2.0.0 | [
"opens",
"socket",
"to",
"this",
"uri"
] | dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc | https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/http/HttpUri.php#L392-L400 | train |
NukaCode/users | src/NukaCode/Users/Http/Controllers/SocialAuthController.php | SocialAuthController.register | private function register($socialUser)
{
$names = explode(' ', $socialUser->getName());
$username = is_null($socialUser->getNickname()) ? $socialUser->getEmail() : $socialUser->getNickname();
$userDetails = [
'username' => $username,
'email' => $socialUser->getEmail(),
'first_name' => isset($names[0]) ? $names[0] : null,
'last_name' => isset($names[1]) ? $names[1] : null,
'display_name' => $username,
];
$user = User::create($userDetails);
$user->assignRole(config('users.default'));
$user->addSocial($socialUser, $this->driver);
event(new UserRegistered($user));
return $user;
} | php | private function register($socialUser)
{
$names = explode(' ', $socialUser->getName());
$username = is_null($socialUser->getNickname()) ? $socialUser->getEmail() : $socialUser->getNickname();
$userDetails = [
'username' => $username,
'email' => $socialUser->getEmail(),
'first_name' => isset($names[0]) ? $names[0] : null,
'last_name' => isset($names[1]) ? $names[1] : null,
'display_name' => $username,
];
$user = User::create($userDetails);
$user->assignRole(config('users.default'));
$user->addSocial($socialUser, $this->driver);
event(new UserRegistered($user));
return $user;
} | [
"private",
"function",
"register",
"(",
"$",
"socialUser",
")",
"{",
"$",
"names",
"=",
"explode",
"(",
"' '",
",",
"$",
"socialUser",
"->",
"getName",
"(",
")",
")",
";",
"$",
"username",
"=",
"is_null",
"(",
"$",
"socialUser",
"->",
"getNickname",
"(",
")",
")",
"?",
"$",
"socialUser",
"->",
"getEmail",
"(",
")",
":",
"$",
"socialUser",
"->",
"getNickname",
"(",
")",
";",
"$",
"userDetails",
"=",
"[",
"'username'",
"=>",
"$",
"username",
",",
"'email'",
"=>",
"$",
"socialUser",
"->",
"getEmail",
"(",
")",
",",
"'first_name'",
"=>",
"isset",
"(",
"$",
"names",
"[",
"0",
"]",
")",
"?",
"$",
"names",
"[",
"0",
"]",
":",
"null",
",",
"'last_name'",
"=>",
"isset",
"(",
"$",
"names",
"[",
"1",
"]",
")",
"?",
"$",
"names",
"[",
"1",
"]",
":",
"null",
",",
"'display_name'",
"=>",
"$",
"username",
",",
"]",
";",
"$",
"user",
"=",
"User",
"::",
"create",
"(",
"$",
"userDetails",
")",
";",
"$",
"user",
"->",
"assignRole",
"(",
"config",
"(",
"'users.default'",
")",
")",
";",
"$",
"user",
"->",
"addSocial",
"(",
"$",
"socialUser",
",",
"$",
"this",
"->",
"driver",
")",
";",
"event",
"(",
"new",
"UserRegistered",
"(",
"$",
"user",
")",
")",
";",
"return",
"$",
"user",
";",
"}"
] | Create a new user from a social user.
@param $socialUser
@return mixed | [
"Create",
"a",
"new",
"user",
"from",
"a",
"social",
"user",
"."
] | d827b8e6ba3faf27c85d867ec1d7e0a426968551 | https://github.com/NukaCode/users/blob/d827b8e6ba3faf27c85d867ec1d7e0a426968551/src/NukaCode/Users/Http/Controllers/SocialAuthController.php#L98-L118 | train |
LartTyler/PHP-DaybreakCommons | src/DaybreakStudios/Common/IO/FileReader.php | FileReader.eof | public function eof() {
if (!$this->hasRead) {
$this->mark();
$ret = fgetc($this->handle);
if ($ret === false)
return true;
$this->reset();
}
return feof($this->handle);
} | php | public function eof() {
if (!$this->hasRead) {
$this->mark();
$ret = fgetc($this->handle);
if ($ret === false)
return true;
$this->reset();
}
return feof($this->handle);
} | [
"public",
"function",
"eof",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasRead",
")",
"{",
"$",
"this",
"->",
"mark",
"(",
")",
";",
"$",
"ret",
"=",
"fgetc",
"(",
"$",
"this",
"->",
"handle",
")",
";",
"if",
"(",
"$",
"ret",
"===",
"false",
")",
"return",
"true",
";",
"$",
"this",
"->",
"reset",
"(",
")",
";",
"}",
"return",
"feof",
"(",
"$",
"this",
"->",
"handle",
")",
";",
"}"
] | Returns true if the end of the stream has been reached.
@return boolean true if the end of the stream has been reached | [
"Returns",
"true",
"if",
"the",
"end",
"of",
"the",
"stream",
"has",
"been",
"reached",
"."
] | db25b5d6cea9b5a1d5afc4c5548a2cbc3018bc0d | https://github.com/LartTyler/PHP-DaybreakCommons/blob/db25b5d6cea9b5a1d5afc4c5548a2cbc3018bc0d/src/DaybreakStudios/Common/IO/FileReader.php#L30-L43 | train |
agentmedia/phine-core | src/Core/Logic/Tree/PageParamListProvider.php | PageParamListProvider.TopMost | public function TopMost()
{
$sql = Access::SqlBuilder();
$tblParams = PageUrlParameter::Schema()->Table();
$where = $sql->Equals($tblParams->Field('PageUrl'), $sql->Value($this->pageUrl->GetID()))
->And_($sql->IsNull($tblParams->Field('Previous')));
return PageUrlParameter::Schema()->First($where);
} | php | public function TopMost()
{
$sql = Access::SqlBuilder();
$tblParams = PageUrlParameter::Schema()->Table();
$where = $sql->Equals($tblParams->Field('PageUrl'), $sql->Value($this->pageUrl->GetID()))
->And_($sql->IsNull($tblParams->Field('Previous')));
return PageUrlParameter::Schema()->First($where);
} | [
"public",
"function",
"TopMost",
"(",
")",
"{",
"$",
"sql",
"=",
"Access",
"::",
"SqlBuilder",
"(",
")",
";",
"$",
"tblParams",
"=",
"PageUrlParameter",
"::",
"Schema",
"(",
")",
"->",
"Table",
"(",
")",
";",
"$",
"where",
"=",
"$",
"sql",
"->",
"Equals",
"(",
"$",
"tblParams",
"->",
"Field",
"(",
"'PageUrl'",
")",
",",
"$",
"sql",
"->",
"Value",
"(",
"$",
"this",
"->",
"pageUrl",
"->",
"GetID",
"(",
")",
")",
")",
"->",
"And_",
"(",
"$",
"sql",
"->",
"IsNull",
"(",
"$",
"tblParams",
"->",
"Field",
"(",
"'Previous'",
")",
")",
")",
";",
"return",
"PageUrlParameter",
"::",
"Schema",
"(",
")",
"->",
"First",
"(",
"$",
"where",
")",
";",
"}"
] | Gets the first page url parameter
@return PageUrlParameter Returns the first parameter or null if none exists | [
"Gets",
"the",
"first",
"page",
"url",
"parameter"
] | 38c1be8d03ebffae950d00a96da3c612aff67832 | https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Logic/Tree/PageParamListProvider.php#L63-L71 | train |
ezra-obiwale/dSCore | src/Stdlib/Table.php | Table.init | public static function init(array $attributes = array()) {
self::$table_attributes = array();
self::$rows = array();
self::$row_data = array();
self::$headers = array();
self::$footers = array();
self::setAttributes($attributes);
} | php | public static function init(array $attributes = array()) {
self::$table_attributes = array();
self::$rows = array();
self::$row_data = array();
self::$headers = array();
self::$footers = array();
self::setAttributes($attributes);
} | [
"public",
"static",
"function",
"init",
"(",
"array",
"$",
"attributes",
"=",
"array",
"(",
")",
")",
"{",
"self",
"::",
"$",
"table_attributes",
"=",
"array",
"(",
")",
";",
"self",
"::",
"$",
"rows",
"=",
"array",
"(",
")",
";",
"self",
"::",
"$",
"row_data",
"=",
"array",
"(",
")",
";",
"self",
"::",
"$",
"headers",
"=",
"array",
"(",
")",
";",
"self",
"::",
"$",
"footers",
"=",
"array",
"(",
")",
";",
"self",
"::",
"setAttributes",
"(",
"$",
"attributes",
")",
";",
"}"
] | Sets up a new table
@param array $attributes [optional] Array of attr => value | [
"Sets",
"up",
"a",
"new",
"table"
] | dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d | https://github.com/ezra-obiwale/dSCore/blob/dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d/src/Stdlib/Table.php#L20-L28 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.