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 |
---|---|---|---|---|---|---|---|---|---|---|---|
matomo-org/device-detector | Parser/Client/Browser.php | Browser.isMobileOnlyBrowser | public static function isMobileOnlyBrowser($browser)
{
return in_array($browser, self::$mobileOnlyBrowsers) || (in_array($browser, self::$availableBrowsers) && in_array(array_search($browser, self::$availableBrowsers), self::$mobileOnlyBrowsers));
} | php | public static function isMobileOnlyBrowser($browser)
{
return in_array($browser, self::$mobileOnlyBrowsers) || (in_array($browser, self::$availableBrowsers) && in_array(array_search($browser, self::$availableBrowsers), self::$mobileOnlyBrowsers));
} | [
"public",
"static",
"function",
"isMobileOnlyBrowser",
"(",
"$",
"browser",
")",
"{",
"return",
"in_array",
"(",
"$",
"browser",
",",
"self",
"::",
"$",
"mobileOnlyBrowsers",
")",
"||",
"(",
"in_array",
"(",
"$",
"browser",
",",
"self",
"::",
"$",
"availableBrowsers",
")",
"&&",
"in_array",
"(",
"array_search",
"(",
"$",
"browser",
",",
"self",
"::",
"$",
"availableBrowsers",
")",
",",
"self",
"::",
"$",
"mobileOnlyBrowsers",
")",
")",
";",
"}"
]
| Returns if the given browser is mobile only
@param string $browser Label or name of browser
@return bool | [
"Returns",
"if",
"the",
"given",
"browser",
"is",
"mobile",
"only"
]
| 61f93df202f3ffa1b5f2ff6d8620944e3f18ae4b | https://github.com/matomo-org/device-detector/blob/61f93df202f3ffa1b5f2ff6d8620944e3f18ae4b/Parser/Client/Browser.php#L269-L272 | train |
matomo-org/device-detector | Parser/Client/ClientParserAbstract.php | ClientParserAbstract.parse | public function parse()
{
$result = null;
if ($this->preMatchOverall()) {
foreach ($this->getRegexes() as $regex) {
$matches = $this->matchUserAgent($regex['regex']);
if ($matches) {
$result = array(
'type' => $this->parserName,
'name' => $this->buildByMatch($regex['name'], $matches),
'version' => $this->buildVersion($regex['version'], $matches)
);
break;
}
}
}
return $result;
} | php | public function parse()
{
$result = null;
if ($this->preMatchOverall()) {
foreach ($this->getRegexes() as $regex) {
$matches = $this->matchUserAgent($regex['regex']);
if ($matches) {
$result = array(
'type' => $this->parserName,
'name' => $this->buildByMatch($regex['name'], $matches),
'version' => $this->buildVersion($regex['version'], $matches)
);
break;
}
}
}
return $result;
} | [
"public",
"function",
"parse",
"(",
")",
"{",
"$",
"result",
"=",
"null",
";",
"if",
"(",
"$",
"this",
"->",
"preMatchOverall",
"(",
")",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getRegexes",
"(",
")",
"as",
"$",
"regex",
")",
"{",
"$",
"matches",
"=",
"$",
"this",
"->",
"matchUserAgent",
"(",
"$",
"regex",
"[",
"'regex'",
"]",
")",
";",
"if",
"(",
"$",
"matches",
")",
"{",
"$",
"result",
"=",
"array",
"(",
"'type'",
"=>",
"$",
"this",
"->",
"parserName",
",",
"'name'",
"=>",
"$",
"this",
"->",
"buildByMatch",
"(",
"$",
"regex",
"[",
"'name'",
"]",
",",
"$",
"matches",
")",
",",
"'version'",
"=>",
"$",
"this",
"->",
"buildVersion",
"(",
"$",
"regex",
"[",
"'version'",
"]",
",",
"$",
"matches",
")",
")",
";",
"break",
";",
"}",
"}",
"}",
"return",
"$",
"result",
";",
"}"
]
| Parses the current UA and checks whether it contains any client information
@see $fixtureFile for file with list of detected clients
Step 1: Build a big regex containing all regexes and match UA against it
-> If no matches found: return
-> Otherwise:
Step 2: Walk through the list of regexes in feed_readers.yml and try to match every one
-> Return the matched feed reader
NOTE: Doing the big match before matching every single regex speeds up the detection | [
"Parses",
"the",
"current",
"UA",
"and",
"checks",
"whether",
"it",
"contains",
"any",
"client",
"information"
]
| 61f93df202f3ffa1b5f2ff6d8620944e3f18ae4b | https://github.com/matomo-org/device-detector/blob/61f93df202f3ffa1b5f2ff6d8620944e3f18ae4b/Parser/Client/ClientParserAbstract.php#L30-L50 | train |
matomo-org/device-detector | Parser/Client/ClientParserAbstract.php | ClientParserAbstract.getAvailableClients | public static function getAvailableClients()
{
$instance = new static();
$regexes = $instance->getRegexes();
$names = array();
foreach ($regexes as $regex) {
if ($regex['name'] != '$1') {
$names[] = $regex['name'];
}
}
natcasesort($names);
return array_unique($names);
} | php | public static function getAvailableClients()
{
$instance = new static();
$regexes = $instance->getRegexes();
$names = array();
foreach ($regexes as $regex) {
if ($regex['name'] != '$1') {
$names[] = $regex['name'];
}
}
natcasesort($names);
return array_unique($names);
} | [
"public",
"static",
"function",
"getAvailableClients",
"(",
")",
"{",
"$",
"instance",
"=",
"new",
"static",
"(",
")",
";",
"$",
"regexes",
"=",
"$",
"instance",
"->",
"getRegexes",
"(",
")",
";",
"$",
"names",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"regexes",
"as",
"$",
"regex",
")",
"{",
"if",
"(",
"$",
"regex",
"[",
"'name'",
"]",
"!=",
"'$1'",
")",
"{",
"$",
"names",
"[",
"]",
"=",
"$",
"regex",
"[",
"'name'",
"]",
";",
"}",
"}",
"natcasesort",
"(",
"$",
"names",
")",
";",
"return",
"array_unique",
"(",
"$",
"names",
")",
";",
"}"
]
| Returns all names defined in the regexes
Attention: This method might not return all names of detected clients
@return array | [
"Returns",
"all",
"names",
"defined",
"in",
"the",
"regexes"
]
| 61f93df202f3ffa1b5f2ff6d8620944e3f18ae4b | https://github.com/matomo-org/device-detector/blob/61f93df202f3ffa1b5f2ff6d8620944e3f18ae4b/Parser/Client/ClientParserAbstract.php#L59-L73 | train |
matomo-org/device-detector | Parser/Bot.php | Bot.parse | public function parse()
{
$result = null;
if ($this->preMatchOverall()) {
if ($this->discardDetails) {
$result = true;
} else {
foreach ($this->getRegexes() as $regex) {
$matches = $this->matchUserAgent($regex['regex']);
if ($matches) {
unset($regex['regex']);
$result = $regex;
break;
}
}
}
}
return $result;
} | php | public function parse()
{
$result = null;
if ($this->preMatchOverall()) {
if ($this->discardDetails) {
$result = true;
} else {
foreach ($this->getRegexes() as $regex) {
$matches = $this->matchUserAgent($regex['regex']);
if ($matches) {
unset($regex['regex']);
$result = $regex;
break;
}
}
}
}
return $result;
} | [
"public",
"function",
"parse",
"(",
")",
"{",
"$",
"result",
"=",
"null",
";",
"if",
"(",
"$",
"this",
"->",
"preMatchOverall",
"(",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"discardDetails",
")",
"{",
"$",
"result",
"=",
"true",
";",
"}",
"else",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getRegexes",
"(",
")",
"as",
"$",
"regex",
")",
"{",
"$",
"matches",
"=",
"$",
"this",
"->",
"matchUserAgent",
"(",
"$",
"regex",
"[",
"'regex'",
"]",
")",
";",
"if",
"(",
"$",
"matches",
")",
"{",
"unset",
"(",
"$",
"regex",
"[",
"'regex'",
"]",
")",
";",
"$",
"result",
"=",
"$",
"regex",
";",
"break",
";",
"}",
"}",
"}",
"}",
"return",
"$",
"result",
";",
"}"
]
| Parses the current UA and checks whether it contains bot information
@see bots.yml for list of detected bots
Step 1: Build a big regex containing all regexes and match UA against it
-> If no matches found: return
-> Otherwise:
Step 2: Walk through the list of regexes in bots.yml and try to match every one
-> Return the matched data
If $discardDetails is set to TRUE, the Step 2 will be skipped
$bot will be set to TRUE instead
NOTE: Doing the big match before matching every single regex speeds up the detection | [
"Parses",
"the",
"current",
"UA",
"and",
"checks",
"whether",
"it",
"contains",
"bot",
"information"
]
| 61f93df202f3ffa1b5f2ff6d8620944e3f18ae4b | https://github.com/matomo-org/device-detector/blob/61f93df202f3ffa1b5f2ff6d8620944e3f18ae4b/Parser/Bot.php#L49-L69 | train |
matomo-org/device-detector | Parser/OperatingSystem.php | OperatingSystem.getOsFamily | public static function getOsFamily($osLabel)
{
foreach (self::$osFamilies as $family => $labels) {
if (in_array($osLabel, $labels)) {
return $family;
}
}
return false;
} | php | public static function getOsFamily($osLabel)
{
foreach (self::$osFamilies as $family => $labels) {
if (in_array($osLabel, $labels)) {
return $family;
}
}
return false;
} | [
"public",
"static",
"function",
"getOsFamily",
"(",
"$",
"osLabel",
")",
"{",
"foreach",
"(",
"self",
"::",
"$",
"osFamilies",
"as",
"$",
"family",
"=>",
"$",
"labels",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"osLabel",
",",
"$",
"labels",
")",
")",
"{",
"return",
"$",
"family",
";",
"}",
"}",
"return",
"false",
";",
"}"
]
| Returns the operating system family for the given operating system
@param $osLabel
@return bool|string If false, "Unknown" | [
"Returns",
"the",
"operating",
"system",
"family",
"for",
"the",
"given",
"operating",
"system"
]
| 61f93df202f3ffa1b5f2ff6d8620944e3f18ae4b | https://github.com/matomo-org/device-detector/blob/61f93df202f3ffa1b5f2ff6d8620944e3f18ae4b/Parser/OperatingSystem.php#L223-L231 | train |
matomo-org/device-detector | Parser/OperatingSystem.php | OperatingSystem.getNameFromId | public static function getNameFromId($os, $ver = false)
{
if (array_key_exists($os, self::$operatingSystems)) {
$osFullName = self::$operatingSystems[$os];
return trim($osFullName . " " . $ver);
}
return false;
} | php | public static function getNameFromId($os, $ver = false)
{
if (array_key_exists($os, self::$operatingSystems)) {
$osFullName = self::$operatingSystems[$os];
return trim($osFullName . " " . $ver);
}
return false;
} | [
"public",
"static",
"function",
"getNameFromId",
"(",
"$",
"os",
",",
"$",
"ver",
"=",
"false",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"os",
",",
"self",
"::",
"$",
"operatingSystems",
")",
")",
"{",
"$",
"osFullName",
"=",
"self",
"::",
"$",
"operatingSystems",
"[",
"$",
"os",
"]",
";",
"return",
"trim",
"(",
"$",
"osFullName",
".",
"\" \"",
".",
"$",
"ver",
")",
";",
"}",
"return",
"false",
";",
"}"
]
| Returns the full name for the given short name
@param $os
@param bool $ver
@return bool|string | [
"Returns",
"the",
"full",
"name",
"for",
"the",
"given",
"short",
"name"
]
| 61f93df202f3ffa1b5f2ff6d8620944e3f18ae4b | https://github.com/matomo-org/device-detector/blob/61f93df202f3ffa1b5f2ff6d8620944e3f18ae4b/Parser/OperatingSystem.php#L241-L248 | train |
matomo-org/device-detector | Parser/ParserAbstract.php | ParserAbstract.setVersionTruncation | public static function setVersionTruncation($type)
{
if (in_array($type, array(self::VERSION_TRUNCATION_BUILD,
self::VERSION_TRUNCATION_NONE,
self::VERSION_TRUNCATION_MAJOR,
self::VERSION_TRUNCATION_MINOR,
self::VERSION_TRUNCATION_PATCH))) {
self::$maxMinorParts = $type;
}
} | php | public static function setVersionTruncation($type)
{
if (in_array($type, array(self::VERSION_TRUNCATION_BUILD,
self::VERSION_TRUNCATION_NONE,
self::VERSION_TRUNCATION_MAJOR,
self::VERSION_TRUNCATION_MINOR,
self::VERSION_TRUNCATION_PATCH))) {
self::$maxMinorParts = $type;
}
} | [
"public",
"static",
"function",
"setVersionTruncation",
"(",
"$",
"type",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"type",
",",
"array",
"(",
"self",
"::",
"VERSION_TRUNCATION_BUILD",
",",
"self",
"::",
"VERSION_TRUNCATION_NONE",
",",
"self",
"::",
"VERSION_TRUNCATION_MAJOR",
",",
"self",
"::",
"VERSION_TRUNCATION_MINOR",
",",
"self",
"::",
"VERSION_TRUNCATION_PATCH",
")",
")",
")",
"{",
"self",
"::",
"$",
"maxMinorParts",
"=",
"$",
"type",
";",
"}",
"}"
]
| Set how DeviceDetector should return versions
@param int|null $type Any of the VERSION_TRUNCATION_* constants | [
"Set",
"how",
"DeviceDetector",
"should",
"return",
"versions"
]
| 61f93df202f3ffa1b5f2ff6d8620944e3f18ae4b | https://github.com/matomo-org/device-detector/blob/61f93df202f3ffa1b5f2ff6d8620944e3f18ae4b/Parser/ParserAbstract.php#L111-L120 | train |
matomo-org/device-detector | Parser/ParserAbstract.php | ParserAbstract.matchUserAgent | protected function matchUserAgent($regex)
{
// only match if useragent begins with given regex or there is no letter before it
$regex = '/(?:^|[^A-Z0-9\-_]|[^A-Z0-9\-]_|sprd-)(?:' . str_replace('/', '\/', $regex) . ')/i';
if (preg_match($regex, $this->userAgent, $matches)) {
return $matches;
}
return false;
} | php | protected function matchUserAgent($regex)
{
// only match if useragent begins with given regex or there is no letter before it
$regex = '/(?:^|[^A-Z0-9\-_]|[^A-Z0-9\-]_|sprd-)(?:' . str_replace('/', '\/', $regex) . ')/i';
if (preg_match($regex, $this->userAgent, $matches)) {
return $matches;
}
return false;
} | [
"protected",
"function",
"matchUserAgent",
"(",
"$",
"regex",
")",
"{",
"// only match if useragent begins with given regex or there is no letter before it",
"$",
"regex",
"=",
"'/(?:^|[^A-Z0-9\\-_]|[^A-Z0-9\\-]_|sprd-)(?:'",
".",
"str_replace",
"(",
"'/'",
",",
"'\\/'",
",",
"$",
"regex",
")",
".",
"')/i'",
";",
"if",
"(",
"preg_match",
"(",
"$",
"regex",
",",
"$",
"this",
"->",
"userAgent",
",",
"$",
"matches",
")",
")",
"{",
"return",
"$",
"matches",
";",
"}",
"return",
"false",
";",
"}"
]
| Matches the useragent against the given regex
@param $regex
@return array|bool | [
"Matches",
"the",
"useragent",
"against",
"the",
"given",
"regex"
]
| 61f93df202f3ffa1b5f2ff6d8620944e3f18ae4b | https://github.com/matomo-org/device-detector/blob/61f93df202f3ffa1b5f2ff6d8620944e3f18ae4b/Parser/ParserAbstract.php#L177-L187 | train |
matomo-org/device-detector | Parser/ParserAbstract.php | ParserAbstract.preMatchOverall | protected function preMatchOverall()
{
$regexes = $this->getRegexes();
static $overAllMatch;
$cacheKey = $this->parserName.DeviceDetector::VERSION.'-all';
$cacheKey = preg_replace('/([^a-z0-9_-]+)/i', '', $cacheKey);
if (empty($overAllMatch)) {
$overAllMatch = $this->getCache()->fetch($cacheKey);
}
if (empty($overAllMatch)) {
// reverse all regexes, so we have the generic one first, which already matches most patterns
$overAllMatch = array_reduce(array_reverse($regexes), function ($val1, $val2) {
if (!empty($val1)) {
return $val1.'|'.$val2['regex'];
} else {
return $val2['regex'];
}
});
$this->getCache()->save($cacheKey, $overAllMatch);
}
return $this->matchUserAgent($overAllMatch);
} | php | protected function preMatchOverall()
{
$regexes = $this->getRegexes();
static $overAllMatch;
$cacheKey = $this->parserName.DeviceDetector::VERSION.'-all';
$cacheKey = preg_replace('/([^a-z0-9_-]+)/i', '', $cacheKey);
if (empty($overAllMatch)) {
$overAllMatch = $this->getCache()->fetch($cacheKey);
}
if (empty($overAllMatch)) {
// reverse all regexes, so we have the generic one first, which already matches most patterns
$overAllMatch = array_reduce(array_reverse($regexes), function ($val1, $val2) {
if (!empty($val1)) {
return $val1.'|'.$val2['regex'];
} else {
return $val2['regex'];
}
});
$this->getCache()->save($cacheKey, $overAllMatch);
}
return $this->matchUserAgent($overAllMatch);
} | [
"protected",
"function",
"preMatchOverall",
"(",
")",
"{",
"$",
"regexes",
"=",
"$",
"this",
"->",
"getRegexes",
"(",
")",
";",
"static",
"$",
"overAllMatch",
";",
"$",
"cacheKey",
"=",
"$",
"this",
"->",
"parserName",
".",
"DeviceDetector",
"::",
"VERSION",
".",
"'-all'",
";",
"$",
"cacheKey",
"=",
"preg_replace",
"(",
"'/([^a-z0-9_-]+)/i'",
",",
"''",
",",
"$",
"cacheKey",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"overAllMatch",
")",
")",
"{",
"$",
"overAllMatch",
"=",
"$",
"this",
"->",
"getCache",
"(",
")",
"->",
"fetch",
"(",
"$",
"cacheKey",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"overAllMatch",
")",
")",
"{",
"// reverse all regexes, so we have the generic one first, which already matches most patterns",
"$",
"overAllMatch",
"=",
"array_reduce",
"(",
"array_reverse",
"(",
"$",
"regexes",
")",
",",
"function",
"(",
"$",
"val1",
",",
"$",
"val2",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"val1",
")",
")",
"{",
"return",
"$",
"val1",
".",
"'|'",
".",
"$",
"val2",
"[",
"'regex'",
"]",
";",
"}",
"else",
"{",
"return",
"$",
"val2",
"[",
"'regex'",
"]",
";",
"}",
"}",
")",
";",
"$",
"this",
"->",
"getCache",
"(",
")",
"->",
"save",
"(",
"$",
"cacheKey",
",",
"$",
"overAllMatch",
")",
";",
"}",
"return",
"$",
"this",
"->",
"matchUserAgent",
"(",
"$",
"overAllMatch",
")",
";",
"}"
]
| Tests the useragent against a combination of all regexes
All regexes returned by getRegexes() will be reversed and concated with '|'
Afterwards the big regex will be tested against the user agent
Method can be used to speed up detections by making a big check before doing checks for every single regex
@return bool | [
"Tests",
"the",
"useragent",
"against",
"a",
"combination",
"of",
"all",
"regexes"
]
| 61f93df202f3ffa1b5f2ff6d8620944e3f18ae4b | https://github.com/matomo-org/device-detector/blob/61f93df202f3ffa1b5f2ff6d8620944e3f18ae4b/Parser/ParserAbstract.php#L241-L267 | train |
spatie/laravel-query-builder | src/QueryBuilder.php | QueryBuilder.for | public static function for($baseQuery, ?Request $request = null): self
{
if (is_string($baseQuery)) {
$baseQuery = ($baseQuery)::query();
}
return new static($baseQuery, $request ?? request());
} | php | public static function for($baseQuery, ?Request $request = null): self
{
if (is_string($baseQuery)) {
$baseQuery = ($baseQuery)::query();
}
return new static($baseQuery, $request ?? request());
} | [
"public",
"static",
"function",
"for",
"(",
"$",
"baseQuery",
",",
"?",
"Request",
"$",
"request",
"=",
"null",
")",
":",
"self",
"{",
"if",
"(",
"is_string",
"(",
"$",
"baseQuery",
")",
")",
"{",
"$",
"baseQuery",
"=",
"(",
"$",
"baseQuery",
")",
"::",
"query",
"(",
")",
";",
"}",
"return",
"new",
"static",
"(",
"$",
"baseQuery",
",",
"$",
"request",
"??",
"request",
"(",
")",
")",
";",
"}"
]
| Create a new QueryBuilder for a request and model.
@param string|\Illuminate\Database\Query\Builder $baseQuery Model class or base query builder
@param \Illuminate\Http\Request $request
@return \Spatie\QueryBuilder\QueryBuilder | [
"Create",
"a",
"new",
"QueryBuilder",
"for",
"a",
"request",
"and",
"model",
"."
]
| 68bc39e816fbdf75d6691960ae3c30479e1f5de5 | https://github.com/spatie/laravel-query-builder/blob/68bc39e816fbdf75d6691960ae3c30479e1f5de5/src/QueryBuilder.php#L42-L49 | train |
php-pm/php-pm | src/Bridges/BootstrapTrait.php | BootstrapTrait.bootstrapApplicationEnvironment | private function bootstrapApplicationEnvironment($appBootstrap, $appenv, $debug)
{
$appBootstrap = $this->normalizeBootstrapClass($appBootstrap);
$this->middleware = new $appBootstrap;
if ($this->middleware instanceof ApplicationEnvironmentAwareInterface) {
$this->middleware->initialize($appenv, $debug);
}
} | php | private function bootstrapApplicationEnvironment($appBootstrap, $appenv, $debug)
{
$appBootstrap = $this->normalizeBootstrapClass($appBootstrap);
$this->middleware = new $appBootstrap;
if ($this->middleware instanceof ApplicationEnvironmentAwareInterface) {
$this->middleware->initialize($appenv, $debug);
}
} | [
"private",
"function",
"bootstrapApplicationEnvironment",
"(",
"$",
"appBootstrap",
",",
"$",
"appenv",
",",
"$",
"debug",
")",
"{",
"$",
"appBootstrap",
"=",
"$",
"this",
"->",
"normalizeBootstrapClass",
"(",
"$",
"appBootstrap",
")",
";",
"$",
"this",
"->",
"middleware",
"=",
"new",
"$",
"appBootstrap",
";",
"if",
"(",
"$",
"this",
"->",
"middleware",
"instanceof",
"ApplicationEnvironmentAwareInterface",
")",
"{",
"$",
"this",
"->",
"middleware",
"->",
"initialize",
"(",
"$",
"appenv",
",",
"$",
"debug",
")",
";",
"}",
"}"
]
| Bootstrap application environment
@param string|null $appBootstrap The environment your application will use to bootstrap (if any)
@param string $appenv
@param boolean $debug If debug is enabled | [
"Bootstrap",
"application",
"environment"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/Bridges/BootstrapTrait.php#L18-L26 | train |
php-pm/php-pm | src/SlavePool.php | SlavePool.add | public function add(Slave $slave)
{
$port = $slave->getPort();
if (isset($this->slaves[$port])) {
throw new \Exception("Slave port $port already occupied.");
}
if ($slave->getPort() !== $port) {
throw new \Exception("Slave mis-assigned.");
}
$this->slaves[$port] = $slave;
} | php | public function add(Slave $slave)
{
$port = $slave->getPort();
if (isset($this->slaves[$port])) {
throw new \Exception("Slave port $port already occupied.");
}
if ($slave->getPort() !== $port) {
throw new \Exception("Slave mis-assigned.");
}
$this->slaves[$port] = $slave;
} | [
"public",
"function",
"add",
"(",
"Slave",
"$",
"slave",
")",
"{",
"$",
"port",
"=",
"$",
"slave",
"->",
"getPort",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"slaves",
"[",
"$",
"port",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"\"Slave port $port already occupied.\"",
")",
";",
"}",
"if",
"(",
"$",
"slave",
"->",
"getPort",
"(",
")",
"!==",
"$",
"port",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"\"Slave mis-assigned.\"",
")",
";",
"}",
"$",
"this",
"->",
"slaves",
"[",
"$",
"port",
"]",
"=",
"$",
"slave",
";",
"}"
]
| Add slave to pool
Slave is in CREATED state
@param Slave $slave
@return void | [
"Add",
"slave",
"to",
"pool"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/SlavePool.php#L24-L37 | train |
php-pm/php-pm | src/SlavePool.php | SlavePool.remove | public function remove(Slave $slave)
{
$port = $slave->getPort();
// validate existence
$this->getByPort($port);
// remove
unset($this->slaves[$port]);
} | php | public function remove(Slave $slave)
{
$port = $slave->getPort();
// validate existence
$this->getByPort($port);
// remove
unset($this->slaves[$port]);
} | [
"public",
"function",
"remove",
"(",
"Slave",
"$",
"slave",
")",
"{",
"$",
"port",
"=",
"$",
"slave",
"->",
"getPort",
"(",
")",
";",
"// validate existence",
"$",
"this",
"->",
"getByPort",
"(",
"$",
"port",
")",
";",
"// remove",
"unset",
"(",
"$",
"this",
"->",
"slaves",
"[",
"$",
"port",
"]",
")",
";",
"}"
]
| Remove from pool
@param Slave $slave
@return void | [
"Remove",
"from",
"pool"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/SlavePool.php#L46-L55 | train |
php-pm/php-pm | src/SlavePool.php | SlavePool.getByPort | public function getByPort($port)
{
if (!isset($this->slaves[$port])) {
throw new \Exception("Slave port $port empty.");
}
return $this->slaves[$port];
} | php | public function getByPort($port)
{
if (!isset($this->slaves[$port])) {
throw new \Exception("Slave port $port empty.");
}
return $this->slaves[$port];
} | [
"public",
"function",
"getByPort",
"(",
"$",
"port",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"slaves",
"[",
"$",
"port",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"\"Slave port $port empty.\"",
")",
";",
"}",
"return",
"$",
"this",
"->",
"slaves",
"[",
"$",
"port",
"]",
";",
"}"
]
| Get slave by port
@param int $port
@return Slave | [
"Get",
"slave",
"by",
"port"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/SlavePool.php#L63-L70 | train |
php-pm/php-pm | src/SlavePool.php | SlavePool.getByConnection | public function getByConnection(ConnectionInterface $connection)
{
$hash = spl_object_hash($connection);
foreach ($this->slaves as $slave) {
if ($slave->getConnection() && $hash === spl_object_hash($slave->getConnection())) {
return $slave;
}
}
throw new \Exception("Slave connection not registered.");
} | php | public function getByConnection(ConnectionInterface $connection)
{
$hash = spl_object_hash($connection);
foreach ($this->slaves as $slave) {
if ($slave->getConnection() && $hash === spl_object_hash($slave->getConnection())) {
return $slave;
}
}
throw new \Exception("Slave connection not registered.");
} | [
"public",
"function",
"getByConnection",
"(",
"ConnectionInterface",
"$",
"connection",
")",
"{",
"$",
"hash",
"=",
"spl_object_hash",
"(",
"$",
"connection",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"slaves",
"as",
"$",
"slave",
")",
"{",
"if",
"(",
"$",
"slave",
"->",
"getConnection",
"(",
")",
"&&",
"$",
"hash",
"===",
"spl_object_hash",
"(",
"$",
"slave",
"->",
"getConnection",
"(",
")",
")",
")",
"{",
"return",
"$",
"slave",
";",
"}",
"}",
"throw",
"new",
"\\",
"Exception",
"(",
"\"Slave connection not registered.\"",
")",
";",
"}"
]
| Get slave slaves by connection
@param ConnectionInterface $connection
@return mixed
@throws \Exception | [
"Get",
"slave",
"slaves",
"by",
"connection"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/SlavePool.php#L80-L91 | train |
php-pm/php-pm | src/SlavePool.php | SlavePool.getByStatus | public function getByStatus($status)
{
return array_filter($this->slaves, function ($slave) use ($status) {
return $status === Slave::ANY || $status === $slave->getStatus();
});
} | php | public function getByStatus($status)
{
return array_filter($this->slaves, function ($slave) use ($status) {
return $status === Slave::ANY || $status === $slave->getStatus();
});
} | [
"public",
"function",
"getByStatus",
"(",
"$",
"status",
")",
"{",
"return",
"array_filter",
"(",
"$",
"this",
"->",
"slaves",
",",
"function",
"(",
"$",
"slave",
")",
"use",
"(",
"$",
"status",
")",
"{",
"return",
"$",
"status",
"===",
"Slave",
"::",
"ANY",
"||",
"$",
"status",
"===",
"$",
"slave",
"->",
"getStatus",
"(",
")",
";",
"}",
")",
";",
"}"
]
| Get multiple slaves by status | [
"Get",
"multiple",
"slaves",
"by",
"status"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/SlavePool.php#L96-L101 | train |
php-pm/php-pm | src/SlavePool.php | SlavePool.getStatusSummary | public function getStatusSummary()
{
$map = [
'total' => Slave::ANY,
'ready' => Slave::READY,
'busy' => Slave::BUSY,
'created' => Slave::CREATED,
'registered' => Slave::REGISTERED,
'closed' => Slave::CLOSED
];
return array_map(function ($state) {
return count($this->getByStatus($state));
}, $map);
} | php | public function getStatusSummary()
{
$map = [
'total' => Slave::ANY,
'ready' => Slave::READY,
'busy' => Slave::BUSY,
'created' => Slave::CREATED,
'registered' => Slave::REGISTERED,
'closed' => Slave::CLOSED
];
return array_map(function ($state) {
return count($this->getByStatus($state));
}, $map);
} | [
"public",
"function",
"getStatusSummary",
"(",
")",
"{",
"$",
"map",
"=",
"[",
"'total'",
"=>",
"Slave",
"::",
"ANY",
",",
"'ready'",
"=>",
"Slave",
"::",
"READY",
",",
"'busy'",
"=>",
"Slave",
"::",
"BUSY",
",",
"'created'",
"=>",
"Slave",
"::",
"CREATED",
",",
"'registered'",
"=>",
"Slave",
"::",
"REGISTERED",
",",
"'closed'",
"=>",
"Slave",
"::",
"CLOSED",
"]",
";",
"return",
"array_map",
"(",
"function",
"(",
"$",
"state",
")",
"{",
"return",
"count",
"(",
"$",
"this",
"->",
"getByStatus",
"(",
"$",
"state",
")",
")",
";",
"}",
",",
"$",
"map",
")",
";",
"}"
]
| Return a human-readable summary of the slaves in the pool.
@return array | [
"Return",
"a",
"human",
"-",
"readable",
"summary",
"of",
"the",
"slaves",
"in",
"the",
"pool",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/SlavePool.php#L108-L122 | train |
php-pm/php-pm | src/Slave.php | Slave.register | public function register($pid, ConnectionInterface $connection)
{
if ($this->status !== self::CREATED) {
throw new \LogicException('Cannot register a slave that is not in created state');
}
$this->pid = $pid;
$this->connection = $connection;
$this->status = self::REGISTERED;
} | php | public function register($pid, ConnectionInterface $connection)
{
if ($this->status !== self::CREATED) {
throw new \LogicException('Cannot register a slave that is not in created state');
}
$this->pid = $pid;
$this->connection = $connection;
$this->status = self::REGISTERED;
} | [
"public",
"function",
"register",
"(",
"$",
"pid",
",",
"ConnectionInterface",
"$",
"connection",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"status",
"!==",
"self",
"::",
"CREATED",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'Cannot register a slave that is not in created state'",
")",
";",
"}",
"$",
"this",
"->",
"pid",
"=",
"$",
"pid",
";",
"$",
"this",
"->",
"connection",
"=",
"$",
"connection",
";",
"$",
"this",
"->",
"status",
"=",
"self",
"::",
"REGISTERED",
";",
"}"
]
| Register a slave after it's process started
@param int $pid
@param ConnectionInterface $connection
@return void | [
"Register",
"a",
"slave",
"after",
"it",
"s",
"process",
"started"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/Slave.php#L122-L132 | train |
php-pm/php-pm | src/Slave.php | Slave.ready | public function ready()
{
if ($this->status !== self::REGISTERED) {
throw new \LogicException('Cannot ready a slave that is not in registered state');
}
$this->status = self::READY;
} | php | public function ready()
{
if ($this->status !== self::REGISTERED) {
throw new \LogicException('Cannot ready a slave that is not in registered state');
}
$this->status = self::READY;
} | [
"public",
"function",
"ready",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"status",
"!==",
"self",
"::",
"REGISTERED",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'Cannot ready a slave that is not in registered state'",
")",
";",
"}",
"$",
"this",
"->",
"status",
"=",
"self",
"::",
"READY",
";",
"}"
]
| Ready a slave after bootstrap completed
@return void | [
"Ready",
"a",
"slave",
"after",
"bootstrap",
"completed"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/Slave.php#L139-L146 | train |
php-pm/php-pm | src/Slave.php | Slave.occupy | public function occupy()
{
if ($this->status !== self::READY) {
throw new \LogicException('Cannot occupy a slave that is not in ready state');
}
$this->status = self::BUSY;
} | php | public function occupy()
{
if ($this->status !== self::READY) {
throw new \LogicException('Cannot occupy a slave that is not in ready state');
}
$this->status = self::BUSY;
} | [
"public",
"function",
"occupy",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"status",
"!==",
"self",
"::",
"READY",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'Cannot occupy a slave that is not in ready state'",
")",
";",
"}",
"$",
"this",
"->",
"status",
"=",
"self",
"::",
"BUSY",
";",
"}"
]
| Occupies a slave for request handling
@return void | [
"Occupies",
"a",
"slave",
"for",
"request",
"handling"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/Slave.php#L153-L160 | train |
php-pm/php-pm | src/Slave.php | Slave.release | public function release()
{
if ($this->status !== self::BUSY) {
throw new \LogicException('Cannot release a slave that is not in busy state');
}
$this->status = self::READY;
$this->handledRequests++;
} | php | public function release()
{
if ($this->status !== self::BUSY) {
throw new \LogicException('Cannot release a slave that is not in busy state');
}
$this->status = self::READY;
$this->handledRequests++;
} | [
"public",
"function",
"release",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"status",
"!==",
"self",
"::",
"BUSY",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'Cannot release a slave that is not in busy state'",
")",
";",
"}",
"$",
"this",
"->",
"status",
"=",
"self",
"::",
"READY",
";",
"$",
"this",
"->",
"handledRequests",
"++",
";",
"}"
]
| Releases a slave from request handling
@return void | [
"Releases",
"a",
"slave",
"from",
"request",
"handling"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/Slave.php#L167-L175 | train |
php-pm/php-pm | src/RequestHandler.php | RequestHandler.handle | public function handle(ConnectionInterface $incoming)
{
$this->incoming = $incoming;
$this->incoming->on('data', [$this, 'handleData']);
$this->incoming->on('close', function () {
$this->connectionOpen = false;
});
$this->start = microtime(true);
$this->requestSentAt = microtime(true);
$this->getNextSlave();
if ($this->maxExecutionTime > 0) {
$this->maxExecutionTimer = $this->loop->addTimer($this->maxExecutionTime, [$this, 'maxExecutionTimeExceeded']);
}
} | php | public function handle(ConnectionInterface $incoming)
{
$this->incoming = $incoming;
$this->incoming->on('data', [$this, 'handleData']);
$this->incoming->on('close', function () {
$this->connectionOpen = false;
});
$this->start = microtime(true);
$this->requestSentAt = microtime(true);
$this->getNextSlave();
if ($this->maxExecutionTime > 0) {
$this->maxExecutionTimer = $this->loop->addTimer($this->maxExecutionTime, [$this, 'maxExecutionTimeExceeded']);
}
} | [
"public",
"function",
"handle",
"(",
"ConnectionInterface",
"$",
"incoming",
")",
"{",
"$",
"this",
"->",
"incoming",
"=",
"$",
"incoming",
";",
"$",
"this",
"->",
"incoming",
"->",
"on",
"(",
"'data'",
",",
"[",
"$",
"this",
",",
"'handleData'",
"]",
")",
";",
"$",
"this",
"->",
"incoming",
"->",
"on",
"(",
"'close'",
",",
"function",
"(",
")",
"{",
"$",
"this",
"->",
"connectionOpen",
"=",
"false",
";",
"}",
")",
";",
"$",
"this",
"->",
"start",
"=",
"microtime",
"(",
"true",
")",
";",
"$",
"this",
"->",
"requestSentAt",
"=",
"microtime",
"(",
"true",
")",
";",
"$",
"this",
"->",
"getNextSlave",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"maxExecutionTime",
">",
"0",
")",
"{",
"$",
"this",
"->",
"maxExecutionTimer",
"=",
"$",
"this",
"->",
"loop",
"->",
"addTimer",
"(",
"$",
"this",
"->",
"maxExecutionTime",
",",
"[",
"$",
"this",
",",
"'maxExecutionTimeExceeded'",
"]",
")",
";",
"}",
"}"
]
| Handle incoming client connection
@param ConnectionInterface $incoming | [
"Handle",
"incoming",
"client",
"connection"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/RequestHandler.php#L97-L113 | train |
php-pm/php-pm | src/RequestHandler.php | RequestHandler.handleData | public function handleData($data)
{
$this->incomingBuffer .= $data;
if ($this->connection && $this->isHeaderEnd($this->incomingBuffer)) {
$remoteAddress = (string) $this->incoming->getRemoteAddress();
$headersToReplace = [
'X-PHP-PM-Remote-IP' => trim(parse_url($remoteAddress, PHP_URL_HOST), '[]'),
'X-PHP-PM-Remote-Port' => trim(parse_url($remoteAddress, PHP_URL_PORT), '[]')
];
$buffer = $this->replaceHeader($this->incomingBuffer, $headersToReplace);
$this->connection->write($buffer);
$this->incoming->removeListener('data', [$this, 'handleData']);
$this->incoming->pipe($this->connection);
}
} | php | public function handleData($data)
{
$this->incomingBuffer .= $data;
if ($this->connection && $this->isHeaderEnd($this->incomingBuffer)) {
$remoteAddress = (string) $this->incoming->getRemoteAddress();
$headersToReplace = [
'X-PHP-PM-Remote-IP' => trim(parse_url($remoteAddress, PHP_URL_HOST), '[]'),
'X-PHP-PM-Remote-Port' => trim(parse_url($remoteAddress, PHP_URL_PORT), '[]')
];
$buffer = $this->replaceHeader($this->incomingBuffer, $headersToReplace);
$this->connection->write($buffer);
$this->incoming->removeListener('data', [$this, 'handleData']);
$this->incoming->pipe($this->connection);
}
} | [
"public",
"function",
"handleData",
"(",
"$",
"data",
")",
"{",
"$",
"this",
"->",
"incomingBuffer",
".=",
"$",
"data",
";",
"if",
"(",
"$",
"this",
"->",
"connection",
"&&",
"$",
"this",
"->",
"isHeaderEnd",
"(",
"$",
"this",
"->",
"incomingBuffer",
")",
")",
"{",
"$",
"remoteAddress",
"=",
"(",
"string",
")",
"$",
"this",
"->",
"incoming",
"->",
"getRemoteAddress",
"(",
")",
";",
"$",
"headersToReplace",
"=",
"[",
"'X-PHP-PM-Remote-IP'",
"=>",
"trim",
"(",
"parse_url",
"(",
"$",
"remoteAddress",
",",
"PHP_URL_HOST",
")",
",",
"'[]'",
")",
",",
"'X-PHP-PM-Remote-Port'",
"=>",
"trim",
"(",
"parse_url",
"(",
"$",
"remoteAddress",
",",
"PHP_URL_PORT",
")",
",",
"'[]'",
")",
"]",
";",
"$",
"buffer",
"=",
"$",
"this",
"->",
"replaceHeader",
"(",
"$",
"this",
"->",
"incomingBuffer",
",",
"$",
"headersToReplace",
")",
";",
"$",
"this",
"->",
"connection",
"->",
"write",
"(",
"$",
"buffer",
")",
";",
"$",
"this",
"->",
"incoming",
"->",
"removeListener",
"(",
"'data'",
",",
"[",
"$",
"this",
",",
"'handleData'",
"]",
")",
";",
"$",
"this",
"->",
"incoming",
"->",
"pipe",
"(",
"$",
"this",
"->",
"connection",
")",
";",
"}",
"}"
]
| Buffer incoming data until slave connection is available
and headers have been received
@param string $data | [
"Buffer",
"incoming",
"data",
"until",
"slave",
"connection",
"is",
"available",
"and",
"headers",
"have",
"been",
"received"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/RequestHandler.php#L121-L138 | train |
php-pm/php-pm | src/RequestHandler.php | RequestHandler.getNextSlave | public function getNextSlave()
{
// client went away while waiting for worker
if (!$this->connectionOpen) {
return;
}
$available = $this->slaves->getByStatus(Slave::READY);
if (count($available)) {
// pick first slave
$slave = array_shift($available);
// slave available -> connect
if ($this->tryOccupySlave($slave)) {
return;
}
}
// keep retrying until slave becomes available, unless timeout has been exceeded
if (time() < ($this->requestSentAt + $this->timeout)) {
$this->loop->futureTick([$this, 'getNextSlave']);
} else {
// Return a "503 Service Unavailable" response
$this->output->writeln(sprintf('No slaves available to handle the request and timeout %d seconds exceeded', $this->timeout));
$this->incoming->write($this->createErrorResponse('503 Service Temporarily Unavailable', 'Service Temporarily Unavailable'));
$this->incoming->end();
}
} | php | public function getNextSlave()
{
// client went away while waiting for worker
if (!$this->connectionOpen) {
return;
}
$available = $this->slaves->getByStatus(Slave::READY);
if (count($available)) {
// pick first slave
$slave = array_shift($available);
// slave available -> connect
if ($this->tryOccupySlave($slave)) {
return;
}
}
// keep retrying until slave becomes available, unless timeout has been exceeded
if (time() < ($this->requestSentAt + $this->timeout)) {
$this->loop->futureTick([$this, 'getNextSlave']);
} else {
// Return a "503 Service Unavailable" response
$this->output->writeln(sprintf('No slaves available to handle the request and timeout %d seconds exceeded', $this->timeout));
$this->incoming->write($this->createErrorResponse('503 Service Temporarily Unavailable', 'Service Temporarily Unavailable'));
$this->incoming->end();
}
} | [
"public",
"function",
"getNextSlave",
"(",
")",
"{",
"// client went away while waiting for worker",
"if",
"(",
"!",
"$",
"this",
"->",
"connectionOpen",
")",
"{",
"return",
";",
"}",
"$",
"available",
"=",
"$",
"this",
"->",
"slaves",
"->",
"getByStatus",
"(",
"Slave",
"::",
"READY",
")",
";",
"if",
"(",
"count",
"(",
"$",
"available",
")",
")",
"{",
"// pick first slave",
"$",
"slave",
"=",
"array_shift",
"(",
"$",
"available",
")",
";",
"// slave available -> connect",
"if",
"(",
"$",
"this",
"->",
"tryOccupySlave",
"(",
"$",
"slave",
")",
")",
"{",
"return",
";",
"}",
"}",
"// keep retrying until slave becomes available, unless timeout has been exceeded",
"if",
"(",
"time",
"(",
")",
"<",
"(",
"$",
"this",
"->",
"requestSentAt",
"+",
"$",
"this",
"->",
"timeout",
")",
")",
"{",
"$",
"this",
"->",
"loop",
"->",
"futureTick",
"(",
"[",
"$",
"this",
",",
"'getNextSlave'",
"]",
")",
";",
"}",
"else",
"{",
"// Return a \"503 Service Unavailable\" response",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'No slaves available to handle the request and timeout %d seconds exceeded'",
",",
"$",
"this",
"->",
"timeout",
")",
")",
";",
"$",
"this",
"->",
"incoming",
"->",
"write",
"(",
"$",
"this",
"->",
"createErrorResponse",
"(",
"'503 Service Temporarily Unavailable'",
",",
"'Service Temporarily Unavailable'",
")",
")",
";",
"$",
"this",
"->",
"incoming",
"->",
"end",
"(",
")",
";",
"}",
"}"
]
| Get next free slave from pool
Asynchronously keep trying until slave becomes available | [
"Get",
"next",
"free",
"slave",
"from",
"pool",
"Asynchronously",
"keep",
"trying",
"until",
"slave",
"becomes",
"available"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/RequestHandler.php#L144-L171 | train |
php-pm/php-pm | src/RequestHandler.php | RequestHandler.tryOccupySlave | public function tryOccupySlave(Slave $slave)
{
if ($slave->isExpired()) {
$slave->close();
$this->output->writeln(sprintf('Restart worker #%d because it reached its TTL', $slave->getPort()));
$slave->getConnection()->close();
return false;
}
$this->redirectionTries++;
$this->slave = $slave;
$this->verboseTimer(function ($took) {
return sprintf('<info>took abnormal %.3f seconds for choosing next free worker</info>', $took);
});
// mark slave as busy
$this->slave->occupy();
$connector = new UnixConnector($this->loop);
$connector = new TimeoutConnector($connector, $this->timeout, $this->loop);
$socketPath = $this->getSlaveSocketPath($this->slave->getPort());
$connector->connect($socketPath)->then(
[$this, 'slaveConnected'],
[$this, 'slaveConnectFailed']
);
return true;
} | php | public function tryOccupySlave(Slave $slave)
{
if ($slave->isExpired()) {
$slave->close();
$this->output->writeln(sprintf('Restart worker #%d because it reached its TTL', $slave->getPort()));
$slave->getConnection()->close();
return false;
}
$this->redirectionTries++;
$this->slave = $slave;
$this->verboseTimer(function ($took) {
return sprintf('<info>took abnormal %.3f seconds for choosing next free worker</info>', $took);
});
// mark slave as busy
$this->slave->occupy();
$connector = new UnixConnector($this->loop);
$connector = new TimeoutConnector($connector, $this->timeout, $this->loop);
$socketPath = $this->getSlaveSocketPath($this->slave->getPort());
$connector->connect($socketPath)->then(
[$this, 'slaveConnected'],
[$this, 'slaveConnectFailed']
);
return true;
} | [
"public",
"function",
"tryOccupySlave",
"(",
"Slave",
"$",
"slave",
")",
"{",
"if",
"(",
"$",
"slave",
"->",
"isExpired",
"(",
")",
")",
"{",
"$",
"slave",
"->",
"close",
"(",
")",
";",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'Restart worker #%d because it reached its TTL'",
",",
"$",
"slave",
"->",
"getPort",
"(",
")",
")",
")",
";",
"$",
"slave",
"->",
"getConnection",
"(",
")",
"->",
"close",
"(",
")",
";",
"return",
"false",
";",
"}",
"$",
"this",
"->",
"redirectionTries",
"++",
";",
"$",
"this",
"->",
"slave",
"=",
"$",
"slave",
";",
"$",
"this",
"->",
"verboseTimer",
"(",
"function",
"(",
"$",
"took",
")",
"{",
"return",
"sprintf",
"(",
"'<info>took abnormal %.3f seconds for choosing next free worker</info>'",
",",
"$",
"took",
")",
";",
"}",
")",
";",
"// mark slave as busy",
"$",
"this",
"->",
"slave",
"->",
"occupy",
"(",
")",
";",
"$",
"connector",
"=",
"new",
"UnixConnector",
"(",
"$",
"this",
"->",
"loop",
")",
";",
"$",
"connector",
"=",
"new",
"TimeoutConnector",
"(",
"$",
"connector",
",",
"$",
"this",
"->",
"timeout",
",",
"$",
"this",
"->",
"loop",
")",
";",
"$",
"socketPath",
"=",
"$",
"this",
"->",
"getSlaveSocketPath",
"(",
"$",
"this",
"->",
"slave",
"->",
"getPort",
"(",
")",
")",
";",
"$",
"connector",
"->",
"connect",
"(",
"$",
"socketPath",
")",
"->",
"then",
"(",
"[",
"$",
"this",
",",
"'slaveConnected'",
"]",
",",
"[",
"$",
"this",
",",
"'slaveConnectFailed'",
"]",
")",
";",
"return",
"true",
";",
"}"
]
| Slave available handler
@param Slave $slave available slave instance
@return bool Slave is available | [
"Slave",
"available",
"handler"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/RequestHandler.php#L195-L224 | train |
php-pm/php-pm | src/RequestHandler.php | RequestHandler.slaveConnected | public function slaveConnected(ConnectionInterface $connection)
{
$this->connection = $connection;
$this->verboseTimer(function ($took) {
return sprintf('<info>Took abnormal %.3f seconds for connecting to worker %d</info>', $took, $this->slave->getPort());
});
// call handler once in case entire request as already been buffered
$this->handleData('');
// close slave connection when client goes away
$this->incoming->on('close', [$this->connection, 'close']);
// update slave availability
$this->connection->on('close', [$this, 'slaveClosed']);
// keep track of the last sent data to detect if slave exited abnormally
$this->connection->on('data', function ($data) {
$this->lastOutgoingData = $data;
});
// relay data to client
$this->connection->pipe($this->incoming, ['end' => false]);
} | php | public function slaveConnected(ConnectionInterface $connection)
{
$this->connection = $connection;
$this->verboseTimer(function ($took) {
return sprintf('<info>Took abnormal %.3f seconds for connecting to worker %d</info>', $took, $this->slave->getPort());
});
// call handler once in case entire request as already been buffered
$this->handleData('');
// close slave connection when client goes away
$this->incoming->on('close', [$this->connection, 'close']);
// update slave availability
$this->connection->on('close', [$this, 'slaveClosed']);
// keep track of the last sent data to detect if slave exited abnormally
$this->connection->on('data', function ($data) {
$this->lastOutgoingData = $data;
});
// relay data to client
$this->connection->pipe($this->incoming, ['end' => false]);
} | [
"public",
"function",
"slaveConnected",
"(",
"ConnectionInterface",
"$",
"connection",
")",
"{",
"$",
"this",
"->",
"connection",
"=",
"$",
"connection",
";",
"$",
"this",
"->",
"verboseTimer",
"(",
"function",
"(",
"$",
"took",
")",
"{",
"return",
"sprintf",
"(",
"'<info>Took abnormal %.3f seconds for connecting to worker %d</info>'",
",",
"$",
"took",
",",
"$",
"this",
"->",
"slave",
"->",
"getPort",
"(",
")",
")",
";",
"}",
")",
";",
"// call handler once in case entire request as already been buffered",
"$",
"this",
"->",
"handleData",
"(",
"''",
")",
";",
"// close slave connection when client goes away",
"$",
"this",
"->",
"incoming",
"->",
"on",
"(",
"'close'",
",",
"[",
"$",
"this",
"->",
"connection",
",",
"'close'",
"]",
")",
";",
"// update slave availability",
"$",
"this",
"->",
"connection",
"->",
"on",
"(",
"'close'",
",",
"[",
"$",
"this",
",",
"'slaveClosed'",
"]",
")",
";",
"// keep track of the last sent data to detect if slave exited abnormally",
"$",
"this",
"->",
"connection",
"->",
"on",
"(",
"'data'",
",",
"function",
"(",
"$",
"data",
")",
"{",
"$",
"this",
"->",
"lastOutgoingData",
"=",
"$",
"data",
";",
"}",
")",
";",
"// relay data to client",
"$",
"this",
"->",
"connection",
"->",
"pipe",
"(",
"$",
"this",
"->",
"incoming",
",",
"[",
"'end'",
"=>",
"false",
"]",
")",
";",
"}"
]
| Handle successful slave connection
@param ConnectionInterface $connection Slave connection | [
"Handle",
"successful",
"slave",
"connection"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/RequestHandler.php#L231-L255 | train |
php-pm/php-pm | src/RequestHandler.php | RequestHandler.maxExecutionTimeExceeded | public function maxExecutionTimeExceeded()
{
// client went away while waiting for worker
if (!$this->connectionOpen) {
return false;
}
$this->incoming->write($this->createErrorResponse('504 Gateway Timeout', 'Maximum execution time exceeded'));
$this->lastOutgoingData = 'not empty'; // Avoid triggering 502
// mark slave as closed
$this->slave->close();
$this->output->writeln(sprintf('Maximum execution time of %d seconds exceeded. Closing worker.', $this->maxExecutionTime));
$this->slave->getConnection()->close();
} | php | public function maxExecutionTimeExceeded()
{
// client went away while waiting for worker
if (!$this->connectionOpen) {
return false;
}
$this->incoming->write($this->createErrorResponse('504 Gateway Timeout', 'Maximum execution time exceeded'));
$this->lastOutgoingData = 'not empty'; // Avoid triggering 502
// mark slave as closed
$this->slave->close();
$this->output->writeln(sprintf('Maximum execution time of %d seconds exceeded. Closing worker.', $this->maxExecutionTime));
$this->slave->getConnection()->close();
} | [
"public",
"function",
"maxExecutionTimeExceeded",
"(",
")",
"{",
"// client went away while waiting for worker",
"if",
"(",
"!",
"$",
"this",
"->",
"connectionOpen",
")",
"{",
"return",
"false",
";",
"}",
"$",
"this",
"->",
"incoming",
"->",
"write",
"(",
"$",
"this",
"->",
"createErrorResponse",
"(",
"'504 Gateway Timeout'",
",",
"'Maximum execution time exceeded'",
")",
")",
";",
"$",
"this",
"->",
"lastOutgoingData",
"=",
"'not empty'",
";",
"// Avoid triggering 502",
"// mark slave as closed",
"$",
"this",
"->",
"slave",
"->",
"close",
"(",
")",
";",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'Maximum execution time of %d seconds exceeded. Closing worker.'",
",",
"$",
"this",
"->",
"maxExecutionTime",
")",
")",
";",
"$",
"this",
"->",
"slave",
"->",
"getConnection",
"(",
")",
"->",
"close",
"(",
")",
";",
"}"
]
| Stop the worker if the max execution time has been exceeded and return 504 | [
"Stop",
"the",
"worker",
"if",
"the",
"max",
"execution",
"time",
"has",
"been",
"exceeded",
"and",
"return",
"504"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/RequestHandler.php#L260-L274 | train |
php-pm/php-pm | src/RequestHandler.php | RequestHandler.slaveClosed | public function slaveClosed()
{
$this->verboseTimer(function ($took) {
return sprintf('<info>Worker %d took abnormal %.3f seconds for handling a connection</info>', $this->slave->getPort(), $took);
});
// Return a "502 Bad Gateway" response if the response was empty
if ($this->lastOutgoingData == '') {
$this->output->writeln('Script did not return a valid HTTP response. Maybe it has called exit() prematurely?');
$this->incoming->write($this->createErrorResponse('502 Bad Gateway', 'Slave returned an invalid HTTP response. Maybe the script has called exit() prematurely?'));
}
$this->incoming->end();
if ($this->maxExecutionTime > 0) {
$this->loop->cancelTimer($this->maxExecutionTimer);
}
if ($this->slave->getStatus() === Slave::LOCKED) {
// slave was locked, so mark as closed now.
$this->slave->close();
$this->output->writeln(sprintf('Marking locked worker #%d as closed', $this->slave->getPort()));
$this->slave->getConnection()->close();
} elseif ($this->slave->getStatus() !== Slave::CLOSED) {
// if slave has already closed its connection to master,
// it probably died and is already terminated
// mark slave as available
$this->slave->release();
/** @var ConnectionInterface $connection */
$connection = $this->slave->getConnection();
$maxRequests = $this->slave->getMaxRequests();
if ($this->slave->getHandledRequests() >= $maxRequests) {
$this->slave->close();
$this->output->writeln(sprintf('Restart worker #%d because it reached max requests of %d', $this->slave->getPort(), $maxRequests));
$connection->close();
}
// Enforce memory limit
$memoryLimit = $this->slave->getMemoryLimit();
if ($memoryLimit > 0 && $this->slave->getUsedMemory() >= $memoryLimit) {
$this->slave->close();
$this->output->writeln(sprintf('Restart worker #%d because it reached memory limit of %d', $this->slave->getPort(), $memoryLimit));
$connection->close();
}
}
} | php | public function slaveClosed()
{
$this->verboseTimer(function ($took) {
return sprintf('<info>Worker %d took abnormal %.3f seconds for handling a connection</info>', $this->slave->getPort(), $took);
});
// Return a "502 Bad Gateway" response if the response was empty
if ($this->lastOutgoingData == '') {
$this->output->writeln('Script did not return a valid HTTP response. Maybe it has called exit() prematurely?');
$this->incoming->write($this->createErrorResponse('502 Bad Gateway', 'Slave returned an invalid HTTP response. Maybe the script has called exit() prematurely?'));
}
$this->incoming->end();
if ($this->maxExecutionTime > 0) {
$this->loop->cancelTimer($this->maxExecutionTimer);
}
if ($this->slave->getStatus() === Slave::LOCKED) {
// slave was locked, so mark as closed now.
$this->slave->close();
$this->output->writeln(sprintf('Marking locked worker #%d as closed', $this->slave->getPort()));
$this->slave->getConnection()->close();
} elseif ($this->slave->getStatus() !== Slave::CLOSED) {
// if slave has already closed its connection to master,
// it probably died and is already terminated
// mark slave as available
$this->slave->release();
/** @var ConnectionInterface $connection */
$connection = $this->slave->getConnection();
$maxRequests = $this->slave->getMaxRequests();
if ($this->slave->getHandledRequests() >= $maxRequests) {
$this->slave->close();
$this->output->writeln(sprintf('Restart worker #%d because it reached max requests of %d', $this->slave->getPort(), $maxRequests));
$connection->close();
}
// Enforce memory limit
$memoryLimit = $this->slave->getMemoryLimit();
if ($memoryLimit > 0 && $this->slave->getUsedMemory() >= $memoryLimit) {
$this->slave->close();
$this->output->writeln(sprintf('Restart worker #%d because it reached memory limit of %d', $this->slave->getPort(), $memoryLimit));
$connection->close();
}
}
} | [
"public",
"function",
"slaveClosed",
"(",
")",
"{",
"$",
"this",
"->",
"verboseTimer",
"(",
"function",
"(",
"$",
"took",
")",
"{",
"return",
"sprintf",
"(",
"'<info>Worker %d took abnormal %.3f seconds for handling a connection</info>'",
",",
"$",
"this",
"->",
"slave",
"->",
"getPort",
"(",
")",
",",
"$",
"took",
")",
";",
"}",
")",
";",
"// Return a \"502 Bad Gateway\" response if the response was empty",
"if",
"(",
"$",
"this",
"->",
"lastOutgoingData",
"==",
"''",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"'Script did not return a valid HTTP response. Maybe it has called exit() prematurely?'",
")",
";",
"$",
"this",
"->",
"incoming",
"->",
"write",
"(",
"$",
"this",
"->",
"createErrorResponse",
"(",
"'502 Bad Gateway'",
",",
"'Slave returned an invalid HTTP response. Maybe the script has called exit() prematurely?'",
")",
")",
";",
"}",
"$",
"this",
"->",
"incoming",
"->",
"end",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"maxExecutionTime",
">",
"0",
")",
"{",
"$",
"this",
"->",
"loop",
"->",
"cancelTimer",
"(",
"$",
"this",
"->",
"maxExecutionTimer",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"slave",
"->",
"getStatus",
"(",
")",
"===",
"Slave",
"::",
"LOCKED",
")",
"{",
"// slave was locked, so mark as closed now.",
"$",
"this",
"->",
"slave",
"->",
"close",
"(",
")",
";",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'Marking locked worker #%d as closed'",
",",
"$",
"this",
"->",
"slave",
"->",
"getPort",
"(",
")",
")",
")",
";",
"$",
"this",
"->",
"slave",
"->",
"getConnection",
"(",
")",
"->",
"close",
"(",
")",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"slave",
"->",
"getStatus",
"(",
")",
"!==",
"Slave",
"::",
"CLOSED",
")",
"{",
"// if slave has already closed its connection to master,",
"// it probably died and is already terminated",
"// mark slave as available",
"$",
"this",
"->",
"slave",
"->",
"release",
"(",
")",
";",
"/** @var ConnectionInterface $connection */",
"$",
"connection",
"=",
"$",
"this",
"->",
"slave",
"->",
"getConnection",
"(",
")",
";",
"$",
"maxRequests",
"=",
"$",
"this",
"->",
"slave",
"->",
"getMaxRequests",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"slave",
"->",
"getHandledRequests",
"(",
")",
">=",
"$",
"maxRequests",
")",
"{",
"$",
"this",
"->",
"slave",
"->",
"close",
"(",
")",
";",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'Restart worker #%d because it reached max requests of %d'",
",",
"$",
"this",
"->",
"slave",
"->",
"getPort",
"(",
")",
",",
"$",
"maxRequests",
")",
")",
";",
"$",
"connection",
"->",
"close",
"(",
")",
";",
"}",
"// Enforce memory limit",
"$",
"memoryLimit",
"=",
"$",
"this",
"->",
"slave",
"->",
"getMemoryLimit",
"(",
")",
";",
"if",
"(",
"$",
"memoryLimit",
">",
"0",
"&&",
"$",
"this",
"->",
"slave",
"->",
"getUsedMemory",
"(",
")",
">=",
"$",
"memoryLimit",
")",
"{",
"$",
"this",
"->",
"slave",
"->",
"close",
"(",
")",
";",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'Restart worker #%d because it reached memory limit of %d'",
",",
"$",
"this",
"->",
"slave",
"->",
"getPort",
"(",
")",
",",
"$",
"memoryLimit",
")",
")",
";",
"$",
"connection",
"->",
"close",
"(",
")",
";",
"}",
"}",
"}"
]
| Handle slave disconnected
Typically called after slave has finished handling request | [
"Handle",
"slave",
"disconnected"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/RequestHandler.php#L281-L326 | train |
php-pm/php-pm | src/RequestHandler.php | RequestHandler.slaveConnectFailed | public function slaveConnectFailed(\Exception $e)
{
$this->slave->release();
$this->verboseTimer(function ($took) use ($e) {
return sprintf(
'<error>Connection to worker %d failed. Try #%d, took %.3fs ' .
'(timeout %ds). Error message: [%d] %s</error>',
$this->slave->getPort(),
$this->redirectionTries,
$took,
$this->timeout,
$e->getCode(),
$e->getMessage()
);
}, true);
// should not get any more access to this slave instance
unset($this->slave);
// try next free slave, let loop schedule it (stack friendly)
// after 10th retry add 10ms delay, keep increasing until timeout
$delay = min($this->timeout, floor($this->redirectionTries / 10) / 100);
$this->loop->addTimer($delay, [$this, 'getNextSlave']);
} | php | public function slaveConnectFailed(\Exception $e)
{
$this->slave->release();
$this->verboseTimer(function ($took) use ($e) {
return sprintf(
'<error>Connection to worker %d failed. Try #%d, took %.3fs ' .
'(timeout %ds). Error message: [%d] %s</error>',
$this->slave->getPort(),
$this->redirectionTries,
$took,
$this->timeout,
$e->getCode(),
$e->getMessage()
);
}, true);
// should not get any more access to this slave instance
unset($this->slave);
// try next free slave, let loop schedule it (stack friendly)
// after 10th retry add 10ms delay, keep increasing until timeout
$delay = min($this->timeout, floor($this->redirectionTries / 10) / 100);
$this->loop->addTimer($delay, [$this, 'getNextSlave']);
} | [
"public",
"function",
"slaveConnectFailed",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"slave",
"->",
"release",
"(",
")",
";",
"$",
"this",
"->",
"verboseTimer",
"(",
"function",
"(",
"$",
"took",
")",
"use",
"(",
"$",
"e",
")",
"{",
"return",
"sprintf",
"(",
"'<error>Connection to worker %d failed. Try #%d, took %.3fs '",
".",
"'(timeout %ds). Error message: [%d] %s</error>'",
",",
"$",
"this",
"->",
"slave",
"->",
"getPort",
"(",
")",
",",
"$",
"this",
"->",
"redirectionTries",
",",
"$",
"took",
",",
"$",
"this",
"->",
"timeout",
",",
"$",
"e",
"->",
"getCode",
"(",
")",
",",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"}",
",",
"true",
")",
";",
"// should not get any more access to this slave instance",
"unset",
"(",
"$",
"this",
"->",
"slave",
")",
";",
"// try next free slave, let loop schedule it (stack friendly)",
"// after 10th retry add 10ms delay, keep increasing until timeout",
"$",
"delay",
"=",
"min",
"(",
"$",
"this",
"->",
"timeout",
",",
"floor",
"(",
"$",
"this",
"->",
"redirectionTries",
"/",
"10",
")",
"/",
"100",
")",
";",
"$",
"this",
"->",
"loop",
"->",
"addTimer",
"(",
"$",
"delay",
",",
"[",
"$",
"this",
",",
"'getNextSlave'",
"]",
")",
";",
"}"
]
| Handle failed slave connection
Connection may fail because of timeouts or crashed or dying worker.
Since the worker may only very busy or dying it's put back into the
available worker list. If it is really dying it will be removed from the
worker list by the connection:close event.
@param \Exception $e slave connection error | [
"Handle",
"failed",
"slave",
"connection"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/RequestHandler.php#L338-L362 | train |
php-pm/php-pm | src/RequestHandler.php | RequestHandler.verboseTimer | protected function verboseTimer($callback, $always = false)
{
$took = microtime(true) - $this->start;
if (($always || $took > 1) && $this->output->isVeryVerbose()) {
$message = $callback($took);
$this->output->writeln($message);
}
$this->start = microtime(true);
} | php | protected function verboseTimer($callback, $always = false)
{
$took = microtime(true) - $this->start;
if (($always || $took > 1) && $this->output->isVeryVerbose()) {
$message = $callback($took);
$this->output->writeln($message);
}
$this->start = microtime(true);
} | [
"protected",
"function",
"verboseTimer",
"(",
"$",
"callback",
",",
"$",
"always",
"=",
"false",
")",
"{",
"$",
"took",
"=",
"microtime",
"(",
"true",
")",
"-",
"$",
"this",
"->",
"start",
";",
"if",
"(",
"(",
"$",
"always",
"||",
"$",
"took",
">",
"1",
")",
"&&",
"$",
"this",
"->",
"output",
"->",
"isVeryVerbose",
"(",
")",
")",
"{",
"$",
"message",
"=",
"$",
"callback",
"(",
"$",
"took",
")",
";",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"$",
"message",
")",
";",
"}",
"$",
"this",
"->",
"start",
"=",
"microtime",
"(",
"true",
")",
";",
"}"
]
| Section timer. Measure execution time hand output if verbose mode.
@param callable $callback
@param bool $always Invoke callback regardless of execution time | [
"Section",
"timer",
".",
"Measure",
"execution",
"time",
"hand",
"output",
"if",
"verbose",
"mode",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/RequestHandler.php#L370-L378 | train |
php-pm/php-pm | src/RequestHandler.php | RequestHandler.replaceHeader | protected function replaceHeader($header, $headersToReplace)
{
$result = $header;
foreach ($headersToReplace as $key => $value) {
if (false !== $headerPosition = stripos($result, $key . ':')) {
// check how long the header is
$length = strpos(substr($header, $headerPosition), "\r\n");
$result = substr_replace($result, "$key: $value", $headerPosition, $length);
} else {
// $key is not in header yet, add it at the end
$end = strpos($result, "\r\n\r\n");
$result = substr_replace($result, "\r\n$key: $value", $end, 0);
}
}
return $result;
} | php | protected function replaceHeader($header, $headersToReplace)
{
$result = $header;
foreach ($headersToReplace as $key => $value) {
if (false !== $headerPosition = stripos($result, $key . ':')) {
// check how long the header is
$length = strpos(substr($header, $headerPosition), "\r\n");
$result = substr_replace($result, "$key: $value", $headerPosition, $length);
} else {
// $key is not in header yet, add it at the end
$end = strpos($result, "\r\n\r\n");
$result = substr_replace($result, "\r\n$key: $value", $end, 0);
}
}
return $result;
} | [
"protected",
"function",
"replaceHeader",
"(",
"$",
"header",
",",
"$",
"headersToReplace",
")",
"{",
"$",
"result",
"=",
"$",
"header",
";",
"foreach",
"(",
"$",
"headersToReplace",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"false",
"!==",
"$",
"headerPosition",
"=",
"stripos",
"(",
"$",
"result",
",",
"$",
"key",
".",
"':'",
")",
")",
"{",
"// check how long the header is",
"$",
"length",
"=",
"strpos",
"(",
"substr",
"(",
"$",
"header",
",",
"$",
"headerPosition",
")",
",",
"\"\\r\\n\"",
")",
";",
"$",
"result",
"=",
"substr_replace",
"(",
"$",
"result",
",",
"\"$key: $value\"",
",",
"$",
"headerPosition",
",",
"$",
"length",
")",
";",
"}",
"else",
"{",
"// $key is not in header yet, add it at the end",
"$",
"end",
"=",
"strpos",
"(",
"$",
"result",
",",
"\"\\r\\n\\r\\n\"",
")",
";",
"$",
"result",
"=",
"substr_replace",
"(",
"$",
"result",
",",
"\"\\r\\n$key: $value\"",
",",
"$",
"end",
",",
"0",
")",
";",
"}",
"}",
"return",
"$",
"result",
";",
"}"
]
| Replaces or injects header
@param string $header
@param string[] $headersToReplace
@return string | [
"Replaces",
"or",
"injects",
"header"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/RequestHandler.php#L400-L417 | train |
php-pm/php-pm | src/ProcessSlave.php | ProcessSlave.prepareShutdown | public function prepareShutdown()
{
if ($this->inShutdown) {
return false;
}
if ($this->errorLogger && $logs = $this->errorLogger->cleanLogs()) {
$messages = array_map(
function ($item) {
//array($level, $message, $context);
$message = $item[1];
$context = $item[2];
if (isset($context['file'])) {
$message .= ' in ' . $context['file'] . ':' . $context['line'];
}
if (isset($context['stack'])) {
foreach ($context['stack'] as $idx => $stack) {
$message .= PHP_EOL . sprintf(
"#%d: %s%s %s%s",
$idx,
isset($stack['class']) ? $stack['class'] . '->' : '',
$stack['function'],
isset($stack['file']) ? 'in' . $stack['file'] : '',
isset($stack['line']) ? ':' . $stack['line'] : ''
);
}
}
return $message;
},
$logs
);
error_log(implode(PHP_EOL, $messages));
}
$this->inShutdown = true;
$this->sendCurrentFiles();
// $this->controller->close() is no longer called here, because it prevented
// shutdown functions from triggering (see https://github.com/php-pm/php-pm/pull/432)
if ($this->server) {
@$this->server->close();
}
if ($this->loop) {
$this->loop->stop();
}
return true;
} | php | public function prepareShutdown()
{
if ($this->inShutdown) {
return false;
}
if ($this->errorLogger && $logs = $this->errorLogger->cleanLogs()) {
$messages = array_map(
function ($item) {
//array($level, $message, $context);
$message = $item[1];
$context = $item[2];
if (isset($context['file'])) {
$message .= ' in ' . $context['file'] . ':' . $context['line'];
}
if (isset($context['stack'])) {
foreach ($context['stack'] as $idx => $stack) {
$message .= PHP_EOL . sprintf(
"#%d: %s%s %s%s",
$idx,
isset($stack['class']) ? $stack['class'] . '->' : '',
$stack['function'],
isset($stack['file']) ? 'in' . $stack['file'] : '',
isset($stack['line']) ? ':' . $stack['line'] : ''
);
}
}
return $message;
},
$logs
);
error_log(implode(PHP_EOL, $messages));
}
$this->inShutdown = true;
$this->sendCurrentFiles();
// $this->controller->close() is no longer called here, because it prevented
// shutdown functions from triggering (see https://github.com/php-pm/php-pm/pull/432)
if ($this->server) {
@$this->server->close();
}
if ($this->loop) {
$this->loop->stop();
}
return true;
} | [
"public",
"function",
"prepareShutdown",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"inShutdown",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"errorLogger",
"&&",
"$",
"logs",
"=",
"$",
"this",
"->",
"errorLogger",
"->",
"cleanLogs",
"(",
")",
")",
"{",
"$",
"messages",
"=",
"array_map",
"(",
"function",
"(",
"$",
"item",
")",
"{",
"//array($level, $message, $context);",
"$",
"message",
"=",
"$",
"item",
"[",
"1",
"]",
";",
"$",
"context",
"=",
"$",
"item",
"[",
"2",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"context",
"[",
"'file'",
"]",
")",
")",
"{",
"$",
"message",
".=",
"' in '",
".",
"$",
"context",
"[",
"'file'",
"]",
".",
"':'",
".",
"$",
"context",
"[",
"'line'",
"]",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"context",
"[",
"'stack'",
"]",
")",
")",
"{",
"foreach",
"(",
"$",
"context",
"[",
"'stack'",
"]",
"as",
"$",
"idx",
"=>",
"$",
"stack",
")",
"{",
"$",
"message",
".=",
"PHP_EOL",
".",
"sprintf",
"(",
"\"#%d: %s%s %s%s\"",
",",
"$",
"idx",
",",
"isset",
"(",
"$",
"stack",
"[",
"'class'",
"]",
")",
"?",
"$",
"stack",
"[",
"'class'",
"]",
".",
"'->'",
":",
"''",
",",
"$",
"stack",
"[",
"'function'",
"]",
",",
"isset",
"(",
"$",
"stack",
"[",
"'file'",
"]",
")",
"?",
"'in'",
".",
"$",
"stack",
"[",
"'file'",
"]",
":",
"''",
",",
"isset",
"(",
"$",
"stack",
"[",
"'line'",
"]",
")",
"?",
"':'",
".",
"$",
"stack",
"[",
"'line'",
"]",
":",
"''",
")",
";",
"}",
"}",
"return",
"$",
"message",
";",
"}",
",",
"$",
"logs",
")",
";",
"error_log",
"(",
"implode",
"(",
"PHP_EOL",
",",
"$",
"messages",
")",
")",
";",
"}",
"$",
"this",
"->",
"inShutdown",
"=",
"true",
";",
"$",
"this",
"->",
"sendCurrentFiles",
"(",
")",
";",
"// $this->controller->close() is no longer called here, because it prevented",
"// shutdown functions from triggering (see https://github.com/php-pm/php-pm/pull/432)",
"if",
"(",
"$",
"this",
"->",
"server",
")",
"{",
"@",
"$",
"this",
"->",
"server",
"->",
"close",
"(",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"loop",
")",
"{",
"$",
"this",
"->",
"loop",
"->",
"stop",
"(",
")",
";",
"}",
"return",
"true",
";",
"}"
]
| Shuts down the event loop. This basically exits the process.
@return boolean | [
"Shuts",
"down",
"the",
"event",
"loop",
".",
"This",
"basically",
"exits",
"the",
"process",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessSlave.php#L153-L205 | train |
php-pm/php-pm | src/ProcessSlave.php | ProcessSlave.bootstrap | protected function bootstrap($appBootstrap, $appenv, $debug)
{
if ($bridge = $this->getBridge()) {
$bridge->bootstrap($appBootstrap, $appenv, $debug);
$this->sendMessage($this->controller, 'ready');
}
} | php | protected function bootstrap($appBootstrap, $appenv, $debug)
{
if ($bridge = $this->getBridge()) {
$bridge->bootstrap($appBootstrap, $appenv, $debug);
$this->sendMessage($this->controller, 'ready');
}
} | [
"protected",
"function",
"bootstrap",
"(",
"$",
"appBootstrap",
",",
"$",
"appenv",
",",
"$",
"debug",
")",
"{",
"if",
"(",
"$",
"bridge",
"=",
"$",
"this",
"->",
"getBridge",
"(",
")",
")",
"{",
"$",
"bridge",
"->",
"bootstrap",
"(",
"$",
"appBootstrap",
",",
"$",
"appenv",
",",
"$",
"debug",
")",
";",
"$",
"this",
"->",
"sendMessage",
"(",
"$",
"this",
"->",
"controller",
",",
"'ready'",
")",
";",
"}",
"}"
]
| Bootstraps the actual application.
@param string $appBootstrap
@param string $appenv
@param boolean $debug
@throws \Exception | [
"Bootstraps",
"the",
"actual",
"application",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessSlave.php#L252-L258 | train |
php-pm/php-pm | src/ProcessSlave.php | ProcessSlave.sendCurrentFiles | protected function sendCurrentFiles()
{
if (!$this->isDebug()) {
return;
}
$files = array_merge($this->watchedFiles, get_included_files());
$flipped = array_flip($files);
//speedy way checking if two arrays are different.
if (!$this->lastSentFiles || array_diff_key($flipped, $this->lastSentFiles)) {
$this->lastSentFiles = $flipped;
$this->sendMessage($this->controller, 'files', ['files' => $files]);
}
$this->watchedFiles = [];
} | php | protected function sendCurrentFiles()
{
if (!$this->isDebug()) {
return;
}
$files = array_merge($this->watchedFiles, get_included_files());
$flipped = array_flip($files);
//speedy way checking if two arrays are different.
if (!$this->lastSentFiles || array_diff_key($flipped, $this->lastSentFiles)) {
$this->lastSentFiles = $flipped;
$this->sendMessage($this->controller, 'files', ['files' => $files]);
}
$this->watchedFiles = [];
} | [
"protected",
"function",
"sendCurrentFiles",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isDebug",
"(",
")",
")",
"{",
"return",
";",
"}",
"$",
"files",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"watchedFiles",
",",
"get_included_files",
"(",
")",
")",
";",
"$",
"flipped",
"=",
"array_flip",
"(",
"$",
"files",
")",
";",
"//speedy way checking if two arrays are different.",
"if",
"(",
"!",
"$",
"this",
"->",
"lastSentFiles",
"||",
"array_diff_key",
"(",
"$",
"flipped",
",",
"$",
"this",
"->",
"lastSentFiles",
")",
")",
"{",
"$",
"this",
"->",
"lastSentFiles",
"=",
"$",
"flipped",
";",
"$",
"this",
"->",
"sendMessage",
"(",
"$",
"this",
"->",
"controller",
",",
"'files'",
",",
"[",
"'files'",
"=>",
"$",
"files",
"]",
")",
";",
"}",
"$",
"this",
"->",
"watchedFiles",
"=",
"[",
"]",
";",
"}"
]
| Sends to the master a snapshot of current known php files, so it can track those files and restart
slaves if necessary. | [
"Sends",
"to",
"the",
"master",
"a",
"snapshot",
"of",
"current",
"known",
"php",
"files",
"so",
"it",
"can",
"track",
"those",
"files",
"and",
"restart",
"slaves",
"if",
"necessary",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessSlave.php#L277-L293 | train |
php-pm/php-pm | src/ProcessSlave.php | ProcessSlave.doConnect | private function doConnect()
{
$connector = new UnixConnector($this->loop);
$unixSocket = $this->getControllerSocketPath(false);
$connector->connect($unixSocket)->done(
function ($controller) {
$this->controller = $controller;
$this->loop->addSignal(SIGTERM, [$this, 'shutdown']);
$this->loop->addSignal(SIGINT, [$this, 'shutdown']);
register_shutdown_function([$this, 'prepareShutdown']);
$this->bindProcessMessage($this->controller);
$this->controller->on('close', [$this, 'shutdown']);
// port is the slave identifier
$port = $this->config['port'];
$socketPath = $this->getSlaveSocketPath($port, true);
$this->server = new UnixServer($socketPath, $this->loop);
$httpServer = new HttpServer([$this, 'onRequest']);
$httpServer->listen($this->server);
$this->sendMessage($this->controller, 'register', ['pid' => getmypid(), 'port' => $port]);
}
);
} | php | private function doConnect()
{
$connector = new UnixConnector($this->loop);
$unixSocket = $this->getControllerSocketPath(false);
$connector->connect($unixSocket)->done(
function ($controller) {
$this->controller = $controller;
$this->loop->addSignal(SIGTERM, [$this, 'shutdown']);
$this->loop->addSignal(SIGINT, [$this, 'shutdown']);
register_shutdown_function([$this, 'prepareShutdown']);
$this->bindProcessMessage($this->controller);
$this->controller->on('close', [$this, 'shutdown']);
// port is the slave identifier
$port = $this->config['port'];
$socketPath = $this->getSlaveSocketPath($port, true);
$this->server = new UnixServer($socketPath, $this->loop);
$httpServer = new HttpServer([$this, 'onRequest']);
$httpServer->listen($this->server);
$this->sendMessage($this->controller, 'register', ['pid' => getmypid(), 'port' => $port]);
}
);
} | [
"private",
"function",
"doConnect",
"(",
")",
"{",
"$",
"connector",
"=",
"new",
"UnixConnector",
"(",
"$",
"this",
"->",
"loop",
")",
";",
"$",
"unixSocket",
"=",
"$",
"this",
"->",
"getControllerSocketPath",
"(",
"false",
")",
";",
"$",
"connector",
"->",
"connect",
"(",
"$",
"unixSocket",
")",
"->",
"done",
"(",
"function",
"(",
"$",
"controller",
")",
"{",
"$",
"this",
"->",
"controller",
"=",
"$",
"controller",
";",
"$",
"this",
"->",
"loop",
"->",
"addSignal",
"(",
"SIGTERM",
",",
"[",
"$",
"this",
",",
"'shutdown'",
"]",
")",
";",
"$",
"this",
"->",
"loop",
"->",
"addSignal",
"(",
"SIGINT",
",",
"[",
"$",
"this",
",",
"'shutdown'",
"]",
")",
";",
"register_shutdown_function",
"(",
"[",
"$",
"this",
",",
"'prepareShutdown'",
"]",
")",
";",
"$",
"this",
"->",
"bindProcessMessage",
"(",
"$",
"this",
"->",
"controller",
")",
";",
"$",
"this",
"->",
"controller",
"->",
"on",
"(",
"'close'",
",",
"[",
"$",
"this",
",",
"'shutdown'",
"]",
")",
";",
"// port is the slave identifier",
"$",
"port",
"=",
"$",
"this",
"->",
"config",
"[",
"'port'",
"]",
";",
"$",
"socketPath",
"=",
"$",
"this",
"->",
"getSlaveSocketPath",
"(",
"$",
"port",
",",
"true",
")",
";",
"$",
"this",
"->",
"server",
"=",
"new",
"UnixServer",
"(",
"$",
"socketPath",
",",
"$",
"this",
"->",
"loop",
")",
";",
"$",
"httpServer",
"=",
"new",
"HttpServer",
"(",
"[",
"$",
"this",
",",
"'onRequest'",
"]",
")",
";",
"$",
"httpServer",
"->",
"listen",
"(",
"$",
"this",
"->",
"server",
")",
";",
"$",
"this",
"->",
"sendMessage",
"(",
"$",
"this",
"->",
"controller",
",",
"'register'",
",",
"[",
"'pid'",
"=>",
"getmypid",
"(",
")",
",",
"'port'",
"=>",
"$",
"port",
"]",
")",
";",
"}",
")",
";",
"}"
]
| Attempt a connection to the unix socket.
@throws \RuntimeException | [
"Attempt",
"a",
"connection",
"to",
"the",
"unix",
"socket",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessSlave.php#L300-L327 | train |
php-pm/php-pm | src/ProcessSlave.php | ProcessSlave.run | public function run()
{
$this->loop = Factory::create();
$this->errorLogger = BufferingLogger::create();
ErrorHandler::register(new ErrorHandler($this->errorLogger));
$this->tryConnect();
$this->loop->run();
} | php | public function run()
{
$this->loop = Factory::create();
$this->errorLogger = BufferingLogger::create();
ErrorHandler::register(new ErrorHandler($this->errorLogger));
$this->tryConnect();
$this->loop->run();
} | [
"public",
"function",
"run",
"(",
")",
"{",
"$",
"this",
"->",
"loop",
"=",
"Factory",
"::",
"create",
"(",
")",
";",
"$",
"this",
"->",
"errorLogger",
"=",
"BufferingLogger",
"::",
"create",
"(",
")",
";",
"ErrorHandler",
"::",
"register",
"(",
"new",
"ErrorHandler",
"(",
"$",
"this",
"->",
"errorLogger",
")",
")",
";",
"$",
"this",
"->",
"tryConnect",
"(",
")",
";",
"$",
"this",
"->",
"loop",
"->",
"run",
"(",
")",
";",
"}"
]
| Connects to ProcessManager, master process. | [
"Connects",
"to",
"ProcessManager",
"master",
"process",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessSlave.php#L348-L357 | train |
php-pm/php-pm | src/ProcessSlave.php | ProcessSlave.handleRequest | protected function handleRequest(ServerRequestInterface $request)
{
if ($this->getStaticDirectory()) {
$staticResponse = $this->serveStatic($request);
if ($staticResponse instanceof ResponseInterface) {
return $staticResponse;
}
}
if ($bridge = $this->getBridge()) {
try {
$response = $bridge->handle($request);
} catch (\Throwable $t) {
error_log(
'An exception was thrown by the bridge. Forcing restart of the worker. The exception was: ' .
(string)$t
);
$response = new Response(500, [], 'Unexpected error');
@ob_end_clean();
$this->shutdown();
}
$this->sendCurrentFiles();
} else {
$response = new Response(404, [], 'No Bridge defined');
}
if (headers_sent()) {
//when a script sent headers the cgi process needs to die because the second request
//trying to send headers again will fail (headers already sent fatal). Its best to not even
//try to send headers because this break the whole approach of php-pm using php-cgi.
error_log(
'Headers have been sent, but not redirected to client. Forcing restart of the worker. ' .
'Make sure your application does not send headers on its own.'
);
$this->shutdown();
}
$this->sendMessage($this->controller, 'stats', ['memory_usage' => round(memory_get_peak_usage(true)/1048576, 2)]); // Convert memory usage to MB
return $response;
} | php | protected function handleRequest(ServerRequestInterface $request)
{
if ($this->getStaticDirectory()) {
$staticResponse = $this->serveStatic($request);
if ($staticResponse instanceof ResponseInterface) {
return $staticResponse;
}
}
if ($bridge = $this->getBridge()) {
try {
$response = $bridge->handle($request);
} catch (\Throwable $t) {
error_log(
'An exception was thrown by the bridge. Forcing restart of the worker. The exception was: ' .
(string)$t
);
$response = new Response(500, [], 'Unexpected error');
@ob_end_clean();
$this->shutdown();
}
$this->sendCurrentFiles();
} else {
$response = new Response(404, [], 'No Bridge defined');
}
if (headers_sent()) {
//when a script sent headers the cgi process needs to die because the second request
//trying to send headers again will fail (headers already sent fatal). Its best to not even
//try to send headers because this break the whole approach of php-pm using php-cgi.
error_log(
'Headers have been sent, but not redirected to client. Forcing restart of the worker. ' .
'Make sure your application does not send headers on its own.'
);
$this->shutdown();
}
$this->sendMessage($this->controller, 'stats', ['memory_usage' => round(memory_get_peak_usage(true)/1048576, 2)]); // Convert memory usage to MB
return $response;
} | [
"protected",
"function",
"handleRequest",
"(",
"ServerRequestInterface",
"$",
"request",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getStaticDirectory",
"(",
")",
")",
"{",
"$",
"staticResponse",
"=",
"$",
"this",
"->",
"serveStatic",
"(",
"$",
"request",
")",
";",
"if",
"(",
"$",
"staticResponse",
"instanceof",
"ResponseInterface",
")",
"{",
"return",
"$",
"staticResponse",
";",
"}",
"}",
"if",
"(",
"$",
"bridge",
"=",
"$",
"this",
"->",
"getBridge",
"(",
")",
")",
"{",
"try",
"{",
"$",
"response",
"=",
"$",
"bridge",
"->",
"handle",
"(",
"$",
"request",
")",
";",
"}",
"catch",
"(",
"\\",
"Throwable",
"$",
"t",
")",
"{",
"error_log",
"(",
"'An exception was thrown by the bridge. Forcing restart of the worker. The exception was: '",
".",
"(",
"string",
")",
"$",
"t",
")",
";",
"$",
"response",
"=",
"new",
"Response",
"(",
"500",
",",
"[",
"]",
",",
"'Unexpected error'",
")",
";",
"@",
"ob_end_clean",
"(",
")",
";",
"$",
"this",
"->",
"shutdown",
"(",
")",
";",
"}",
"$",
"this",
"->",
"sendCurrentFiles",
"(",
")",
";",
"}",
"else",
"{",
"$",
"response",
"=",
"new",
"Response",
"(",
"404",
",",
"[",
"]",
",",
"'No Bridge defined'",
")",
";",
"}",
"if",
"(",
"headers_sent",
"(",
")",
")",
"{",
"//when a script sent headers the cgi process needs to die because the second request",
"//trying to send headers again will fail (headers already sent fatal). Its best to not even",
"//try to send headers because this break the whole approach of php-pm using php-cgi.",
"error_log",
"(",
"'Headers have been sent, but not redirected to client. Forcing restart of the worker. '",
".",
"'Make sure your application does not send headers on its own.'",
")",
";",
"$",
"this",
"->",
"shutdown",
"(",
")",
";",
"}",
"$",
"this",
"->",
"sendMessage",
"(",
"$",
"this",
"->",
"controller",
",",
"'stats'",
",",
"[",
"'memory_usage'",
"=>",
"round",
"(",
"memory_get_peak_usage",
"(",
"true",
")",
"/",
"1048576",
",",
"2",
")",
"]",
")",
";",
"// Convert memory usage to MB",
"return",
"$",
"response",
";",
"}"
]
| Handle a redirected request from master.
@param ServerRequestInterface $request
@return ResponseInterface | [
"Handle",
"a",
"redirected",
"request",
"from",
"master",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessSlave.php#L422-L461 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.shutdown | public function shutdown($graceful = true)
{
if ($this->status === self::STATE_SHUTDOWN) {
return;
}
$this->output->writeln("<info>Server is shutting down.</info>");
$this->status = self::STATE_SHUTDOWN;
$remainingSlaves = count($this->slaves->getByStatus(Slave::READY));
if ($remainingSlaves === 0) {
// if for some reason there are no workers, the close callback won't do anything, so just quit.
$this->quit();
} else {
$this->closeSlaves($graceful, function ($slave) use (&$remainingSlaves) {
$this->terminateSlave($slave);
$remainingSlaves--;
if ($this->output->isVeryVerbose()) {
$this->output->writeln(
sprintf(
'Worker #%d terminated, %d more worker(s) to close.',
$slave->getPort(),
$remainingSlaves
)
);
}
if ($remainingSlaves === 0) {
$this->quit();
}
});
}
} | php | public function shutdown($graceful = true)
{
if ($this->status === self::STATE_SHUTDOWN) {
return;
}
$this->output->writeln("<info>Server is shutting down.</info>");
$this->status = self::STATE_SHUTDOWN;
$remainingSlaves = count($this->slaves->getByStatus(Slave::READY));
if ($remainingSlaves === 0) {
// if for some reason there are no workers, the close callback won't do anything, so just quit.
$this->quit();
} else {
$this->closeSlaves($graceful, function ($slave) use (&$remainingSlaves) {
$this->terminateSlave($slave);
$remainingSlaves--;
if ($this->output->isVeryVerbose()) {
$this->output->writeln(
sprintf(
'Worker #%d terminated, %d more worker(s) to close.',
$slave->getPort(),
$remainingSlaves
)
);
}
if ($remainingSlaves === 0) {
$this->quit();
}
});
}
} | [
"public",
"function",
"shutdown",
"(",
"$",
"graceful",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"status",
"===",
"self",
"::",
"STATE_SHUTDOWN",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"\"<info>Server is shutting down.</info>\"",
")",
";",
"$",
"this",
"->",
"status",
"=",
"self",
"::",
"STATE_SHUTDOWN",
";",
"$",
"remainingSlaves",
"=",
"count",
"(",
"$",
"this",
"->",
"slaves",
"->",
"getByStatus",
"(",
"Slave",
"::",
"READY",
")",
")",
";",
"if",
"(",
"$",
"remainingSlaves",
"===",
"0",
")",
"{",
"// if for some reason there are no workers, the close callback won't do anything, so just quit.",
"$",
"this",
"->",
"quit",
"(",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"closeSlaves",
"(",
"$",
"graceful",
",",
"function",
"(",
"$",
"slave",
")",
"use",
"(",
"&",
"$",
"remainingSlaves",
")",
"{",
"$",
"this",
"->",
"terminateSlave",
"(",
"$",
"slave",
")",
";",
"$",
"remainingSlaves",
"--",
";",
"if",
"(",
"$",
"this",
"->",
"output",
"->",
"isVeryVerbose",
"(",
")",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'Worker #%d terminated, %d more worker(s) to close.'",
",",
"$",
"slave",
"->",
"getPort",
"(",
")",
",",
"$",
"remainingSlaves",
")",
")",
";",
"}",
"if",
"(",
"$",
"remainingSlaves",
"===",
"0",
")",
"{",
"$",
"this",
"->",
"quit",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
]
| Handles termination signals, so we can gracefully stop all servers.
@param bool $graceful If true, will wait for busy workers to finish. | [
"Handles",
"termination",
"signals",
"so",
"we",
"can",
"gracefully",
"stop",
"all",
"servers",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L250-L284 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.quit | private function quit()
{
$this->output->writeln('Stopping the process manager.');
// this method is also called during startup when something crashed, so
// make sure we don't operate on nulls.
if ($this->controller) {
@$this->controller->close();
}
if ($this->web) {
@$this->web->close();
}
if ($this->loop) {
$this->loop->stop();
}
unlink($this->pidfile);
exit;
} | php | private function quit()
{
$this->output->writeln('Stopping the process manager.');
// this method is also called during startup when something crashed, so
// make sure we don't operate on nulls.
if ($this->controller) {
@$this->controller->close();
}
if ($this->web) {
@$this->web->close();
}
if ($this->loop) {
$this->loop->stop();
}
unlink($this->pidfile);
exit;
} | [
"private",
"function",
"quit",
"(",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"'Stopping the process manager.'",
")",
";",
"// this method is also called during startup when something crashed, so",
"// make sure we don't operate on nulls.",
"if",
"(",
"$",
"this",
"->",
"controller",
")",
"{",
"@",
"$",
"this",
"->",
"controller",
"->",
"close",
"(",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"web",
")",
"{",
"@",
"$",
"this",
"->",
"web",
"->",
"close",
"(",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"loop",
")",
"{",
"$",
"this",
"->",
"loop",
"->",
"stop",
"(",
")",
";",
"}",
"unlink",
"(",
"$",
"this",
"->",
"pidfile",
")",
";",
"exit",
";",
"}"
]
| To be called after all workers have been terminated and the event loop is no longer in use. | [
"To",
"be",
"called",
"after",
"all",
"workers",
"have",
"been",
"terminated",
"and",
"the",
"event",
"loop",
"is",
"no",
"longer",
"in",
"use",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L289-L308 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.run | public function run()
{
Debug::enable();
// make whatever is necessary to disable all stuff that could buffer output
ini_set('zlib.output_compression', 0);
ini_set('output_buffering', 0);
ini_set('implicit_flush', 1);
ob_implicit_flush(1);
$this->loop = Factory::create();
$this->controller = new UnixServer($this->getControllerSocketPath(), $this->loop);
$this->controller->on('connection', [$this, 'onSlaveConnection']);
$this->web = new Server(sprintf('%s:%d', $this->host, $this->port), $this->loop);
$this->web->on('connection', [$this, 'onRequest']);
$this->loop->addSignal(SIGTERM, [$this, 'shutdown']);
$this->loop->addSignal(SIGINT, [$this, 'shutdown']);
$this->loop->addSignal(SIGCHLD, [$this, 'handleSigchld']);
$this->loop->addSignal(SIGUSR1, [$this, 'restartSlaves']);
$this->loop->addSignal(SIGUSR2, [$this, 'reloadSlaves']);
if ($this->isDebug()) {
$this->loop->addPeriodicTimer(0.5, function () {
$this->checkChangedFiles();
});
}
$loopClass = (new \ReflectionClass($this->loop))->getShortName();
$this->output->writeln("<info>Starting PHP-PM with {$this->slaveCount} workers, using {$loopClass} ...</info>");
$this->writePid();
$this->createSlaves();
$this->loop->run();
} | php | public function run()
{
Debug::enable();
// make whatever is necessary to disable all stuff that could buffer output
ini_set('zlib.output_compression', 0);
ini_set('output_buffering', 0);
ini_set('implicit_flush', 1);
ob_implicit_flush(1);
$this->loop = Factory::create();
$this->controller = new UnixServer($this->getControllerSocketPath(), $this->loop);
$this->controller->on('connection', [$this, 'onSlaveConnection']);
$this->web = new Server(sprintf('%s:%d', $this->host, $this->port), $this->loop);
$this->web->on('connection', [$this, 'onRequest']);
$this->loop->addSignal(SIGTERM, [$this, 'shutdown']);
$this->loop->addSignal(SIGINT, [$this, 'shutdown']);
$this->loop->addSignal(SIGCHLD, [$this, 'handleSigchld']);
$this->loop->addSignal(SIGUSR1, [$this, 'restartSlaves']);
$this->loop->addSignal(SIGUSR2, [$this, 'reloadSlaves']);
if ($this->isDebug()) {
$this->loop->addPeriodicTimer(0.5, function () {
$this->checkChangedFiles();
});
}
$loopClass = (new \ReflectionClass($this->loop))->getShortName();
$this->output->writeln("<info>Starting PHP-PM with {$this->slaveCount} workers, using {$loopClass} ...</info>");
$this->writePid();
$this->createSlaves();
$this->loop->run();
} | [
"public",
"function",
"run",
"(",
")",
"{",
"Debug",
"::",
"enable",
"(",
")",
";",
"// make whatever is necessary to disable all stuff that could buffer output",
"ini_set",
"(",
"'zlib.output_compression'",
",",
"0",
")",
";",
"ini_set",
"(",
"'output_buffering'",
",",
"0",
")",
";",
"ini_set",
"(",
"'implicit_flush'",
",",
"1",
")",
";",
"ob_implicit_flush",
"(",
"1",
")",
";",
"$",
"this",
"->",
"loop",
"=",
"Factory",
"::",
"create",
"(",
")",
";",
"$",
"this",
"->",
"controller",
"=",
"new",
"UnixServer",
"(",
"$",
"this",
"->",
"getControllerSocketPath",
"(",
")",
",",
"$",
"this",
"->",
"loop",
")",
";",
"$",
"this",
"->",
"controller",
"->",
"on",
"(",
"'connection'",
",",
"[",
"$",
"this",
",",
"'onSlaveConnection'",
"]",
")",
";",
"$",
"this",
"->",
"web",
"=",
"new",
"Server",
"(",
"sprintf",
"(",
"'%s:%d'",
",",
"$",
"this",
"->",
"host",
",",
"$",
"this",
"->",
"port",
")",
",",
"$",
"this",
"->",
"loop",
")",
";",
"$",
"this",
"->",
"web",
"->",
"on",
"(",
"'connection'",
",",
"[",
"$",
"this",
",",
"'onRequest'",
"]",
")",
";",
"$",
"this",
"->",
"loop",
"->",
"addSignal",
"(",
"SIGTERM",
",",
"[",
"$",
"this",
",",
"'shutdown'",
"]",
")",
";",
"$",
"this",
"->",
"loop",
"->",
"addSignal",
"(",
"SIGINT",
",",
"[",
"$",
"this",
",",
"'shutdown'",
"]",
")",
";",
"$",
"this",
"->",
"loop",
"->",
"addSignal",
"(",
"SIGCHLD",
",",
"[",
"$",
"this",
",",
"'handleSigchld'",
"]",
")",
";",
"$",
"this",
"->",
"loop",
"->",
"addSignal",
"(",
"SIGUSR1",
",",
"[",
"$",
"this",
",",
"'restartSlaves'",
"]",
")",
";",
"$",
"this",
"->",
"loop",
"->",
"addSignal",
"(",
"SIGUSR2",
",",
"[",
"$",
"this",
",",
"'reloadSlaves'",
"]",
")",
";",
"if",
"(",
"$",
"this",
"->",
"isDebug",
"(",
")",
")",
"{",
"$",
"this",
"->",
"loop",
"->",
"addPeriodicTimer",
"(",
"0.5",
",",
"function",
"(",
")",
"{",
"$",
"this",
"->",
"checkChangedFiles",
"(",
")",
";",
"}",
")",
";",
"}",
"$",
"loopClass",
"=",
"(",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"this",
"->",
"loop",
")",
")",
"->",
"getShortName",
"(",
")",
";",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"\"<info>Starting PHP-PM with {$this->slaveCount} workers, using {$loopClass} ...</info>\"",
")",
";",
"$",
"this",
"->",
"writePid",
"(",
")",
";",
"$",
"this",
"->",
"createSlaves",
"(",
")",
";",
"$",
"this",
"->",
"loop",
"->",
"run",
"(",
")",
";",
"}"
]
| Starts the main loop. Blocks. | [
"Starts",
"the",
"main",
"loop",
".",
"Blocks",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L485-L522 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.onSlaveConnection | public function onSlaveConnection(ConnectionInterface $connection)
{
$this->bindProcessMessage($connection);
$connection->on('close', function () use ($connection) {
$this->onSlaveClosed($connection);
});
} | php | public function onSlaveConnection(ConnectionInterface $connection)
{
$this->bindProcessMessage($connection);
$connection->on('close', function () use ($connection) {
$this->onSlaveClosed($connection);
});
} | [
"public",
"function",
"onSlaveConnection",
"(",
"ConnectionInterface",
"$",
"connection",
")",
"{",
"$",
"this",
"->",
"bindProcessMessage",
"(",
"$",
"connection",
")",
";",
"$",
"connection",
"->",
"on",
"(",
"'close'",
",",
"function",
"(",
")",
"use",
"(",
"$",
"connection",
")",
"{",
"$",
"this",
"->",
"onSlaveClosed",
"(",
"$",
"connection",
")",
";",
"}",
")",
";",
"}"
]
| Handles data communication from slave -> master
@param ConnectionInterface $connection | [
"Handles",
"data",
"communication",
"from",
"slave",
"-",
">",
"master"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L556-L562 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.onSlaveClosed | public function onSlaveClosed(ConnectionInterface $connection)
{
if ($this->status === self::STATE_SHUTDOWN) {
return;
}
try {
$slave = $this->slaves->getByConnection($connection);
} catch (\Exception $e) {
// this connection is not registered, so it died during the ProcessSlave constructor.
$this->output->writeln(
'<error>Worker permanently closed during PHP-PM bootstrap. Not so cool. ' .
'Not your fault, please create a ticket at github.com/php-pm/php-pm with ' .
'the output of `ppm start -vv`.</error>'
);
return;
}
// remove slave from reload killer pool
unset($this->slavesToReload[$slave->getPort()]);
// get status before terminating
$status = $slave->getStatus();
$port = $slave->getPort();
if ($this->output->isVeryVerbose()) {
$this->output->writeln(sprintf('Worker #%d closed after %d handled requests', $port, $slave->getHandledRequests()));
}
// kill slave and remove from pool
$this->terminateSlave($slave);
/*
* If slave is in registered state it died during bootstrap.
* In this case new instances should only be created:
* - in debug mode after file change detection via restartSlaves()
* - in production mode immediately
*/
if ($status === Slave::REGISTERED) {
$this->bootstrapFailed($port);
} else {
// recreate
$this->newSlaveInstance($port);
}
} | php | public function onSlaveClosed(ConnectionInterface $connection)
{
if ($this->status === self::STATE_SHUTDOWN) {
return;
}
try {
$slave = $this->slaves->getByConnection($connection);
} catch (\Exception $e) {
// this connection is not registered, so it died during the ProcessSlave constructor.
$this->output->writeln(
'<error>Worker permanently closed during PHP-PM bootstrap. Not so cool. ' .
'Not your fault, please create a ticket at github.com/php-pm/php-pm with ' .
'the output of `ppm start -vv`.</error>'
);
return;
}
// remove slave from reload killer pool
unset($this->slavesToReload[$slave->getPort()]);
// get status before terminating
$status = $slave->getStatus();
$port = $slave->getPort();
if ($this->output->isVeryVerbose()) {
$this->output->writeln(sprintf('Worker #%d closed after %d handled requests', $port, $slave->getHandledRequests()));
}
// kill slave and remove from pool
$this->terminateSlave($slave);
/*
* If slave is in registered state it died during bootstrap.
* In this case new instances should only be created:
* - in debug mode after file change detection via restartSlaves()
* - in production mode immediately
*/
if ($status === Slave::REGISTERED) {
$this->bootstrapFailed($port);
} else {
// recreate
$this->newSlaveInstance($port);
}
} | [
"public",
"function",
"onSlaveClosed",
"(",
"ConnectionInterface",
"$",
"connection",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"status",
"===",
"self",
"::",
"STATE_SHUTDOWN",
")",
"{",
"return",
";",
"}",
"try",
"{",
"$",
"slave",
"=",
"$",
"this",
"->",
"slaves",
"->",
"getByConnection",
"(",
"$",
"connection",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"// this connection is not registered, so it died during the ProcessSlave constructor.",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"'<error>Worker permanently closed during PHP-PM bootstrap. Not so cool. '",
".",
"'Not your fault, please create a ticket at github.com/php-pm/php-pm with '",
".",
"'the output of `ppm start -vv`.</error>'",
")",
";",
"return",
";",
"}",
"// remove slave from reload killer pool",
"unset",
"(",
"$",
"this",
"->",
"slavesToReload",
"[",
"$",
"slave",
"->",
"getPort",
"(",
")",
"]",
")",
";",
"// get status before terminating",
"$",
"status",
"=",
"$",
"slave",
"->",
"getStatus",
"(",
")",
";",
"$",
"port",
"=",
"$",
"slave",
"->",
"getPort",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"output",
"->",
"isVeryVerbose",
"(",
")",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'Worker #%d closed after %d handled requests'",
",",
"$",
"port",
",",
"$",
"slave",
"->",
"getHandledRequests",
"(",
")",
")",
")",
";",
"}",
"// kill slave and remove from pool",
"$",
"this",
"->",
"terminateSlave",
"(",
"$",
"slave",
")",
";",
"/*\n * If slave is in registered state it died during bootstrap.\n * In this case new instances should only be created:\n * - in debug mode after file change detection via restartSlaves()\n * - in production mode immediately\n */",
"if",
"(",
"$",
"status",
"===",
"Slave",
"::",
"REGISTERED",
")",
"{",
"$",
"this",
"->",
"bootstrapFailed",
"(",
"$",
"port",
")",
";",
"}",
"else",
"{",
"// recreate",
"$",
"this",
"->",
"newSlaveInstance",
"(",
"$",
"port",
")",
";",
"}",
"}"
]
| Handle slave closed
@param ConnectionInterface $connection
@return void | [
"Handle",
"slave",
"closed"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L570-L615 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.commandStatus | protected function commandStatus(array $data, ConnectionInterface $conn)
{
// remove nasty info about worker's bootstrap fail
$conn->removeAllListeners('close');
if ($this->output->isVeryVerbose()) {
$conn->on('close', function () {
$this->output->writeln('Status command requested');
});
}
// create port -> requests map
$requests = array_reduce(
$this->slaves->getByStatus(Slave::ANY),
function ($carry, Slave $slave) {
$carry[$slave->getPort()] = 0 + $slave->getHandledRequests();
return $carry;
},
[]
);
switch ($this->status) {
case self::STATE_STARTING:
$status = 'starting';
break;
case self::STATE_RUNNING:
$status = 'healthy';
break;
case self::STATE_EMERGENCY:
$status = 'offline';
break;
default:
$status = 'unknown';
}
$conn->end(json_encode([
'status' => $status,
'workers' => $this->slaves->getStatusSummary(),
'handled_requests' => $this->handledRequests,
'handled_requests_per_worker' => $requests
]));
} | php | protected function commandStatus(array $data, ConnectionInterface $conn)
{
// remove nasty info about worker's bootstrap fail
$conn->removeAllListeners('close');
if ($this->output->isVeryVerbose()) {
$conn->on('close', function () {
$this->output->writeln('Status command requested');
});
}
// create port -> requests map
$requests = array_reduce(
$this->slaves->getByStatus(Slave::ANY),
function ($carry, Slave $slave) {
$carry[$slave->getPort()] = 0 + $slave->getHandledRequests();
return $carry;
},
[]
);
switch ($this->status) {
case self::STATE_STARTING:
$status = 'starting';
break;
case self::STATE_RUNNING:
$status = 'healthy';
break;
case self::STATE_EMERGENCY:
$status = 'offline';
break;
default:
$status = 'unknown';
}
$conn->end(json_encode([
'status' => $status,
'workers' => $this->slaves->getStatusSummary(),
'handled_requests' => $this->handledRequests,
'handled_requests_per_worker' => $requests
]));
} | [
"protected",
"function",
"commandStatus",
"(",
"array",
"$",
"data",
",",
"ConnectionInterface",
"$",
"conn",
")",
"{",
"// remove nasty info about worker's bootstrap fail",
"$",
"conn",
"->",
"removeAllListeners",
"(",
"'close'",
")",
";",
"if",
"(",
"$",
"this",
"->",
"output",
"->",
"isVeryVerbose",
"(",
")",
")",
"{",
"$",
"conn",
"->",
"on",
"(",
"'close'",
",",
"function",
"(",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"'Status command requested'",
")",
";",
"}",
")",
";",
"}",
"// create port -> requests map",
"$",
"requests",
"=",
"array_reduce",
"(",
"$",
"this",
"->",
"slaves",
"->",
"getByStatus",
"(",
"Slave",
"::",
"ANY",
")",
",",
"function",
"(",
"$",
"carry",
",",
"Slave",
"$",
"slave",
")",
"{",
"$",
"carry",
"[",
"$",
"slave",
"->",
"getPort",
"(",
")",
"]",
"=",
"0",
"+",
"$",
"slave",
"->",
"getHandledRequests",
"(",
")",
";",
"return",
"$",
"carry",
";",
"}",
",",
"[",
"]",
")",
";",
"switch",
"(",
"$",
"this",
"->",
"status",
")",
"{",
"case",
"self",
"::",
"STATE_STARTING",
":",
"$",
"status",
"=",
"'starting'",
";",
"break",
";",
"case",
"self",
"::",
"STATE_RUNNING",
":",
"$",
"status",
"=",
"'healthy'",
";",
"break",
";",
"case",
"self",
"::",
"STATE_EMERGENCY",
":",
"$",
"status",
"=",
"'offline'",
";",
"break",
";",
"default",
":",
"$",
"status",
"=",
"'unknown'",
";",
"}",
"$",
"conn",
"->",
"end",
"(",
"json_encode",
"(",
"[",
"'status'",
"=>",
"$",
"status",
",",
"'workers'",
"=>",
"$",
"this",
"->",
"slaves",
"->",
"getStatusSummary",
"(",
")",
",",
"'handled_requests'",
"=>",
"$",
"this",
"->",
"handledRequests",
",",
"'handled_requests_per_worker'",
"=>",
"$",
"requests",
"]",
")",
")",
";",
"}"
]
| A slave sent a `status` command.
@param array $data
@param ConnectionInterface $conn | [
"A",
"slave",
"sent",
"a",
"status",
"command",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L623-L663 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.commandStop | protected function commandStop(array $data, ConnectionInterface $conn)
{
if ($this->output->isVeryVerbose()) {
$conn->on('close', function () {
$this->output->writeln('Stop command requested');
});
}
$conn->end(json_encode([]));
$this->shutdown();
} | php | protected function commandStop(array $data, ConnectionInterface $conn)
{
if ($this->output->isVeryVerbose()) {
$conn->on('close', function () {
$this->output->writeln('Stop command requested');
});
}
$conn->end(json_encode([]));
$this->shutdown();
} | [
"protected",
"function",
"commandStop",
"(",
"array",
"$",
"data",
",",
"ConnectionInterface",
"$",
"conn",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"output",
"->",
"isVeryVerbose",
"(",
")",
")",
"{",
"$",
"conn",
"->",
"on",
"(",
"'close'",
",",
"function",
"(",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"'Stop command requested'",
")",
";",
"}",
")",
";",
"}",
"$",
"conn",
"->",
"end",
"(",
"json_encode",
"(",
"[",
"]",
")",
")",
";",
"$",
"this",
"->",
"shutdown",
"(",
")",
";",
"}"
]
| A slave sent a `stop` command.
@param array $data
@param ConnectionInterface $conn | [
"A",
"slave",
"sent",
"a",
"stop",
"command",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L671-L682 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.commandReload | protected function commandReload(array $data, ConnectionInterface $conn)
{
// remove nasty info about worker's bootstrap fail
$conn->removeAllListeners('close');
if ($this->output->isVeryVerbose()) {
$conn->on('close', function () {
$this->output->writeln('Reload command requested');
});
}
$conn->end(json_encode([]));
$this->reloadSlaves();
} | php | protected function commandReload(array $data, ConnectionInterface $conn)
{
// remove nasty info about worker's bootstrap fail
$conn->removeAllListeners('close');
if ($this->output->isVeryVerbose()) {
$conn->on('close', function () {
$this->output->writeln('Reload command requested');
});
}
$conn->end(json_encode([]));
$this->reloadSlaves();
} | [
"protected",
"function",
"commandReload",
"(",
"array",
"$",
"data",
",",
"ConnectionInterface",
"$",
"conn",
")",
"{",
"// remove nasty info about worker's bootstrap fail",
"$",
"conn",
"->",
"removeAllListeners",
"(",
"'close'",
")",
";",
"if",
"(",
"$",
"this",
"->",
"output",
"->",
"isVeryVerbose",
"(",
")",
")",
"{",
"$",
"conn",
"->",
"on",
"(",
"'close'",
",",
"function",
"(",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"'Reload command requested'",
")",
";",
"}",
")",
";",
"}",
"$",
"conn",
"->",
"end",
"(",
"json_encode",
"(",
"[",
"]",
")",
")",
";",
"$",
"this",
"->",
"reloadSlaves",
"(",
")",
";",
"}"
]
| A slave sent a `reload` command.
@param array $data
@param ConnectionInterface $conn | [
"A",
"slave",
"sent",
"a",
"reload",
"command",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L690-L704 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.commandRegister | protected function commandRegister(array $data, ConnectionInterface $conn)
{
$pid = (int)$data['pid'];
$port = (int)$data['port'];
try {
$slave = $this->slaves->getByPort($port);
$slave->register($pid, $conn);
} catch (\Exception $e) {
$this->output->writeln(sprintf(
'<error>Worker #%d wanted to register on master which was not expected.</error>',
$port
));
$conn->close();
return;
}
if ($this->output->isVeryVerbose()) {
$this->output->writeln(sprintf('Worker #%d registered. Waiting for application bootstrap ... ', $port));
}
$this->sendMessage($conn, 'bootstrap');
} | php | protected function commandRegister(array $data, ConnectionInterface $conn)
{
$pid = (int)$data['pid'];
$port = (int)$data['port'];
try {
$slave = $this->slaves->getByPort($port);
$slave->register($pid, $conn);
} catch (\Exception $e) {
$this->output->writeln(sprintf(
'<error>Worker #%d wanted to register on master which was not expected.</error>',
$port
));
$conn->close();
return;
}
if ($this->output->isVeryVerbose()) {
$this->output->writeln(sprintf('Worker #%d registered. Waiting for application bootstrap ... ', $port));
}
$this->sendMessage($conn, 'bootstrap');
} | [
"protected",
"function",
"commandRegister",
"(",
"array",
"$",
"data",
",",
"ConnectionInterface",
"$",
"conn",
")",
"{",
"$",
"pid",
"=",
"(",
"int",
")",
"$",
"data",
"[",
"'pid'",
"]",
";",
"$",
"port",
"=",
"(",
"int",
")",
"$",
"data",
"[",
"'port'",
"]",
";",
"try",
"{",
"$",
"slave",
"=",
"$",
"this",
"->",
"slaves",
"->",
"getByPort",
"(",
"$",
"port",
")",
";",
"$",
"slave",
"->",
"register",
"(",
"$",
"pid",
",",
"$",
"conn",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'<error>Worker #%d wanted to register on master which was not expected.</error>'",
",",
"$",
"port",
")",
")",
";",
"$",
"conn",
"->",
"close",
"(",
")",
";",
"return",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"output",
"->",
"isVeryVerbose",
"(",
")",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'Worker #%d registered. Waiting for application bootstrap ... '",
",",
"$",
"port",
")",
")",
";",
"}",
"$",
"this",
"->",
"sendMessage",
"(",
"$",
"conn",
",",
"'bootstrap'",
")",
";",
"}"
]
| A slave sent a `register` command.
@param array $data
@param ConnectionInterface $conn | [
"A",
"slave",
"sent",
"a",
"register",
"command",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L712-L734 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.commandReady | protected function commandReady(array $data, ConnectionInterface $conn)
{
try {
$slave = $this->slaves->getByConnection($conn);
} catch (\Exception $e) {
$this->output->writeln(
'<error>A ready command was sent by a worker with no connection. This was unexpected. ' .
'Not your fault, please create a ticket at github.com/php-pm/php-pm with ' .
'the output of `ppm start -vv`.</error>'
);
return;
}
$slave->ready();
if ($this->output->isVeryVerbose()) {
$this->output->writeln(sprintf('Worker #%d ready.', $slave->getPort()));
}
if ($this->allSlavesReady()) {
if ($this->status === self::STATE_EMERGENCY) {
$this->output->writeln("<info>Emergency survived. Workers up and running again.</info>");
} else {
$this->output->writeln(
sprintf(
"<info>%d workers (starting at %d) up and ready. Application is ready at http://%s:%s/</info>",
$this->slaveCount,
self::CONTROLLER_PORT+1,
$this->host,
$this->port
)
);
}
$this->status = self::STATE_RUNNING;
}
} | php | protected function commandReady(array $data, ConnectionInterface $conn)
{
try {
$slave = $this->slaves->getByConnection($conn);
} catch (\Exception $e) {
$this->output->writeln(
'<error>A ready command was sent by a worker with no connection. This was unexpected. ' .
'Not your fault, please create a ticket at github.com/php-pm/php-pm with ' .
'the output of `ppm start -vv`.</error>'
);
return;
}
$slave->ready();
if ($this->output->isVeryVerbose()) {
$this->output->writeln(sprintf('Worker #%d ready.', $slave->getPort()));
}
if ($this->allSlavesReady()) {
if ($this->status === self::STATE_EMERGENCY) {
$this->output->writeln("<info>Emergency survived. Workers up and running again.</info>");
} else {
$this->output->writeln(
sprintf(
"<info>%d workers (starting at %d) up and ready. Application is ready at http://%s:%s/</info>",
$this->slaveCount,
self::CONTROLLER_PORT+1,
$this->host,
$this->port
)
);
}
$this->status = self::STATE_RUNNING;
}
} | [
"protected",
"function",
"commandReady",
"(",
"array",
"$",
"data",
",",
"ConnectionInterface",
"$",
"conn",
")",
"{",
"try",
"{",
"$",
"slave",
"=",
"$",
"this",
"->",
"slaves",
"->",
"getByConnection",
"(",
"$",
"conn",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"'<error>A ready command was sent by a worker with no connection. This was unexpected. '",
".",
"'Not your fault, please create a ticket at github.com/php-pm/php-pm with '",
".",
"'the output of `ppm start -vv`.</error>'",
")",
";",
"return",
";",
"}",
"$",
"slave",
"->",
"ready",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"output",
"->",
"isVeryVerbose",
"(",
")",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'Worker #%d ready.'",
",",
"$",
"slave",
"->",
"getPort",
"(",
")",
")",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"allSlavesReady",
"(",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"status",
"===",
"self",
"::",
"STATE_EMERGENCY",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"\"<info>Emergency survived. Workers up and running again.</info>\"",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"\"<info>%d workers (starting at %d) up and ready. Application is ready at http://%s:%s/</info>\"",
",",
"$",
"this",
"->",
"slaveCount",
",",
"self",
"::",
"CONTROLLER_PORT",
"+",
"1",
",",
"$",
"this",
"->",
"host",
",",
"$",
"this",
"->",
"port",
")",
")",
";",
"}",
"$",
"this",
"->",
"status",
"=",
"self",
"::",
"STATE_RUNNING",
";",
"}",
"}"
]
| A slave sent a `ready` commands which basically says that the slave bootstrapped successfully the
application and is ready to accept connections.
@param array $data
@param ConnectionInterface $conn | [
"A",
"slave",
"sent",
"a",
"ready",
"commands",
"which",
"basically",
"says",
"that",
"the",
"slave",
"bootstrapped",
"successfully",
"the",
"application",
"and",
"is",
"ready",
"to",
"accept",
"connections",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L743-L779 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.commandFiles | protected function commandFiles(array $data, ConnectionInterface $conn)
{
try {
$slave = $this->slaves->getByConnection($conn);
$start = microtime(true);
clearstatcache();
$newFilesCount = 0;
$knownFiles = array_keys($this->filesLastMTime);
$recentlyIncludedFiles = array_diff($data['files'], $knownFiles);
foreach ($recentlyIncludedFiles as $filePath) {
if (file_exists($filePath)) {
$this->filesLastMTime[$filePath] = filemtime($filePath);
$this->filesLastMd5[$filePath] = md5_file($filePath, true);
$newFilesCount++;
}
}
if ($this->output->isVeryVerbose()) {
$this->output->writeln(
sprintf(
'Received %d new files from %d. Stats collection cycle: %u files, %.3f ms',
$newFilesCount,
$slave->getPort(),
count($this->filesLastMTime),
(microtime(true) - $start) * 1000
)
);
}
} catch (\Exception $e) {
// silent
}
} | php | protected function commandFiles(array $data, ConnectionInterface $conn)
{
try {
$slave = $this->slaves->getByConnection($conn);
$start = microtime(true);
clearstatcache();
$newFilesCount = 0;
$knownFiles = array_keys($this->filesLastMTime);
$recentlyIncludedFiles = array_diff($data['files'], $knownFiles);
foreach ($recentlyIncludedFiles as $filePath) {
if (file_exists($filePath)) {
$this->filesLastMTime[$filePath] = filemtime($filePath);
$this->filesLastMd5[$filePath] = md5_file($filePath, true);
$newFilesCount++;
}
}
if ($this->output->isVeryVerbose()) {
$this->output->writeln(
sprintf(
'Received %d new files from %d. Stats collection cycle: %u files, %.3f ms',
$newFilesCount,
$slave->getPort(),
count($this->filesLastMTime),
(microtime(true) - $start) * 1000
)
);
}
} catch (\Exception $e) {
// silent
}
} | [
"protected",
"function",
"commandFiles",
"(",
"array",
"$",
"data",
",",
"ConnectionInterface",
"$",
"conn",
")",
"{",
"try",
"{",
"$",
"slave",
"=",
"$",
"this",
"->",
"slaves",
"->",
"getByConnection",
"(",
"$",
"conn",
")",
";",
"$",
"start",
"=",
"microtime",
"(",
"true",
")",
";",
"clearstatcache",
"(",
")",
";",
"$",
"newFilesCount",
"=",
"0",
";",
"$",
"knownFiles",
"=",
"array_keys",
"(",
"$",
"this",
"->",
"filesLastMTime",
")",
";",
"$",
"recentlyIncludedFiles",
"=",
"array_diff",
"(",
"$",
"data",
"[",
"'files'",
"]",
",",
"$",
"knownFiles",
")",
";",
"foreach",
"(",
"$",
"recentlyIncludedFiles",
"as",
"$",
"filePath",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"filePath",
")",
")",
"{",
"$",
"this",
"->",
"filesLastMTime",
"[",
"$",
"filePath",
"]",
"=",
"filemtime",
"(",
"$",
"filePath",
")",
";",
"$",
"this",
"->",
"filesLastMd5",
"[",
"$",
"filePath",
"]",
"=",
"md5_file",
"(",
"$",
"filePath",
",",
"true",
")",
";",
"$",
"newFilesCount",
"++",
";",
"}",
"}",
"if",
"(",
"$",
"this",
"->",
"output",
"->",
"isVeryVerbose",
"(",
")",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'Received %d new files from %d. Stats collection cycle: %u files, %.3f ms'",
",",
"$",
"newFilesCount",
",",
"$",
"slave",
"->",
"getPort",
"(",
")",
",",
"count",
"(",
"$",
"this",
"->",
"filesLastMTime",
")",
",",
"(",
"microtime",
"(",
"true",
")",
"-",
"$",
"start",
")",
"*",
"1000",
")",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"// silent",
"}",
"}"
]
| Register client files for change tracking
@param array $data
@param ConnectionInterface $conn | [
"Register",
"client",
"files",
"for",
"change",
"tracking"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L800-L834 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.commandStats | protected function commandStats(array $data, ConnectionInterface $conn)
{
try {
$slave = $this->slaves->getByConnection($conn);
$slave->setUsedMemory($data['memory_usage']);
if ($this->output->isVeryVerbose()) {
$this->output->writeln(
sprintf(
'Current memory usage for worker %d: %.2f MB',
$slave->getPort(),
$data['memory_usage']
)
);
}
} catch (\Exception $e) {
// silent
}
} | php | protected function commandStats(array $data, ConnectionInterface $conn)
{
try {
$slave = $this->slaves->getByConnection($conn);
$slave->setUsedMemory($data['memory_usage']);
if ($this->output->isVeryVerbose()) {
$this->output->writeln(
sprintf(
'Current memory usage for worker %d: %.2f MB',
$slave->getPort(),
$data['memory_usage']
)
);
}
} catch (\Exception $e) {
// silent
}
} | [
"protected",
"function",
"commandStats",
"(",
"array",
"$",
"data",
",",
"ConnectionInterface",
"$",
"conn",
")",
"{",
"try",
"{",
"$",
"slave",
"=",
"$",
"this",
"->",
"slaves",
"->",
"getByConnection",
"(",
"$",
"conn",
")",
";",
"$",
"slave",
"->",
"setUsedMemory",
"(",
"$",
"data",
"[",
"'memory_usage'",
"]",
")",
";",
"if",
"(",
"$",
"this",
"->",
"output",
"->",
"isVeryVerbose",
"(",
")",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'Current memory usage for worker %d: %.2f MB'",
",",
"$",
"slave",
"->",
"getPort",
"(",
")",
",",
"$",
"data",
"[",
"'memory_usage'",
"]",
")",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"// silent",
"}",
"}"
]
| Receive stats from the worker such as current memory use
@param array $data
@param ConnectionInterface $conn | [
"Receive",
"stats",
"from",
"the",
"worker",
"such",
"as",
"current",
"memory",
"use"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L842-L859 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.bootstrapFailed | protected function bootstrapFailed($port)
{
if ($this->isDebug()) {
$this->output->writeln('');
if ($this->status !== self::STATE_EMERGENCY) {
$this->status = self::STATE_EMERGENCY;
$this->output->writeln(
sprintf(
'<error>Application bootstrap failed. We are entering emergency mode now. All offline. ' .
'Waiting for file changes ...</error>'
)
);
} else {
$this->output->writeln(
sprintf(
'<error>Application bootstrap failed. We are still in emergency mode. All offline. ' .
'Waiting for file changes ...</error>'
)
);
}
$this->reloadSlaves(false);
} else {
$this->output->writeln(
sprintf(
'<error>Application bootstrap failed. Restarting worker #%d ...</error>',
$port
)
);
$this->newSlaveInstance($port);
}
} | php | protected function bootstrapFailed($port)
{
if ($this->isDebug()) {
$this->output->writeln('');
if ($this->status !== self::STATE_EMERGENCY) {
$this->status = self::STATE_EMERGENCY;
$this->output->writeln(
sprintf(
'<error>Application bootstrap failed. We are entering emergency mode now. All offline. ' .
'Waiting for file changes ...</error>'
)
);
} else {
$this->output->writeln(
sprintf(
'<error>Application bootstrap failed. We are still in emergency mode. All offline. ' .
'Waiting for file changes ...</error>'
)
);
}
$this->reloadSlaves(false);
} else {
$this->output->writeln(
sprintf(
'<error>Application bootstrap failed. Restarting worker #%d ...</error>',
$port
)
);
$this->newSlaveInstance($port);
}
} | [
"protected",
"function",
"bootstrapFailed",
"(",
"$",
"port",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isDebug",
"(",
")",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"''",
")",
";",
"if",
"(",
"$",
"this",
"->",
"status",
"!==",
"self",
"::",
"STATE_EMERGENCY",
")",
"{",
"$",
"this",
"->",
"status",
"=",
"self",
"::",
"STATE_EMERGENCY",
";",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'<error>Application bootstrap failed. We are entering emergency mode now. All offline. '",
".",
"'Waiting for file changes ...</error>'",
")",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'<error>Application bootstrap failed. We are still in emergency mode. All offline. '",
".",
"'Waiting for file changes ...</error>'",
")",
")",
";",
"}",
"$",
"this",
"->",
"reloadSlaves",
"(",
"false",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'<error>Application bootstrap failed. Restarting worker #%d ...</error>'",
",",
"$",
"port",
")",
")",
";",
"$",
"this",
"->",
"newSlaveInstance",
"(",
"$",
"port",
")",
";",
"}",
"}"
]
| Handles failed application bootstraps.
@param int $port | [
"Handles",
"failed",
"application",
"bootstraps",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L866-L900 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.checkChangedFiles | protected function checkChangedFiles($restartSlaves = true)
{
if ($this->inChangesDetectionCycle) {
return false;
}
$start = microtime(true);
$hasChanged = false;
$this->inChangesDetectionCycle = true;
clearstatcache();
foreach ($this->filesLastMTime as $filePath => $knownMTime) {
if (!file_exists($filePath)) {
continue;
}
$actualFileTime = filemtime($filePath);
$actualFileHash = md5_file($filePath);
if ($knownMTime !== $actualFileTime && $this->filesLastMd5[$filePath] !== $actualFileHash) {
// update tracked entry metadata
$this->filesLastMd5[$filePath] = $actualFileHash;
$this->filesLastMTime[$filePath] = $actualFileTime;
$this->output->writeln(
sprintf("<info>[%s] File %s has changed.</info>", date('d/M/Y:H:i:s O'), $filePath)
);
$hasChanged = true;
break;
}
}
if ($hasChanged) {
$this->output->writeln(
sprintf(
"<info>[%s] At least one of %u known files was changed. Reloading workers.</info>",
date('d/M/Y:H:i:s O'),
count($this->filesLastMTime)
)
);
if ($this->output->isVeryVerbose()) {
$this->output->writeln(
sprintf("Changes detection cycle length = %.3f ms", (microtime(true) - $start) * 1000)
);
}
if ($restartSlaves) {
$this->restartSlaves();
}
}
$this->inChangesDetectionCycle = false;
return $hasChanged;
} | php | protected function checkChangedFiles($restartSlaves = true)
{
if ($this->inChangesDetectionCycle) {
return false;
}
$start = microtime(true);
$hasChanged = false;
$this->inChangesDetectionCycle = true;
clearstatcache();
foreach ($this->filesLastMTime as $filePath => $knownMTime) {
if (!file_exists($filePath)) {
continue;
}
$actualFileTime = filemtime($filePath);
$actualFileHash = md5_file($filePath);
if ($knownMTime !== $actualFileTime && $this->filesLastMd5[$filePath] !== $actualFileHash) {
// update tracked entry metadata
$this->filesLastMd5[$filePath] = $actualFileHash;
$this->filesLastMTime[$filePath] = $actualFileTime;
$this->output->writeln(
sprintf("<info>[%s] File %s has changed.</info>", date('d/M/Y:H:i:s O'), $filePath)
);
$hasChanged = true;
break;
}
}
if ($hasChanged) {
$this->output->writeln(
sprintf(
"<info>[%s] At least one of %u known files was changed. Reloading workers.</info>",
date('d/M/Y:H:i:s O'),
count($this->filesLastMTime)
)
);
if ($this->output->isVeryVerbose()) {
$this->output->writeln(
sprintf("Changes detection cycle length = %.3f ms", (microtime(true) - $start) * 1000)
);
}
if ($restartSlaves) {
$this->restartSlaves();
}
}
$this->inChangesDetectionCycle = false;
return $hasChanged;
} | [
"protected",
"function",
"checkChangedFiles",
"(",
"$",
"restartSlaves",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"inChangesDetectionCycle",
")",
"{",
"return",
"false",
";",
"}",
"$",
"start",
"=",
"microtime",
"(",
"true",
")",
";",
"$",
"hasChanged",
"=",
"false",
";",
"$",
"this",
"->",
"inChangesDetectionCycle",
"=",
"true",
";",
"clearstatcache",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"filesLastMTime",
"as",
"$",
"filePath",
"=>",
"$",
"knownMTime",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"filePath",
")",
")",
"{",
"continue",
";",
"}",
"$",
"actualFileTime",
"=",
"filemtime",
"(",
"$",
"filePath",
")",
";",
"$",
"actualFileHash",
"=",
"md5_file",
"(",
"$",
"filePath",
")",
";",
"if",
"(",
"$",
"knownMTime",
"!==",
"$",
"actualFileTime",
"&&",
"$",
"this",
"->",
"filesLastMd5",
"[",
"$",
"filePath",
"]",
"!==",
"$",
"actualFileHash",
")",
"{",
"// update tracked entry metadata",
"$",
"this",
"->",
"filesLastMd5",
"[",
"$",
"filePath",
"]",
"=",
"$",
"actualFileHash",
";",
"$",
"this",
"->",
"filesLastMTime",
"[",
"$",
"filePath",
"]",
"=",
"$",
"actualFileTime",
";",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"\"<info>[%s] File %s has changed.</info>\"",
",",
"date",
"(",
"'d/M/Y:H:i:s O'",
")",
",",
"$",
"filePath",
")",
")",
";",
"$",
"hasChanged",
"=",
"true",
";",
"break",
";",
"}",
"}",
"if",
"(",
"$",
"hasChanged",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"\"<info>[%s] At least one of %u known files was changed. Reloading workers.</info>\"",
",",
"date",
"(",
"'d/M/Y:H:i:s O'",
")",
",",
"count",
"(",
"$",
"this",
"->",
"filesLastMTime",
")",
")",
")",
";",
"if",
"(",
"$",
"this",
"->",
"output",
"->",
"isVeryVerbose",
"(",
")",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"\"Changes detection cycle length = %.3f ms\"",
",",
"(",
"microtime",
"(",
"true",
")",
"-",
"$",
"start",
")",
"*",
"1000",
")",
")",
";",
"}",
"if",
"(",
"$",
"restartSlaves",
")",
"{",
"$",
"this",
"->",
"restartSlaves",
"(",
")",
";",
"}",
"}",
"$",
"this",
"->",
"inChangesDetectionCycle",
"=",
"false",
";",
"return",
"$",
"hasChanged",
";",
"}"
]
| Checks if tracked files have changed. If so, restart all slaves.
This approach uses simple filemtime to check against modifications. It is using this technique because
all other file watching stuff have either big dependencies or do not work under all platforms without
installing a pecl extension. Also this way is interestingly fast and is only used when debug=true.
@param bool $restartSlaves
@return bool | [
"Checks",
"if",
"tracked",
"files",
"have",
"changed",
".",
"If",
"so",
"restart",
"all",
"slaves",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L913-L971 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.createSlaves | public function createSlaves()
{
for ($i = 1; $i <= $this->slaveCount; $i++) {
$this->newSlaveInstance(self::CONTROLLER_PORT + $i);
}
} | php | public function createSlaves()
{
for ($i = 1; $i <= $this->slaveCount; $i++) {
$this->newSlaveInstance(self::CONTROLLER_PORT + $i);
}
} | [
"public",
"function",
"createSlaves",
"(",
")",
"{",
"for",
"(",
"$",
"i",
"=",
"1",
";",
"$",
"i",
"<=",
"$",
"this",
"->",
"slaveCount",
";",
"$",
"i",
"++",
")",
"{",
"$",
"this",
"->",
"newSlaveInstance",
"(",
"self",
"::",
"CONTROLLER_PORT",
"+",
"$",
"i",
")",
";",
"}",
"}"
]
| Populate slave pool
@return void | [
"Populate",
"slave",
"pool"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L978-L983 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.closeSlave | protected function closeSlave($slave)
{
$slave->close();
$this->slaves->remove($slave);
if (!empty($slave->getConnection())) {
/** @var ConnectionInterface */
$connection = $slave->getConnection();
$connection->removeAllListeners('close');
$connection->close();
}
} | php | protected function closeSlave($slave)
{
$slave->close();
$this->slaves->remove($slave);
if (!empty($slave->getConnection())) {
/** @var ConnectionInterface */
$connection = $slave->getConnection();
$connection->removeAllListeners('close');
$connection->close();
}
} | [
"protected",
"function",
"closeSlave",
"(",
"$",
"slave",
")",
"{",
"$",
"slave",
"->",
"close",
"(",
")",
";",
"$",
"this",
"->",
"slaves",
"->",
"remove",
"(",
"$",
"slave",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"slave",
"->",
"getConnection",
"(",
")",
")",
")",
"{",
"/** @var ConnectionInterface */",
"$",
"connection",
"=",
"$",
"slave",
"->",
"getConnection",
"(",
")",
";",
"$",
"connection",
"->",
"removeAllListeners",
"(",
"'close'",
")",
";",
"$",
"connection",
"->",
"close",
"(",
")",
";",
"}",
"}"
]
| Close a slave
@param Slave $slave
@return void | [
"Close",
"a",
"slave"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L992-L1003 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.reloadSlaves | public function reloadSlaves($graceful = true)
{
$this->output->writeln('<info>Reloading all workers gracefully</info>');
$this->closeSlaves($graceful, function ($slave) {
/** @var $slave Slave */
if ($this->output->isVeryVerbose()) {
$this->output->writeln(
sprintf(
'Worker #%d has been closed, reloading.',
$slave->getPort()
)
);
}
$this->newSlaveInstance($slave->getPort());
});
} | php | public function reloadSlaves($graceful = true)
{
$this->output->writeln('<info>Reloading all workers gracefully</info>');
$this->closeSlaves($graceful, function ($slave) {
/** @var $slave Slave */
if ($this->output->isVeryVerbose()) {
$this->output->writeln(
sprintf(
'Worker #%d has been closed, reloading.',
$slave->getPort()
)
);
}
$this->newSlaveInstance($slave->getPort());
});
} | [
"public",
"function",
"reloadSlaves",
"(",
"$",
"graceful",
"=",
"true",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"'<info>Reloading all workers gracefully</info>'",
")",
";",
"$",
"this",
"->",
"closeSlaves",
"(",
"$",
"graceful",
",",
"function",
"(",
"$",
"slave",
")",
"{",
"/** @var $slave Slave */",
"if",
"(",
"$",
"this",
"->",
"output",
"->",
"isVeryVerbose",
"(",
")",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'Worker #%d has been closed, reloading.'",
",",
"$",
"slave",
"->",
"getPort",
"(",
")",
")",
")",
";",
"}",
"$",
"this",
"->",
"newSlaveInstance",
"(",
"$",
"slave",
"->",
"getPort",
"(",
")",
")",
";",
"}",
")",
";",
"}"
]
| Reload slaves in-place, allowing busy workers to finish what they are doing. | [
"Reload",
"slaves",
"in",
"-",
"place",
"allowing",
"busy",
"workers",
"to",
"finish",
"what",
"they",
"are",
"doing",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L1008-L1026 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.closeSlaves | public function closeSlaves($graceful = false, $onSlaveClosed = null)
{
if (!$onSlaveClosed) {
// create a default no-op if callable is undefined
$onSlaveClosed = function ($slave) {
};
}
/*
* NB: we don't lock slave reload with a semaphore, since this could cause
* improper reloads when long reload timeouts and multiple code edits are combined.
*/
$this->slavesToReload = [];
foreach ($this->slaves->getByStatus(Slave::ANY) as $slave) {
/** @var Slave $slave */
/*
* Attach the callable to the connection close event, because locked workers are closed via RequestHandler.
* For now, we still need to call onClosed() in other circumstances as ProcessManager->closeSlave() removes
* all close handlers.
*/
$connection = $slave->getConnection();
if ($connection) {
// todo: connection has to be null-checked, because of race conditions with many workers. fixed in #366
$connection->on('close', function () use ($onSlaveClosed, $slave) {
$onSlaveClosed($slave);
});
}
if ($graceful && $slave->getStatus() === Slave::BUSY) {
if ($this->output->isVeryVerbose()) {
$this->output->writeln(sprintf('Waiting for worker #%d to finish', $slave->getPort()));
}
$slave->lock();
$this->slavesToReload[$slave->getPort()] = $slave;
} elseif ($graceful && $slave->getStatus() === Slave::LOCKED) {
if ($this->output->isVeryVerbose()) {
$this->output->writeln(
sprintf(
'Still waiting for worker #%d to finish from an earlier reload',
$slave->getPort()
)
);
}
$this->slavesToReload[$slave->getPort()] = $slave;
} else {
$this->closeSlave($slave);
$onSlaveClosed($slave);
}
}
if ($this->reloadTimeoutTimer !== null) {
$this->loop->cancelTimer($this->reloadTimeoutTimer);
}
$this->reloadTimeoutTimer = $this->loop->addTimer($this->reloadTimeout, function () use ($onSlaveClosed) {
if ($this->slavesToReload && $this->output->isVeryVerbose()) {
$this->output->writeln('Cleaning up workers that exceeded the graceful reload timeout.');
}
foreach ($this->slavesToReload as $slave) {
$this->output->writeln(
sprintf(
'<error>Worker #%d exceeded the graceful reload timeout and was killed.</error>',
$slave->getPort()
)
);
$this->closeSlave($slave);
$onSlaveClosed($slave);
}
});
} | php | public function closeSlaves($graceful = false, $onSlaveClosed = null)
{
if (!$onSlaveClosed) {
// create a default no-op if callable is undefined
$onSlaveClosed = function ($slave) {
};
}
/*
* NB: we don't lock slave reload with a semaphore, since this could cause
* improper reloads when long reload timeouts and multiple code edits are combined.
*/
$this->slavesToReload = [];
foreach ($this->slaves->getByStatus(Slave::ANY) as $slave) {
/** @var Slave $slave */
/*
* Attach the callable to the connection close event, because locked workers are closed via RequestHandler.
* For now, we still need to call onClosed() in other circumstances as ProcessManager->closeSlave() removes
* all close handlers.
*/
$connection = $slave->getConnection();
if ($connection) {
// todo: connection has to be null-checked, because of race conditions with many workers. fixed in #366
$connection->on('close', function () use ($onSlaveClosed, $slave) {
$onSlaveClosed($slave);
});
}
if ($graceful && $slave->getStatus() === Slave::BUSY) {
if ($this->output->isVeryVerbose()) {
$this->output->writeln(sprintf('Waiting for worker #%d to finish', $slave->getPort()));
}
$slave->lock();
$this->slavesToReload[$slave->getPort()] = $slave;
} elseif ($graceful && $slave->getStatus() === Slave::LOCKED) {
if ($this->output->isVeryVerbose()) {
$this->output->writeln(
sprintf(
'Still waiting for worker #%d to finish from an earlier reload',
$slave->getPort()
)
);
}
$this->slavesToReload[$slave->getPort()] = $slave;
} else {
$this->closeSlave($slave);
$onSlaveClosed($slave);
}
}
if ($this->reloadTimeoutTimer !== null) {
$this->loop->cancelTimer($this->reloadTimeoutTimer);
}
$this->reloadTimeoutTimer = $this->loop->addTimer($this->reloadTimeout, function () use ($onSlaveClosed) {
if ($this->slavesToReload && $this->output->isVeryVerbose()) {
$this->output->writeln('Cleaning up workers that exceeded the graceful reload timeout.');
}
foreach ($this->slavesToReload as $slave) {
$this->output->writeln(
sprintf(
'<error>Worker #%d exceeded the graceful reload timeout and was killed.</error>',
$slave->getPort()
)
);
$this->closeSlave($slave);
$onSlaveClosed($slave);
}
});
} | [
"public",
"function",
"closeSlaves",
"(",
"$",
"graceful",
"=",
"false",
",",
"$",
"onSlaveClosed",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"onSlaveClosed",
")",
"{",
"// create a default no-op if callable is undefined",
"$",
"onSlaveClosed",
"=",
"function",
"(",
"$",
"slave",
")",
"{",
"}",
";",
"}",
"/*\n * NB: we don't lock slave reload with a semaphore, since this could cause\n * improper reloads when long reload timeouts and multiple code edits are combined.\n */",
"$",
"this",
"->",
"slavesToReload",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"slaves",
"->",
"getByStatus",
"(",
"Slave",
"::",
"ANY",
")",
"as",
"$",
"slave",
")",
"{",
"/** @var Slave $slave */",
"/*\n * Attach the callable to the connection close event, because locked workers are closed via RequestHandler.\n * For now, we still need to call onClosed() in other circumstances as ProcessManager->closeSlave() removes\n * all close handlers.\n */",
"$",
"connection",
"=",
"$",
"slave",
"->",
"getConnection",
"(",
")",
";",
"if",
"(",
"$",
"connection",
")",
"{",
"// todo: connection has to be null-checked, because of race conditions with many workers. fixed in #366",
"$",
"connection",
"->",
"on",
"(",
"'close'",
",",
"function",
"(",
")",
"use",
"(",
"$",
"onSlaveClosed",
",",
"$",
"slave",
")",
"{",
"$",
"onSlaveClosed",
"(",
"$",
"slave",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"$",
"graceful",
"&&",
"$",
"slave",
"->",
"getStatus",
"(",
")",
"===",
"Slave",
"::",
"BUSY",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"output",
"->",
"isVeryVerbose",
"(",
")",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'Waiting for worker #%d to finish'",
",",
"$",
"slave",
"->",
"getPort",
"(",
")",
")",
")",
";",
"}",
"$",
"slave",
"->",
"lock",
"(",
")",
";",
"$",
"this",
"->",
"slavesToReload",
"[",
"$",
"slave",
"->",
"getPort",
"(",
")",
"]",
"=",
"$",
"slave",
";",
"}",
"elseif",
"(",
"$",
"graceful",
"&&",
"$",
"slave",
"->",
"getStatus",
"(",
")",
"===",
"Slave",
"::",
"LOCKED",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"output",
"->",
"isVeryVerbose",
"(",
")",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'Still waiting for worker #%d to finish from an earlier reload'",
",",
"$",
"slave",
"->",
"getPort",
"(",
")",
")",
")",
";",
"}",
"$",
"this",
"->",
"slavesToReload",
"[",
"$",
"slave",
"->",
"getPort",
"(",
")",
"]",
"=",
"$",
"slave",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"closeSlave",
"(",
"$",
"slave",
")",
";",
"$",
"onSlaveClosed",
"(",
"$",
"slave",
")",
";",
"}",
"}",
"if",
"(",
"$",
"this",
"->",
"reloadTimeoutTimer",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"loop",
"->",
"cancelTimer",
"(",
"$",
"this",
"->",
"reloadTimeoutTimer",
")",
";",
"}",
"$",
"this",
"->",
"reloadTimeoutTimer",
"=",
"$",
"this",
"->",
"loop",
"->",
"addTimer",
"(",
"$",
"this",
"->",
"reloadTimeout",
",",
"function",
"(",
")",
"use",
"(",
"$",
"onSlaveClosed",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"slavesToReload",
"&&",
"$",
"this",
"->",
"output",
"->",
"isVeryVerbose",
"(",
")",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"'Cleaning up workers that exceeded the graceful reload timeout.'",
")",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"slavesToReload",
"as",
"$",
"slave",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'<error>Worker #%d exceeded the graceful reload timeout and was killed.</error>'",
",",
"$",
"slave",
"->",
"getPort",
"(",
")",
")",
")",
";",
"$",
"this",
"->",
"closeSlave",
"(",
"$",
"slave",
")",
";",
"$",
"onSlaveClosed",
"(",
"$",
"slave",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Closes all slaves and fires a user-defined callback for each slave that is closed.
If $graceful is false, slaves are closed unconditionally, regardless of their current status.
If $graceful is true, workers that are busy are put into a locked state, and will be closed after serving the
current request. If a reload-timeout is configured with a non-negative value, any workers that exceed this value
in seconds will be killed.
@param bool $graceful
@param callable $onSlaveClosed A closure that is called for each worker. | [
"Closes",
"all",
"slaves",
"and",
"fires",
"a",
"user",
"-",
"defined",
"callback",
"for",
"each",
"slave",
"that",
"is",
"closed",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L1040-L1116 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.restartSlaves | public function restartSlaves()
{
if ($this->inRestart) {
return;
}
$this->inRestart = true;
$this->closeSlaves();
$this->createSlaves();
$this->inRestart = false;
} | php | public function restartSlaves()
{
if ($this->inRestart) {
return;
}
$this->inRestart = true;
$this->closeSlaves();
$this->createSlaves();
$this->inRestart = false;
} | [
"public",
"function",
"restartSlaves",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"inRestart",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"inRestart",
"=",
"true",
";",
"$",
"this",
"->",
"closeSlaves",
"(",
")",
";",
"$",
"this",
"->",
"createSlaves",
"(",
")",
";",
"$",
"this",
"->",
"inRestart",
"=",
"false",
";",
"}"
]
| Restart all slaves. Necessary when watched files have changed. | [
"Restart",
"all",
"slaves",
".",
"Necessary",
"when",
"watched",
"files",
"have",
"changed",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L1121-L1133 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.allSlavesReady | protected function allSlavesReady()
{
if ($this->status === self::STATE_STARTING || $this->status === self::STATE_EMERGENCY) {
$readySlaves = $this->slaves->getByStatus(Slave::READY);
$busySlaves = $this->slaves->getByStatus(Slave::BUSY);
return count($readySlaves) + count($busySlaves) === $this->slaveCount;
}
return false;
} | php | protected function allSlavesReady()
{
if ($this->status === self::STATE_STARTING || $this->status === self::STATE_EMERGENCY) {
$readySlaves = $this->slaves->getByStatus(Slave::READY);
$busySlaves = $this->slaves->getByStatus(Slave::BUSY);
return count($readySlaves) + count($busySlaves) === $this->slaveCount;
}
return false;
} | [
"protected",
"function",
"allSlavesReady",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"status",
"===",
"self",
"::",
"STATE_STARTING",
"||",
"$",
"this",
"->",
"status",
"===",
"self",
"::",
"STATE_EMERGENCY",
")",
"{",
"$",
"readySlaves",
"=",
"$",
"this",
"->",
"slaves",
"->",
"getByStatus",
"(",
"Slave",
"::",
"READY",
")",
";",
"$",
"busySlaves",
"=",
"$",
"this",
"->",
"slaves",
"->",
"getByStatus",
"(",
"Slave",
"::",
"BUSY",
")",
";",
"return",
"count",
"(",
"$",
"readySlaves",
")",
"+",
"count",
"(",
"$",
"busySlaves",
")",
"===",
"$",
"this",
"->",
"slaveCount",
";",
"}",
"return",
"false",
";",
"}"
]
| Check if all slaves have become available | [
"Check",
"if",
"all",
"slaves",
"have",
"become",
"available"
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L1138-L1147 | train |
php-pm/php-pm | src/ProcessManager.php | ProcessManager.newSlaveInstance | protected function newSlaveInstance($port)
{
if ($this->status === self::STATE_SHUTDOWN) {
// during shutdown phase all connections are closed and as result new
// instances are created - which is forbidden during this phase
return;
}
if ($this->output->isVeryVerbose()) {
$this->output->writeln(sprintf("Start new worker #%d", $port));
}
$socketpath = var_export($this->getSocketPath(), true);
$bridge = var_export($this->getBridge(), true);
$bootstrap = var_export($this->getAppBootstrap(), true);
$config = [
'port' => $port,
'session_path' => session_save_path(),
'app-env' => $this->getAppEnv(),
'debug' => $this->isDebug(),
'logging' => $this->isLogging(),
'static-directory' => $this->getStaticDirectory(),
'populate-server-var' => $this->isPopulateServer()
];
$config = var_export($config, true);
$dir = var_export(__DIR__ . '/..', true);
$script = <<<EOF
<?php
namespace PHPPM;
set_time_limit(0);
require_once file_exists($dir . '/vendor/autoload.php')
? $dir . '/vendor/autoload.php'
: $dir . '/../../autoload.php';
if (!pcntl_installed()) {
error_log(
sprintf(
'PCNTL is not enabled in the PHP installation at %s. See: http://php.net/manual/en/pcntl.installation.php',
PHP_BINARY
)
);
exit();
}
if (!pcntl_enabled()) {
error_log('Some required PCNTL functions are disabled. Check `disabled_functions` in `php.ini`.');
exit();
}
//global for all global functions
ProcessSlave::\$slave = new ProcessSlave($socketpath, $bridge, $bootstrap, $config);
ProcessSlave::\$slave->run();
EOF;
// slave php file
$file = tempnam(sys_get_temp_dir(), 'dbg');
file_put_contents($file, $script);
register_shutdown_function('unlink', $file);
// we can not use -q since this disables basically all header support
// but since this is necessary at least in Symfony we can not use it.
// e.g. headers_sent() returns always true, although wrong.
// For version 2.x and 3.x of \Symfony\Component\Process\Process package
if (method_exists('\Symfony\Component\Process\ProcessUtils', 'escapeArgument')) {
$commandline = 'exec ' . $this->phpCgiExecutable . ' -C ' . ProcessUtils::escapeArgument($file);
} else {
//For version 4.x of \Symfony\Component\Process\Process package
$commandline = ['exec', $this->phpCgiExecutable, '-C', $file];
$processInstance = new \Symfony\Component\Process\Process($commandline);
$commandline = $processInstance->getCommandLine();
}
// use exec to omit wrapping shell
$process = new Process($commandline);
$slave = new Slave($port, $this->maxRequests, $this->memoryLimit, $this->ttl);
$slave->attach($process);
$this->slaves->add($slave);
$process->start($this->loop);
$process->stderr->on(
'data',
function ($data) use ($port) {
if ($this->lastWorkerErrorPrintBy !== $port) {
$this->output->writeln("<info>--- Worker $port stderr ---</info>");
$this->lastWorkerErrorPrintBy = $port;
}
$this->output->write("<error>$data</error>");
}
);
} | php | protected function newSlaveInstance($port)
{
if ($this->status === self::STATE_SHUTDOWN) {
// during shutdown phase all connections are closed and as result new
// instances are created - which is forbidden during this phase
return;
}
if ($this->output->isVeryVerbose()) {
$this->output->writeln(sprintf("Start new worker #%d", $port));
}
$socketpath = var_export($this->getSocketPath(), true);
$bridge = var_export($this->getBridge(), true);
$bootstrap = var_export($this->getAppBootstrap(), true);
$config = [
'port' => $port,
'session_path' => session_save_path(),
'app-env' => $this->getAppEnv(),
'debug' => $this->isDebug(),
'logging' => $this->isLogging(),
'static-directory' => $this->getStaticDirectory(),
'populate-server-var' => $this->isPopulateServer()
];
$config = var_export($config, true);
$dir = var_export(__DIR__ . '/..', true);
$script = <<<EOF
<?php
namespace PHPPM;
set_time_limit(0);
require_once file_exists($dir . '/vendor/autoload.php')
? $dir . '/vendor/autoload.php'
: $dir . '/../../autoload.php';
if (!pcntl_installed()) {
error_log(
sprintf(
'PCNTL is not enabled in the PHP installation at %s. See: http://php.net/manual/en/pcntl.installation.php',
PHP_BINARY
)
);
exit();
}
if (!pcntl_enabled()) {
error_log('Some required PCNTL functions are disabled. Check `disabled_functions` in `php.ini`.');
exit();
}
//global for all global functions
ProcessSlave::\$slave = new ProcessSlave($socketpath, $bridge, $bootstrap, $config);
ProcessSlave::\$slave->run();
EOF;
// slave php file
$file = tempnam(sys_get_temp_dir(), 'dbg');
file_put_contents($file, $script);
register_shutdown_function('unlink', $file);
// we can not use -q since this disables basically all header support
// but since this is necessary at least in Symfony we can not use it.
// e.g. headers_sent() returns always true, although wrong.
// For version 2.x and 3.x of \Symfony\Component\Process\Process package
if (method_exists('\Symfony\Component\Process\ProcessUtils', 'escapeArgument')) {
$commandline = 'exec ' . $this->phpCgiExecutable . ' -C ' . ProcessUtils::escapeArgument($file);
} else {
//For version 4.x of \Symfony\Component\Process\Process package
$commandline = ['exec', $this->phpCgiExecutable, '-C', $file];
$processInstance = new \Symfony\Component\Process\Process($commandline);
$commandline = $processInstance->getCommandLine();
}
// use exec to omit wrapping shell
$process = new Process($commandline);
$slave = new Slave($port, $this->maxRequests, $this->memoryLimit, $this->ttl);
$slave->attach($process);
$this->slaves->add($slave);
$process->start($this->loop);
$process->stderr->on(
'data',
function ($data) use ($port) {
if ($this->lastWorkerErrorPrintBy !== $port) {
$this->output->writeln("<info>--- Worker $port stderr ---</info>");
$this->lastWorkerErrorPrintBy = $port;
}
$this->output->write("<error>$data</error>");
}
);
} | [
"protected",
"function",
"newSlaveInstance",
"(",
"$",
"port",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"status",
"===",
"self",
"::",
"STATE_SHUTDOWN",
")",
"{",
"// during shutdown phase all connections are closed and as result new",
"// instances are created - which is forbidden during this phase",
"return",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"output",
"->",
"isVeryVerbose",
"(",
")",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"\"Start new worker #%d\"",
",",
"$",
"port",
")",
")",
";",
"}",
"$",
"socketpath",
"=",
"var_export",
"(",
"$",
"this",
"->",
"getSocketPath",
"(",
")",
",",
"true",
")",
";",
"$",
"bridge",
"=",
"var_export",
"(",
"$",
"this",
"->",
"getBridge",
"(",
")",
",",
"true",
")",
";",
"$",
"bootstrap",
"=",
"var_export",
"(",
"$",
"this",
"->",
"getAppBootstrap",
"(",
")",
",",
"true",
")",
";",
"$",
"config",
"=",
"[",
"'port'",
"=>",
"$",
"port",
",",
"'session_path'",
"=>",
"session_save_path",
"(",
")",
",",
"'app-env'",
"=>",
"$",
"this",
"->",
"getAppEnv",
"(",
")",
",",
"'debug'",
"=>",
"$",
"this",
"->",
"isDebug",
"(",
")",
",",
"'logging'",
"=>",
"$",
"this",
"->",
"isLogging",
"(",
")",
",",
"'static-directory'",
"=>",
"$",
"this",
"->",
"getStaticDirectory",
"(",
")",
",",
"'populate-server-var'",
"=>",
"$",
"this",
"->",
"isPopulateServer",
"(",
")",
"]",
";",
"$",
"config",
"=",
"var_export",
"(",
"$",
"config",
",",
"true",
")",
";",
"$",
"dir",
"=",
"var_export",
"(",
"__DIR__",
".",
"'/..'",
",",
"true",
")",
";",
"$",
"script",
"=",
" <<<EOF\n<?php\n\nnamespace PHPPM;\n\nset_time_limit(0);\n\nrequire_once file_exists($dir . '/vendor/autoload.php')\n ? $dir . '/vendor/autoload.php'\n : $dir . '/../../autoload.php';\n \nif (!pcntl_installed()) {\n error_log(\n sprintf(\n 'PCNTL is not enabled in the PHP installation at %s. See: http://php.net/manual/en/pcntl.installation.php',\n PHP_BINARY\n )\n );\n exit();\n}\n\nif (!pcntl_enabled()) {\n error_log('Some required PCNTL functions are disabled. Check `disabled_functions` in `php.ini`.');\n exit();\n}\n\n//global for all global functions\nProcessSlave::\\$slave = new ProcessSlave($socketpath, $bridge, $bootstrap, $config);\nProcessSlave::\\$slave->run();\nEOF",
";",
"// slave php file",
"$",
"file",
"=",
"tempnam",
"(",
"sys_get_temp_dir",
"(",
")",
",",
"'dbg'",
")",
";",
"file_put_contents",
"(",
"$",
"file",
",",
"$",
"script",
")",
";",
"register_shutdown_function",
"(",
"'unlink'",
",",
"$",
"file",
")",
";",
"// we can not use -q since this disables basically all header support",
"// but since this is necessary at least in Symfony we can not use it.",
"// e.g. headers_sent() returns always true, although wrong.",
"// For version 2.x and 3.x of \\Symfony\\Component\\Process\\Process package",
"if",
"(",
"method_exists",
"(",
"'\\Symfony\\Component\\Process\\ProcessUtils'",
",",
"'escapeArgument'",
")",
")",
"{",
"$",
"commandline",
"=",
"'exec '",
".",
"$",
"this",
"->",
"phpCgiExecutable",
".",
"' -C '",
".",
"ProcessUtils",
"::",
"escapeArgument",
"(",
"$",
"file",
")",
";",
"}",
"else",
"{",
"//For version 4.x of \\Symfony\\Component\\Process\\Process package",
"$",
"commandline",
"=",
"[",
"'exec'",
",",
"$",
"this",
"->",
"phpCgiExecutable",
",",
"'-C'",
",",
"$",
"file",
"]",
";",
"$",
"processInstance",
"=",
"new",
"\\",
"Symfony",
"\\",
"Component",
"\\",
"Process",
"\\",
"Process",
"(",
"$",
"commandline",
")",
";",
"$",
"commandline",
"=",
"$",
"processInstance",
"->",
"getCommandLine",
"(",
")",
";",
"}",
"// use exec to omit wrapping shell",
"$",
"process",
"=",
"new",
"Process",
"(",
"$",
"commandline",
")",
";",
"$",
"slave",
"=",
"new",
"Slave",
"(",
"$",
"port",
",",
"$",
"this",
"->",
"maxRequests",
",",
"$",
"this",
"->",
"memoryLimit",
",",
"$",
"this",
"->",
"ttl",
")",
";",
"$",
"slave",
"->",
"attach",
"(",
"$",
"process",
")",
";",
"$",
"this",
"->",
"slaves",
"->",
"add",
"(",
"$",
"slave",
")",
";",
"$",
"process",
"->",
"start",
"(",
"$",
"this",
"->",
"loop",
")",
";",
"$",
"process",
"->",
"stderr",
"->",
"on",
"(",
"'data'",
",",
"function",
"(",
"$",
"data",
")",
"use",
"(",
"$",
"port",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"lastWorkerErrorPrintBy",
"!==",
"$",
"port",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"\"<info>--- Worker $port stderr ---</info>\"",
")",
";",
"$",
"this",
"->",
"lastWorkerErrorPrintBy",
"=",
"$",
"port",
";",
"}",
"$",
"this",
"->",
"output",
"->",
"write",
"(",
"\"<error>$data</error>\"",
")",
";",
"}",
")",
";",
"}"
]
| Creates a new ProcessSlave instance.
@param int $port | [
"Creates",
"a",
"new",
"ProcessSlave",
"instance",
"."
]
| 4db650a94b51a26ce80dbec82e419ee913333431 | https://github.com/php-pm/php-pm/blob/4db650a94b51a26ce80dbec82e419ee913333431/src/ProcessManager.php#L1154-L1251 | train |
api-platform/core | src/Bridge/Doctrine/MongoDbOdm/PropertyHelperTrait.php | PropertyHelperTrait.addLookupsForNestedProperty | protected function addLookupsForNestedProperty(string $property, Builder $aggregationBuilder, string $resourceClass): array
{
$propertyParts = $this->splitPropertyParts($property, $resourceClass);
$alias = '';
foreach ($propertyParts['associations'] as $association) {
$classMetadata = $this->getClassMetadata($resourceClass);
if (!$classMetadata instanceof MongoDbOdmClassMetadata) {
break;
}
if ($classMetadata->hasReference($association)) {
$propertyAlias = "${association}_lkup";
// previous_association_lkup.association
$localField = "$alias$association";
// previous_association_lkup.association_lkup
$alias .= $propertyAlias;
$referenceMapping = $classMetadata->getFieldMapping($association);
if (($isOwningSide = $referenceMapping['isOwningSide']) && MongoDbOdmClassMetadata::REFERENCE_STORE_AS_ID !== $referenceMapping['storeAs']) {
throw MappingException::cannotLookupDbRefReference($classMetadata->getReflectionClass()->getShortName(), $association);
}
if (!$isOwningSide) {
if (isset($referenceMapping['repositoryMethod']) || !isset($referenceMapping['mappedBy'])) {
throw MappingException::repositoryMethodLookupNotAllowed($classMetadata->getReflectionClass()->getShortName(), $association);
}
$targetClassMetadata = $this->getClassMetadata($referenceMapping['targetDocument']);
if ($targetClassMetadata instanceof MongoDbOdmClassMetadata && MongoDbOdmClassMetadata::REFERENCE_STORE_AS_ID !== $targetClassMetadata->getFieldMapping($referenceMapping['mappedBy'])['storeAs']) {
throw MappingException::cannotLookupDbRefReference($classMetadata->getReflectionClass()->getShortName(), $association);
}
}
$aggregationBuilder->lookup($classMetadata->getAssociationTargetClass($association))
->localField($isOwningSide ? $localField : '_id')
->foreignField($isOwningSide ? '_id' : $referenceMapping['mappedBy'])
->alias($alias);
$aggregationBuilder->unwind("\$$alias");
// association.property => association_lkup.property
$property = substr_replace($property, $propertyAlias, strpos($property, $association), \strlen($association));
$resourceClass = $classMetadata->getAssociationTargetClass($association);
$alias .= '.';
} elseif ($classMetadata->hasEmbed($association)) {
$alias = "$association.";
$resourceClass = $classMetadata->getAssociationTargetClass($association);
}
}
if ('' === $alias) {
throw new InvalidArgumentException(sprintf('Cannot add lookups for property "%s" - property is not nested.', $property));
}
return [$property, $propertyParts['field'], $propertyParts['associations']];
} | php | protected function addLookupsForNestedProperty(string $property, Builder $aggregationBuilder, string $resourceClass): array
{
$propertyParts = $this->splitPropertyParts($property, $resourceClass);
$alias = '';
foreach ($propertyParts['associations'] as $association) {
$classMetadata = $this->getClassMetadata($resourceClass);
if (!$classMetadata instanceof MongoDbOdmClassMetadata) {
break;
}
if ($classMetadata->hasReference($association)) {
$propertyAlias = "${association}_lkup";
// previous_association_lkup.association
$localField = "$alias$association";
// previous_association_lkup.association_lkup
$alias .= $propertyAlias;
$referenceMapping = $classMetadata->getFieldMapping($association);
if (($isOwningSide = $referenceMapping['isOwningSide']) && MongoDbOdmClassMetadata::REFERENCE_STORE_AS_ID !== $referenceMapping['storeAs']) {
throw MappingException::cannotLookupDbRefReference($classMetadata->getReflectionClass()->getShortName(), $association);
}
if (!$isOwningSide) {
if (isset($referenceMapping['repositoryMethod']) || !isset($referenceMapping['mappedBy'])) {
throw MappingException::repositoryMethodLookupNotAllowed($classMetadata->getReflectionClass()->getShortName(), $association);
}
$targetClassMetadata = $this->getClassMetadata($referenceMapping['targetDocument']);
if ($targetClassMetadata instanceof MongoDbOdmClassMetadata && MongoDbOdmClassMetadata::REFERENCE_STORE_AS_ID !== $targetClassMetadata->getFieldMapping($referenceMapping['mappedBy'])['storeAs']) {
throw MappingException::cannotLookupDbRefReference($classMetadata->getReflectionClass()->getShortName(), $association);
}
}
$aggregationBuilder->lookup($classMetadata->getAssociationTargetClass($association))
->localField($isOwningSide ? $localField : '_id')
->foreignField($isOwningSide ? '_id' : $referenceMapping['mappedBy'])
->alias($alias);
$aggregationBuilder->unwind("\$$alias");
// association.property => association_lkup.property
$property = substr_replace($property, $propertyAlias, strpos($property, $association), \strlen($association));
$resourceClass = $classMetadata->getAssociationTargetClass($association);
$alias .= '.';
} elseif ($classMetadata->hasEmbed($association)) {
$alias = "$association.";
$resourceClass = $classMetadata->getAssociationTargetClass($association);
}
}
if ('' === $alias) {
throw new InvalidArgumentException(sprintf('Cannot add lookups for property "%s" - property is not nested.', $property));
}
return [$property, $propertyParts['field'], $propertyParts['associations']];
} | [
"protected",
"function",
"addLookupsForNestedProperty",
"(",
"string",
"$",
"property",
",",
"Builder",
"$",
"aggregationBuilder",
",",
"string",
"$",
"resourceClass",
")",
":",
"array",
"{",
"$",
"propertyParts",
"=",
"$",
"this",
"->",
"splitPropertyParts",
"(",
"$",
"property",
",",
"$",
"resourceClass",
")",
";",
"$",
"alias",
"=",
"''",
";",
"foreach",
"(",
"$",
"propertyParts",
"[",
"'associations'",
"]",
"as",
"$",
"association",
")",
"{",
"$",
"classMetadata",
"=",
"$",
"this",
"->",
"getClassMetadata",
"(",
"$",
"resourceClass",
")",
";",
"if",
"(",
"!",
"$",
"classMetadata",
"instanceof",
"MongoDbOdmClassMetadata",
")",
"{",
"break",
";",
"}",
"if",
"(",
"$",
"classMetadata",
"->",
"hasReference",
"(",
"$",
"association",
")",
")",
"{",
"$",
"propertyAlias",
"=",
"\"${association}_lkup\"",
";",
"// previous_association_lkup.association",
"$",
"localField",
"=",
"\"$alias$association\"",
";",
"// previous_association_lkup.association_lkup",
"$",
"alias",
".=",
"$",
"propertyAlias",
";",
"$",
"referenceMapping",
"=",
"$",
"classMetadata",
"->",
"getFieldMapping",
"(",
"$",
"association",
")",
";",
"if",
"(",
"(",
"$",
"isOwningSide",
"=",
"$",
"referenceMapping",
"[",
"'isOwningSide'",
"]",
")",
"&&",
"MongoDbOdmClassMetadata",
"::",
"REFERENCE_STORE_AS_ID",
"!==",
"$",
"referenceMapping",
"[",
"'storeAs'",
"]",
")",
"{",
"throw",
"MappingException",
"::",
"cannotLookupDbRefReference",
"(",
"$",
"classMetadata",
"->",
"getReflectionClass",
"(",
")",
"->",
"getShortName",
"(",
")",
",",
"$",
"association",
")",
";",
"}",
"if",
"(",
"!",
"$",
"isOwningSide",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"referenceMapping",
"[",
"'repositoryMethod'",
"]",
")",
"||",
"!",
"isset",
"(",
"$",
"referenceMapping",
"[",
"'mappedBy'",
"]",
")",
")",
"{",
"throw",
"MappingException",
"::",
"repositoryMethodLookupNotAllowed",
"(",
"$",
"classMetadata",
"->",
"getReflectionClass",
"(",
")",
"->",
"getShortName",
"(",
")",
",",
"$",
"association",
")",
";",
"}",
"$",
"targetClassMetadata",
"=",
"$",
"this",
"->",
"getClassMetadata",
"(",
"$",
"referenceMapping",
"[",
"'targetDocument'",
"]",
")",
";",
"if",
"(",
"$",
"targetClassMetadata",
"instanceof",
"MongoDbOdmClassMetadata",
"&&",
"MongoDbOdmClassMetadata",
"::",
"REFERENCE_STORE_AS_ID",
"!==",
"$",
"targetClassMetadata",
"->",
"getFieldMapping",
"(",
"$",
"referenceMapping",
"[",
"'mappedBy'",
"]",
")",
"[",
"'storeAs'",
"]",
")",
"{",
"throw",
"MappingException",
"::",
"cannotLookupDbRefReference",
"(",
"$",
"classMetadata",
"->",
"getReflectionClass",
"(",
")",
"->",
"getShortName",
"(",
")",
",",
"$",
"association",
")",
";",
"}",
"}",
"$",
"aggregationBuilder",
"->",
"lookup",
"(",
"$",
"classMetadata",
"->",
"getAssociationTargetClass",
"(",
"$",
"association",
")",
")",
"->",
"localField",
"(",
"$",
"isOwningSide",
"?",
"$",
"localField",
":",
"'_id'",
")",
"->",
"foreignField",
"(",
"$",
"isOwningSide",
"?",
"'_id'",
":",
"$",
"referenceMapping",
"[",
"'mappedBy'",
"]",
")",
"->",
"alias",
"(",
"$",
"alias",
")",
";",
"$",
"aggregationBuilder",
"->",
"unwind",
"(",
"\"\\$$alias\"",
")",
";",
"// association.property => association_lkup.property",
"$",
"property",
"=",
"substr_replace",
"(",
"$",
"property",
",",
"$",
"propertyAlias",
",",
"strpos",
"(",
"$",
"property",
",",
"$",
"association",
")",
",",
"\\",
"strlen",
"(",
"$",
"association",
")",
")",
";",
"$",
"resourceClass",
"=",
"$",
"classMetadata",
"->",
"getAssociationTargetClass",
"(",
"$",
"association",
")",
";",
"$",
"alias",
".=",
"'.'",
";",
"}",
"elseif",
"(",
"$",
"classMetadata",
"->",
"hasEmbed",
"(",
"$",
"association",
")",
")",
"{",
"$",
"alias",
"=",
"\"$association.\"",
";",
"$",
"resourceClass",
"=",
"$",
"classMetadata",
"->",
"getAssociationTargetClass",
"(",
"$",
"association",
")",
";",
"}",
"}",
"if",
"(",
"''",
"===",
"$",
"alias",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Cannot add lookups for property \"%s\" - property is not nested.'",
",",
"$",
"property",
")",
")",
";",
"}",
"return",
"[",
"$",
"property",
",",
"$",
"propertyParts",
"[",
"'field'",
"]",
",",
"$",
"propertyParts",
"[",
"'associations'",
"]",
"]",
";",
"}"
]
| Adds the necessary lookups for a nested property.
@throws InvalidArgumentException If property is not nested
@throws MappingException
@return array An array where the first element is the $alias of the lookup,
the second element is the $field name
the third element is the $associations array | [
"Adds",
"the",
"necessary",
"lookups",
"for",
"a",
"nested",
"property",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Bridge/Doctrine/MongoDbOdm/PropertyHelperTrait.php#L51-L106 | train |
api-platform/core | src/Serializer/Filter/PropertyFilter.php | PropertyFilter.formatWhitelist | private function formatWhitelist(array $whitelist): array
{
if (array_values($whitelist) === $whitelist) {
return $whitelist;
}
foreach ($whitelist as $name => $value) {
if (null === $value) {
unset($whitelist[$name]);
$whitelist[] = $name;
}
}
return $whitelist;
} | php | private function formatWhitelist(array $whitelist): array
{
if (array_values($whitelist) === $whitelist) {
return $whitelist;
}
foreach ($whitelist as $name => $value) {
if (null === $value) {
unset($whitelist[$name]);
$whitelist[] = $name;
}
}
return $whitelist;
} | [
"private",
"function",
"formatWhitelist",
"(",
"array",
"$",
"whitelist",
")",
":",
"array",
"{",
"if",
"(",
"array_values",
"(",
"$",
"whitelist",
")",
"===",
"$",
"whitelist",
")",
"{",
"return",
"$",
"whitelist",
";",
"}",
"foreach",
"(",
"$",
"whitelist",
"as",
"$",
"name",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"{",
"unset",
"(",
"$",
"whitelist",
"[",
"$",
"name",
"]",
")",
";",
"$",
"whitelist",
"[",
"]",
"=",
"$",
"name",
";",
"}",
"}",
"return",
"$",
"whitelist",
";",
"}"
]
| Generate an array of whitelist properties to match the format that properties
will have in the request.
@param array $whitelist the whitelist to format
@return array An array containing the whitelist ready to match request parameters | [
"Generate",
"an",
"array",
"of",
"whitelist",
"properties",
"to",
"match",
"the",
"format",
"that",
"properties",
"will",
"have",
"in",
"the",
"request",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Serializer/Filter/PropertyFilter.php#L110-L123 | train |
api-platform/core | src/Bridge/Elasticsearch/Serializer/ItemNormalizer.php | ItemNormalizer.populateIdentifier | private function populateIdentifier(array $data, string $class): array
{
$identifier = $this->identifierExtractor->getIdentifierFromResourceClass($class);
$identifier = null === $this->nameConverter ? $identifier : $this->nameConverter->normalize($identifier, $class, self::FORMAT);
if (!isset($data['_source'][$identifier])) {
$data['_source'][$identifier] = $data['_id'];
}
return $data;
} | php | private function populateIdentifier(array $data, string $class): array
{
$identifier = $this->identifierExtractor->getIdentifierFromResourceClass($class);
$identifier = null === $this->nameConverter ? $identifier : $this->nameConverter->normalize($identifier, $class, self::FORMAT);
if (!isset($data['_source'][$identifier])) {
$data['_source'][$identifier] = $data['_id'];
}
return $data;
} | [
"private",
"function",
"populateIdentifier",
"(",
"array",
"$",
"data",
",",
"string",
"$",
"class",
")",
":",
"array",
"{",
"$",
"identifier",
"=",
"$",
"this",
"->",
"identifierExtractor",
"->",
"getIdentifierFromResourceClass",
"(",
"$",
"class",
")",
";",
"$",
"identifier",
"=",
"null",
"===",
"$",
"this",
"->",
"nameConverter",
"?",
"$",
"identifier",
":",
"$",
"this",
"->",
"nameConverter",
"->",
"normalize",
"(",
"$",
"identifier",
",",
"$",
"class",
",",
"self",
"::",
"FORMAT",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"data",
"[",
"'_source'",
"]",
"[",
"$",
"identifier",
"]",
")",
")",
"{",
"$",
"data",
"[",
"'_source'",
"]",
"[",
"$",
"identifier",
"]",
"=",
"$",
"data",
"[",
"'_id'",
"]",
";",
"}",
"return",
"$",
"data",
";",
"}"
]
| Populates the resource identifier with the document identifier if not present in the original JSON document. | [
"Populates",
"the",
"resource",
"identifier",
"with",
"the",
"document",
"identifier",
"if",
"not",
"present",
"in",
"the",
"original",
"JSON",
"document",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Bridge/Elasticsearch/Serializer/ItemNormalizer.php#L87-L97 | train |
api-platform/core | src/Serializer/AbstractCollectionNormalizer.php | AbstractCollectionNormalizer.getPaginationConfig | protected function getPaginationConfig($object, array $context = []): array
{
$currentPage = $lastPage = $itemsPerPage = $pageTotalItems = $totalItems = null;
$paginated = $paginator = false;
if ($object instanceof PartialPaginatorInterface) {
$paginated = $paginator = true;
if ($object instanceof PaginatorInterface) {
$paginated = 1. !== $lastPage = $object->getLastPage();
$totalItems = $object->getTotalItems();
} else {
$pageTotalItems = (float) \count($object);
}
$currentPage = $object->getCurrentPage();
$itemsPerPage = $object->getItemsPerPage();
} elseif (\is_array($object) || $object instanceof \Countable) {
$totalItems = \count($object);
}
return [$paginator, $paginated, $currentPage, $itemsPerPage, $lastPage, $pageTotalItems, $totalItems];
} | php | protected function getPaginationConfig($object, array $context = []): array
{
$currentPage = $lastPage = $itemsPerPage = $pageTotalItems = $totalItems = null;
$paginated = $paginator = false;
if ($object instanceof PartialPaginatorInterface) {
$paginated = $paginator = true;
if ($object instanceof PaginatorInterface) {
$paginated = 1. !== $lastPage = $object->getLastPage();
$totalItems = $object->getTotalItems();
} else {
$pageTotalItems = (float) \count($object);
}
$currentPage = $object->getCurrentPage();
$itemsPerPage = $object->getItemsPerPage();
} elseif (\is_array($object) || $object instanceof \Countable) {
$totalItems = \count($object);
}
return [$paginator, $paginated, $currentPage, $itemsPerPage, $lastPage, $pageTotalItems, $totalItems];
} | [
"protected",
"function",
"getPaginationConfig",
"(",
"$",
"object",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
":",
"array",
"{",
"$",
"currentPage",
"=",
"$",
"lastPage",
"=",
"$",
"itemsPerPage",
"=",
"$",
"pageTotalItems",
"=",
"$",
"totalItems",
"=",
"null",
";",
"$",
"paginated",
"=",
"$",
"paginator",
"=",
"false",
";",
"if",
"(",
"$",
"object",
"instanceof",
"PartialPaginatorInterface",
")",
"{",
"$",
"paginated",
"=",
"$",
"paginator",
"=",
"true",
";",
"if",
"(",
"$",
"object",
"instanceof",
"PaginatorInterface",
")",
"{",
"$",
"paginated",
"=",
"1.",
"!==",
"$",
"lastPage",
"=",
"$",
"object",
"->",
"getLastPage",
"(",
")",
";",
"$",
"totalItems",
"=",
"$",
"object",
"->",
"getTotalItems",
"(",
")",
";",
"}",
"else",
"{",
"$",
"pageTotalItems",
"=",
"(",
"float",
")",
"\\",
"count",
"(",
"$",
"object",
")",
";",
"}",
"$",
"currentPage",
"=",
"$",
"object",
"->",
"getCurrentPage",
"(",
")",
";",
"$",
"itemsPerPage",
"=",
"$",
"object",
"->",
"getItemsPerPage",
"(",
")",
";",
"}",
"elseif",
"(",
"\\",
"is_array",
"(",
"$",
"object",
")",
"||",
"$",
"object",
"instanceof",
"\\",
"Countable",
")",
"{",
"$",
"totalItems",
"=",
"\\",
"count",
"(",
"$",
"object",
")",
";",
"}",
"return",
"[",
"$",
"paginator",
",",
"$",
"paginated",
",",
"$",
"currentPage",
",",
"$",
"itemsPerPage",
",",
"$",
"lastPage",
",",
"$",
"pageTotalItems",
",",
"$",
"totalItems",
"]",
";",
"}"
]
| Gets the pagination configuration.
@param iterable $object | [
"Gets",
"the",
"pagination",
"configuration",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Serializer/AbstractCollectionNormalizer.php#L117-L138 | train |
api-platform/core | features/bootstrap/SwaggerContext.php | SwaggerContext.getProperties | private function getProperties(string $className, int $specVersion = 2): stdClass
{
return $this->getClassInfo($className, $specVersion)->{'properties'} ?? new \stdClass();
} | php | private function getProperties(string $className, int $specVersion = 2): stdClass
{
return $this->getClassInfo($className, $specVersion)->{'properties'} ?? new \stdClass();
} | [
"private",
"function",
"getProperties",
"(",
"string",
"$",
"className",
",",
"int",
"$",
"specVersion",
"=",
"2",
")",
":",
"stdClass",
"{",
"return",
"$",
"this",
"->",
"getClassInfo",
"(",
"$",
"className",
",",
"$",
"specVersion",
")",
"->",
"{",
"'properties'",
"}",
"??",
"new",
"\\",
"stdClass",
"(",
")",
";",
"}"
]
| Gets all operations of a given class. | [
"Gets",
"all",
"operations",
"of",
"a",
"given",
"class",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/features/bootstrap/SwaggerContext.php#L166-L169 | train |
api-platform/core | features/bootstrap/SwaggerContext.php | SwaggerContext.getLastJsonResponse | private function getLastJsonResponse(): stdClass
{
if (null === ($decoded = json_decode($this->restContext->getMink()->getSession()->getDriver()->getContent()))) {
throw new \RuntimeException('JSON response seems to be invalid');
}
return $decoded;
} | php | private function getLastJsonResponse(): stdClass
{
if (null === ($decoded = json_decode($this->restContext->getMink()->getSession()->getDriver()->getContent()))) {
throw new \RuntimeException('JSON response seems to be invalid');
}
return $decoded;
} | [
"private",
"function",
"getLastJsonResponse",
"(",
")",
":",
"stdClass",
"{",
"if",
"(",
"null",
"===",
"(",
"$",
"decoded",
"=",
"json_decode",
"(",
"$",
"this",
"->",
"restContext",
"->",
"getMink",
"(",
")",
"->",
"getSession",
"(",
")",
"->",
"getDriver",
"(",
")",
"->",
"getContent",
"(",
")",
")",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'JSON response seems to be invalid'",
")",
";",
"}",
"return",
"$",
"decoded",
";",
"}"
]
| Gets the last JSON response.
@throws \RuntimeException | [
"Gets",
"the",
"last",
"JSON",
"response",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/features/bootstrap/SwaggerContext.php#L193-L200 | train |
api-platform/core | src/Bridge/Elasticsearch/Metadata/Document/DocumentMetadata.php | DocumentMetadata.withIndex | public function withIndex(string $index): self
{
$metadata = clone $this;
$metadata->index = $index;
return $metadata;
} | php | public function withIndex(string $index): self
{
$metadata = clone $this;
$metadata->index = $index;
return $metadata;
} | [
"public",
"function",
"withIndex",
"(",
"string",
"$",
"index",
")",
":",
"self",
"{",
"$",
"metadata",
"=",
"clone",
"$",
"this",
";",
"$",
"metadata",
"->",
"index",
"=",
"$",
"index",
";",
"return",
"$",
"metadata",
";",
"}"
]
| Gets a new instance with the given index. | [
"Gets",
"a",
"new",
"instance",
"with",
"the",
"given",
"index",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Bridge/Elasticsearch/Metadata/Document/DocumentMetadata.php#L41-L47 | train |
api-platform/core | src/Bridge/Elasticsearch/Metadata/Document/DocumentMetadata.php | DocumentMetadata.withType | public function withType(string $type): self
{
$metadata = clone $this;
$metadata->type = $type;
return $metadata;
} | php | public function withType(string $type): self
{
$metadata = clone $this;
$metadata->type = $type;
return $metadata;
} | [
"public",
"function",
"withType",
"(",
"string",
"$",
"type",
")",
":",
"self",
"{",
"$",
"metadata",
"=",
"clone",
"$",
"this",
";",
"$",
"metadata",
"->",
"type",
"=",
"$",
"type",
";",
"return",
"$",
"metadata",
";",
"}"
]
| Gets a new instance with the given type. | [
"Gets",
"a",
"new",
"instance",
"with",
"the",
"given",
"type",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Bridge/Elasticsearch/Metadata/Document/DocumentMetadata.php#L60-L66 | train |
api-platform/core | src/EventListener/ReadListener.php | ReadListener.onKernelRequest | public function onKernelRequest(GetResponseEvent $event): void
{
$request = $event->getRequest();
if (
!($attributes = RequestAttributesExtractor::extractAttributes($request))
|| !$attributes['receive']
) {
return;
}
if (null === $filters = $request->attributes->get('_api_filters')) {
$queryString = RequestParser::getQueryString($request);
$filters = $queryString ? RequestParser::parseRequestParams($queryString) : null;
}
$context = null === $filters ? [] : ['filters' => $filters];
if ($this->serializerContextBuilder) {
// Builtin data providers are able to use the serialization context to automatically add join clauses
$context += $normalizationContext = $this->serializerContextBuilder->createFromRequest($request, true, $attributes);
$request->attributes->set('_api_normalization_context', $normalizationContext);
}
if (isset($attributes['collection_operation_name'])) {
$request->attributes->set('data', $request->isMethod('POST') ? null : $this->getCollectionData($attributes, $context));
return;
}
$data = [];
if ($this->identifierConverter) {
$context[IdentifierConverterInterface::HAS_IDENTIFIER_CONVERTER] = true;
}
try {
$identifiers = $this->extractIdentifiers($request->attributes->all(), $attributes);
if (isset($attributes['item_operation_name'])) {
$data = $this->getItemData($identifiers, $attributes, $context);
} elseif (isset($attributes['subresource_operation_name'])) {
// Legacy
if (null === $this->subresourceDataProvider) {
throw new RuntimeException('No subresource data provider.');
}
$data = $this->getSubresourceData($identifiers, $attributes, $context);
}
} catch (InvalidIdentifierException $e) {
throw new NotFoundHttpException('Not found, because of an invalid identifier configuration', $e);
}
if (null === $data) {
throw new NotFoundHttpException('Not Found');
}
$request->attributes->set('data', $data);
} | php | public function onKernelRequest(GetResponseEvent $event): void
{
$request = $event->getRequest();
if (
!($attributes = RequestAttributesExtractor::extractAttributes($request))
|| !$attributes['receive']
) {
return;
}
if (null === $filters = $request->attributes->get('_api_filters')) {
$queryString = RequestParser::getQueryString($request);
$filters = $queryString ? RequestParser::parseRequestParams($queryString) : null;
}
$context = null === $filters ? [] : ['filters' => $filters];
if ($this->serializerContextBuilder) {
// Builtin data providers are able to use the serialization context to automatically add join clauses
$context += $normalizationContext = $this->serializerContextBuilder->createFromRequest($request, true, $attributes);
$request->attributes->set('_api_normalization_context', $normalizationContext);
}
if (isset($attributes['collection_operation_name'])) {
$request->attributes->set('data', $request->isMethod('POST') ? null : $this->getCollectionData($attributes, $context));
return;
}
$data = [];
if ($this->identifierConverter) {
$context[IdentifierConverterInterface::HAS_IDENTIFIER_CONVERTER] = true;
}
try {
$identifiers = $this->extractIdentifiers($request->attributes->all(), $attributes);
if (isset($attributes['item_operation_name'])) {
$data = $this->getItemData($identifiers, $attributes, $context);
} elseif (isset($attributes['subresource_operation_name'])) {
// Legacy
if (null === $this->subresourceDataProvider) {
throw new RuntimeException('No subresource data provider.');
}
$data = $this->getSubresourceData($identifiers, $attributes, $context);
}
} catch (InvalidIdentifierException $e) {
throw new NotFoundHttpException('Not found, because of an invalid identifier configuration', $e);
}
if (null === $data) {
throw new NotFoundHttpException('Not Found');
}
$request->attributes->set('data', $data);
} | [
"public",
"function",
"onKernelRequest",
"(",
"GetResponseEvent",
"$",
"event",
")",
":",
"void",
"{",
"$",
"request",
"=",
"$",
"event",
"->",
"getRequest",
"(",
")",
";",
"if",
"(",
"!",
"(",
"$",
"attributes",
"=",
"RequestAttributesExtractor",
"::",
"extractAttributes",
"(",
"$",
"request",
")",
")",
"||",
"!",
"$",
"attributes",
"[",
"'receive'",
"]",
")",
"{",
"return",
";",
"}",
"if",
"(",
"null",
"===",
"$",
"filters",
"=",
"$",
"request",
"->",
"attributes",
"->",
"get",
"(",
"'_api_filters'",
")",
")",
"{",
"$",
"queryString",
"=",
"RequestParser",
"::",
"getQueryString",
"(",
"$",
"request",
")",
";",
"$",
"filters",
"=",
"$",
"queryString",
"?",
"RequestParser",
"::",
"parseRequestParams",
"(",
"$",
"queryString",
")",
":",
"null",
";",
"}",
"$",
"context",
"=",
"null",
"===",
"$",
"filters",
"?",
"[",
"]",
":",
"[",
"'filters'",
"=>",
"$",
"filters",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"serializerContextBuilder",
")",
"{",
"// Builtin data providers are able to use the serialization context to automatically add join clauses",
"$",
"context",
"+=",
"$",
"normalizationContext",
"=",
"$",
"this",
"->",
"serializerContextBuilder",
"->",
"createFromRequest",
"(",
"$",
"request",
",",
"true",
",",
"$",
"attributes",
")",
";",
"$",
"request",
"->",
"attributes",
"->",
"set",
"(",
"'_api_normalization_context'",
",",
"$",
"normalizationContext",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"attributes",
"[",
"'collection_operation_name'",
"]",
")",
")",
"{",
"$",
"request",
"->",
"attributes",
"->",
"set",
"(",
"'data'",
",",
"$",
"request",
"->",
"isMethod",
"(",
"'POST'",
")",
"?",
"null",
":",
"$",
"this",
"->",
"getCollectionData",
"(",
"$",
"attributes",
",",
"$",
"context",
")",
")",
";",
"return",
";",
"}",
"$",
"data",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"identifierConverter",
")",
"{",
"$",
"context",
"[",
"IdentifierConverterInterface",
"::",
"HAS_IDENTIFIER_CONVERTER",
"]",
"=",
"true",
";",
"}",
"try",
"{",
"$",
"identifiers",
"=",
"$",
"this",
"->",
"extractIdentifiers",
"(",
"$",
"request",
"->",
"attributes",
"->",
"all",
"(",
")",
",",
"$",
"attributes",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"attributes",
"[",
"'item_operation_name'",
"]",
")",
")",
"{",
"$",
"data",
"=",
"$",
"this",
"->",
"getItemData",
"(",
"$",
"identifiers",
",",
"$",
"attributes",
",",
"$",
"context",
")",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"attributes",
"[",
"'subresource_operation_name'",
"]",
")",
")",
"{",
"// Legacy",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"subresourceDataProvider",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'No subresource data provider.'",
")",
";",
"}",
"$",
"data",
"=",
"$",
"this",
"->",
"getSubresourceData",
"(",
"$",
"identifiers",
",",
"$",
"attributes",
",",
"$",
"context",
")",
";",
"}",
"}",
"catch",
"(",
"InvalidIdentifierException",
"$",
"e",
")",
"{",
"throw",
"new",
"NotFoundHttpException",
"(",
"'Not found, because of an invalid identifier configuration'",
",",
"$",
"e",
")",
";",
"}",
"if",
"(",
"null",
"===",
"$",
"data",
")",
"{",
"throw",
"new",
"NotFoundHttpException",
"(",
"'Not Found'",
")",
";",
"}",
"$",
"request",
"->",
"attributes",
"->",
"set",
"(",
"'data'",
",",
"$",
"data",
")",
";",
"}"
]
| Calls the data provider and sets the data attribute.
@throws NotFoundHttpException | [
"Calls",
"the",
"data",
"provider",
"and",
"sets",
"the",
"data",
"attribute",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/EventListener/ReadListener.php#L54-L110 | train |
api-platform/core | src/Bridge/Doctrine/Orm/Filter/RangeFilter.php | RangeFilter.addWhere | protected function addWhere(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, $alias, $field, $operator, $value)
{
$valueParameter = $queryNameGenerator->generateParameterName($field);
switch ($operator) {
case self::PARAMETER_BETWEEN:
$rangeValue = explode('..', $value);
$rangeValue = $this->normalizeBetweenValues($rangeValue);
if (null === $rangeValue) {
return;
}
$queryBuilder
->andWhere(sprintf('%1$s.%2$s BETWEEN :%3$s_1 AND :%3$s_2', $alias, $field, $valueParameter))
->setParameter(sprintf('%s_1', $valueParameter), $rangeValue[0])
->setParameter(sprintf('%s_2', $valueParameter), $rangeValue[1]);
break;
case self::PARAMETER_GREATER_THAN:
$value = $this->normalizeValue($value, $operator);
if (null === $value) {
return;
}
$queryBuilder
->andWhere(sprintf('%s.%s > :%s', $alias, $field, $valueParameter))
->setParameter($valueParameter, $value);
break;
case self::PARAMETER_GREATER_THAN_OR_EQUAL:
$value = $this->normalizeValue($value, $operator);
if (null === $value) {
return;
}
$queryBuilder
->andWhere(sprintf('%s.%s >= :%s', $alias, $field, $valueParameter))
->setParameter($valueParameter, $value);
break;
case self::PARAMETER_LESS_THAN:
$value = $this->normalizeValue($value, $operator);
if (null === $value) {
return;
}
$queryBuilder
->andWhere(sprintf('%s.%s < :%s', $alias, $field, $valueParameter))
->setParameter($valueParameter, $value);
break;
case self::PARAMETER_LESS_THAN_OR_EQUAL:
$value = $this->normalizeValue($value, $operator);
if (null === $value) {
return;
}
$queryBuilder
->andWhere(sprintf('%s.%s <= :%s', $alias, $field, $valueParameter))
->setParameter($valueParameter, $value);
break;
}
} | php | protected function addWhere(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, $alias, $field, $operator, $value)
{
$valueParameter = $queryNameGenerator->generateParameterName($field);
switch ($operator) {
case self::PARAMETER_BETWEEN:
$rangeValue = explode('..', $value);
$rangeValue = $this->normalizeBetweenValues($rangeValue);
if (null === $rangeValue) {
return;
}
$queryBuilder
->andWhere(sprintf('%1$s.%2$s BETWEEN :%3$s_1 AND :%3$s_2', $alias, $field, $valueParameter))
->setParameter(sprintf('%s_1', $valueParameter), $rangeValue[0])
->setParameter(sprintf('%s_2', $valueParameter), $rangeValue[1]);
break;
case self::PARAMETER_GREATER_THAN:
$value = $this->normalizeValue($value, $operator);
if (null === $value) {
return;
}
$queryBuilder
->andWhere(sprintf('%s.%s > :%s', $alias, $field, $valueParameter))
->setParameter($valueParameter, $value);
break;
case self::PARAMETER_GREATER_THAN_OR_EQUAL:
$value = $this->normalizeValue($value, $operator);
if (null === $value) {
return;
}
$queryBuilder
->andWhere(sprintf('%s.%s >= :%s', $alias, $field, $valueParameter))
->setParameter($valueParameter, $value);
break;
case self::PARAMETER_LESS_THAN:
$value = $this->normalizeValue($value, $operator);
if (null === $value) {
return;
}
$queryBuilder
->andWhere(sprintf('%s.%s < :%s', $alias, $field, $valueParameter))
->setParameter($valueParameter, $value);
break;
case self::PARAMETER_LESS_THAN_OR_EQUAL:
$value = $this->normalizeValue($value, $operator);
if (null === $value) {
return;
}
$queryBuilder
->andWhere(sprintf('%s.%s <= :%s', $alias, $field, $valueParameter))
->setParameter($valueParameter, $value);
break;
}
} | [
"protected",
"function",
"addWhere",
"(",
"QueryBuilder",
"$",
"queryBuilder",
",",
"QueryNameGeneratorInterface",
"$",
"queryNameGenerator",
",",
"$",
"alias",
",",
"$",
"field",
",",
"$",
"operator",
",",
"$",
"value",
")",
"{",
"$",
"valueParameter",
"=",
"$",
"queryNameGenerator",
"->",
"generateParameterName",
"(",
"$",
"field",
")",
";",
"switch",
"(",
"$",
"operator",
")",
"{",
"case",
"self",
"::",
"PARAMETER_BETWEEN",
":",
"$",
"rangeValue",
"=",
"explode",
"(",
"'..'",
",",
"$",
"value",
")",
";",
"$",
"rangeValue",
"=",
"$",
"this",
"->",
"normalizeBetweenValues",
"(",
"$",
"rangeValue",
")",
";",
"if",
"(",
"null",
"===",
"$",
"rangeValue",
")",
"{",
"return",
";",
"}",
"$",
"queryBuilder",
"->",
"andWhere",
"(",
"sprintf",
"(",
"'%1$s.%2$s BETWEEN :%3$s_1 AND :%3$s_2'",
",",
"$",
"alias",
",",
"$",
"field",
",",
"$",
"valueParameter",
")",
")",
"->",
"setParameter",
"(",
"sprintf",
"(",
"'%s_1'",
",",
"$",
"valueParameter",
")",
",",
"$",
"rangeValue",
"[",
"0",
"]",
")",
"->",
"setParameter",
"(",
"sprintf",
"(",
"'%s_2'",
",",
"$",
"valueParameter",
")",
",",
"$",
"rangeValue",
"[",
"1",
"]",
")",
";",
"break",
";",
"case",
"self",
"::",
"PARAMETER_GREATER_THAN",
":",
"$",
"value",
"=",
"$",
"this",
"->",
"normalizeValue",
"(",
"$",
"value",
",",
"$",
"operator",
")",
";",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"{",
"return",
";",
"}",
"$",
"queryBuilder",
"->",
"andWhere",
"(",
"sprintf",
"(",
"'%s.%s > :%s'",
",",
"$",
"alias",
",",
"$",
"field",
",",
"$",
"valueParameter",
")",
")",
"->",
"setParameter",
"(",
"$",
"valueParameter",
",",
"$",
"value",
")",
";",
"break",
";",
"case",
"self",
"::",
"PARAMETER_GREATER_THAN_OR_EQUAL",
":",
"$",
"value",
"=",
"$",
"this",
"->",
"normalizeValue",
"(",
"$",
"value",
",",
"$",
"operator",
")",
";",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"{",
"return",
";",
"}",
"$",
"queryBuilder",
"->",
"andWhere",
"(",
"sprintf",
"(",
"'%s.%s >= :%s'",
",",
"$",
"alias",
",",
"$",
"field",
",",
"$",
"valueParameter",
")",
")",
"->",
"setParameter",
"(",
"$",
"valueParameter",
",",
"$",
"value",
")",
";",
"break",
";",
"case",
"self",
"::",
"PARAMETER_LESS_THAN",
":",
"$",
"value",
"=",
"$",
"this",
"->",
"normalizeValue",
"(",
"$",
"value",
",",
"$",
"operator",
")",
";",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"{",
"return",
";",
"}",
"$",
"queryBuilder",
"->",
"andWhere",
"(",
"sprintf",
"(",
"'%s.%s < :%s'",
",",
"$",
"alias",
",",
"$",
"field",
",",
"$",
"valueParameter",
")",
")",
"->",
"setParameter",
"(",
"$",
"valueParameter",
",",
"$",
"value",
")",
";",
"break",
";",
"case",
"self",
"::",
"PARAMETER_LESS_THAN_OR_EQUAL",
":",
"$",
"value",
"=",
"$",
"this",
"->",
"normalizeValue",
"(",
"$",
"value",
",",
"$",
"operator",
")",
";",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"{",
"return",
";",
"}",
"$",
"queryBuilder",
"->",
"andWhere",
"(",
"sprintf",
"(",
"'%s.%s <= :%s'",
",",
"$",
"alias",
",",
"$",
"field",
",",
"$",
"valueParameter",
")",
")",
"->",
"setParameter",
"(",
"$",
"valueParameter",
",",
"$",
"value",
")",
";",
"break",
";",
"}",
"}"
]
| Adds the where clause according to the operator.
@param string $alias
@param string $field
@param string $operator
@param string $value | [
"Adds",
"the",
"where",
"clause",
"according",
"to",
"the",
"operator",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Bridge/Doctrine/Orm/Filter/RangeFilter.php#L75-L139 | train |
api-platform/core | src/Bridge/Symfony/Bundle/Action/SwaggerUiAction.php | SwaggerUiAction.getContext | private function getContext(Request $request, Documentation $documentation): array
{
$context = [
'title' => $this->title,
'description' => $this->description,
'formats' => $this->formats,
'showWebby' => $this->showWebby,
'swaggerUiEnabled' => $this->swaggerUiEnabled,
'reDocEnabled' => $this->reDocEnabled,
'graphqlEnabled' => $this->graphqlEnabled,
];
$swaggerContext = ['spec_version' => $request->query->getInt('spec_version', 2)];
if ('' !== $baseUrl = $request->getBaseUrl()) {
$swaggerContext['base_url'] = $baseUrl;
}
$swaggerData = [
'url' => $this->urlGenerator->generate('api_doc', ['format' => 'json']),
'spec' => $this->normalizer->normalize($documentation, 'json', $swaggerContext),
];
$swaggerData['oauth'] = [
'enabled' => $this->oauthEnabled,
'clientId' => $this->oauthClientId,
'clientSecret' => $this->oauthClientSecret,
'type' => $this->oauthType,
'flow' => $this->oauthFlow,
'tokenUrl' => $this->oauthTokenUrl,
'authorizationUrl' => $this->oauthAuthorizationUrl,
'scopes' => $this->oauthScopes,
];
if ($request->isMethodSafe(false) && null !== $resourceClass = $request->attributes->get('_api_resource_class')) {
$swaggerData['id'] = $request->attributes->get('id');
$swaggerData['queryParameters'] = $request->query->all();
$metadata = $this->resourceMetadataFactory->create($resourceClass);
$swaggerData['shortName'] = $metadata->getShortName();
if (null !== $collectionOperationName = $request->attributes->get('_api_collection_operation_name')) {
$swaggerData['operationId'] = sprintf('%s%sCollection', $collectionOperationName, ucfirst($swaggerData['shortName']));
} elseif (null !== $itemOperationName = $request->attributes->get('_api_item_operation_name')) {
$swaggerData['operationId'] = sprintf('%s%sItem', $itemOperationName, ucfirst($swaggerData['shortName']));
} elseif (null !== $subresourceOperationContext = $request->attributes->get('_api_subresource_context')) {
$swaggerData['operationId'] = $subresourceOperationContext['operationId'];
}
[$swaggerData['path'], $swaggerData['method']] = $this->getPathAndMethod($swaggerData);
}
return $context + ['swagger_data' => $swaggerData];
} | php | private function getContext(Request $request, Documentation $documentation): array
{
$context = [
'title' => $this->title,
'description' => $this->description,
'formats' => $this->formats,
'showWebby' => $this->showWebby,
'swaggerUiEnabled' => $this->swaggerUiEnabled,
'reDocEnabled' => $this->reDocEnabled,
'graphqlEnabled' => $this->graphqlEnabled,
];
$swaggerContext = ['spec_version' => $request->query->getInt('spec_version', 2)];
if ('' !== $baseUrl = $request->getBaseUrl()) {
$swaggerContext['base_url'] = $baseUrl;
}
$swaggerData = [
'url' => $this->urlGenerator->generate('api_doc', ['format' => 'json']),
'spec' => $this->normalizer->normalize($documentation, 'json', $swaggerContext),
];
$swaggerData['oauth'] = [
'enabled' => $this->oauthEnabled,
'clientId' => $this->oauthClientId,
'clientSecret' => $this->oauthClientSecret,
'type' => $this->oauthType,
'flow' => $this->oauthFlow,
'tokenUrl' => $this->oauthTokenUrl,
'authorizationUrl' => $this->oauthAuthorizationUrl,
'scopes' => $this->oauthScopes,
];
if ($request->isMethodSafe(false) && null !== $resourceClass = $request->attributes->get('_api_resource_class')) {
$swaggerData['id'] = $request->attributes->get('id');
$swaggerData['queryParameters'] = $request->query->all();
$metadata = $this->resourceMetadataFactory->create($resourceClass);
$swaggerData['shortName'] = $metadata->getShortName();
if (null !== $collectionOperationName = $request->attributes->get('_api_collection_operation_name')) {
$swaggerData['operationId'] = sprintf('%s%sCollection', $collectionOperationName, ucfirst($swaggerData['shortName']));
} elseif (null !== $itemOperationName = $request->attributes->get('_api_item_operation_name')) {
$swaggerData['operationId'] = sprintf('%s%sItem', $itemOperationName, ucfirst($swaggerData['shortName']));
} elseif (null !== $subresourceOperationContext = $request->attributes->get('_api_subresource_context')) {
$swaggerData['operationId'] = $subresourceOperationContext['operationId'];
}
[$swaggerData['path'], $swaggerData['method']] = $this->getPathAndMethod($swaggerData);
}
return $context + ['swagger_data' => $swaggerData];
} | [
"private",
"function",
"getContext",
"(",
"Request",
"$",
"request",
",",
"Documentation",
"$",
"documentation",
")",
":",
"array",
"{",
"$",
"context",
"=",
"[",
"'title'",
"=>",
"$",
"this",
"->",
"title",
",",
"'description'",
"=>",
"$",
"this",
"->",
"description",
",",
"'formats'",
"=>",
"$",
"this",
"->",
"formats",
",",
"'showWebby'",
"=>",
"$",
"this",
"->",
"showWebby",
",",
"'swaggerUiEnabled'",
"=>",
"$",
"this",
"->",
"swaggerUiEnabled",
",",
"'reDocEnabled'",
"=>",
"$",
"this",
"->",
"reDocEnabled",
",",
"'graphqlEnabled'",
"=>",
"$",
"this",
"->",
"graphqlEnabled",
",",
"]",
";",
"$",
"swaggerContext",
"=",
"[",
"'spec_version'",
"=>",
"$",
"request",
"->",
"query",
"->",
"getInt",
"(",
"'spec_version'",
",",
"2",
")",
"]",
";",
"if",
"(",
"''",
"!==",
"$",
"baseUrl",
"=",
"$",
"request",
"->",
"getBaseUrl",
"(",
")",
")",
"{",
"$",
"swaggerContext",
"[",
"'base_url'",
"]",
"=",
"$",
"baseUrl",
";",
"}",
"$",
"swaggerData",
"=",
"[",
"'url'",
"=>",
"$",
"this",
"->",
"urlGenerator",
"->",
"generate",
"(",
"'api_doc'",
",",
"[",
"'format'",
"=>",
"'json'",
"]",
")",
",",
"'spec'",
"=>",
"$",
"this",
"->",
"normalizer",
"->",
"normalize",
"(",
"$",
"documentation",
",",
"'json'",
",",
"$",
"swaggerContext",
")",
",",
"]",
";",
"$",
"swaggerData",
"[",
"'oauth'",
"]",
"=",
"[",
"'enabled'",
"=>",
"$",
"this",
"->",
"oauthEnabled",
",",
"'clientId'",
"=>",
"$",
"this",
"->",
"oauthClientId",
",",
"'clientSecret'",
"=>",
"$",
"this",
"->",
"oauthClientSecret",
",",
"'type'",
"=>",
"$",
"this",
"->",
"oauthType",
",",
"'flow'",
"=>",
"$",
"this",
"->",
"oauthFlow",
",",
"'tokenUrl'",
"=>",
"$",
"this",
"->",
"oauthTokenUrl",
",",
"'authorizationUrl'",
"=>",
"$",
"this",
"->",
"oauthAuthorizationUrl",
",",
"'scopes'",
"=>",
"$",
"this",
"->",
"oauthScopes",
",",
"]",
";",
"if",
"(",
"$",
"request",
"->",
"isMethodSafe",
"(",
"false",
")",
"&&",
"null",
"!==",
"$",
"resourceClass",
"=",
"$",
"request",
"->",
"attributes",
"->",
"get",
"(",
"'_api_resource_class'",
")",
")",
"{",
"$",
"swaggerData",
"[",
"'id'",
"]",
"=",
"$",
"request",
"->",
"attributes",
"->",
"get",
"(",
"'id'",
")",
";",
"$",
"swaggerData",
"[",
"'queryParameters'",
"]",
"=",
"$",
"request",
"->",
"query",
"->",
"all",
"(",
")",
";",
"$",
"metadata",
"=",
"$",
"this",
"->",
"resourceMetadataFactory",
"->",
"create",
"(",
"$",
"resourceClass",
")",
";",
"$",
"swaggerData",
"[",
"'shortName'",
"]",
"=",
"$",
"metadata",
"->",
"getShortName",
"(",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"collectionOperationName",
"=",
"$",
"request",
"->",
"attributes",
"->",
"get",
"(",
"'_api_collection_operation_name'",
")",
")",
"{",
"$",
"swaggerData",
"[",
"'operationId'",
"]",
"=",
"sprintf",
"(",
"'%s%sCollection'",
",",
"$",
"collectionOperationName",
",",
"ucfirst",
"(",
"$",
"swaggerData",
"[",
"'shortName'",
"]",
")",
")",
";",
"}",
"elseif",
"(",
"null",
"!==",
"$",
"itemOperationName",
"=",
"$",
"request",
"->",
"attributes",
"->",
"get",
"(",
"'_api_item_operation_name'",
")",
")",
"{",
"$",
"swaggerData",
"[",
"'operationId'",
"]",
"=",
"sprintf",
"(",
"'%s%sItem'",
",",
"$",
"itemOperationName",
",",
"ucfirst",
"(",
"$",
"swaggerData",
"[",
"'shortName'",
"]",
")",
")",
";",
"}",
"elseif",
"(",
"null",
"!==",
"$",
"subresourceOperationContext",
"=",
"$",
"request",
"->",
"attributes",
"->",
"get",
"(",
"'_api_subresource_context'",
")",
")",
"{",
"$",
"swaggerData",
"[",
"'operationId'",
"]",
"=",
"$",
"subresourceOperationContext",
"[",
"'operationId'",
"]",
";",
"}",
"[",
"$",
"swaggerData",
"[",
"'path'",
"]",
",",
"$",
"swaggerData",
"[",
"'method'",
"]",
"]",
"=",
"$",
"this",
"->",
"getPathAndMethod",
"(",
"$",
"swaggerData",
")",
";",
"}",
"return",
"$",
"context",
"+",
"[",
"'swagger_data'",
"=>",
"$",
"swaggerData",
"]",
";",
"}"
]
| Gets the base Twig context. | [
"Gets",
"the",
"base",
"Twig",
"context",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Bridge/Symfony/Bundle/Action/SwaggerUiAction.php#L116-L168 | train |
api-platform/core | src/Bridge/Doctrine/Orm/Util/QueryChecker.php | QueryChecker.hasRootEntityWithForeignKeyIdentifier | public static function hasRootEntityWithForeignKeyIdentifier(QueryBuilder $queryBuilder, ManagerRegistry $managerRegistry): bool
{
foreach ($queryBuilder->getRootEntities() as $rootEntity) {
/** @var ClassMetadata $rootMetadata */
$rootMetadata = $managerRegistry
->getManagerForClass($rootEntity)
->getClassMetadata($rootEntity);
if ($rootMetadata->containsForeignIdentifier) {
return true;
}
}
return false;
} | php | public static function hasRootEntityWithForeignKeyIdentifier(QueryBuilder $queryBuilder, ManagerRegistry $managerRegistry): bool
{
foreach ($queryBuilder->getRootEntities() as $rootEntity) {
/** @var ClassMetadata $rootMetadata */
$rootMetadata = $managerRegistry
->getManagerForClass($rootEntity)
->getClassMetadata($rootEntity);
if ($rootMetadata->containsForeignIdentifier) {
return true;
}
}
return false;
} | [
"public",
"static",
"function",
"hasRootEntityWithForeignKeyIdentifier",
"(",
"QueryBuilder",
"$",
"queryBuilder",
",",
"ManagerRegistry",
"$",
"managerRegistry",
")",
":",
"bool",
"{",
"foreach",
"(",
"$",
"queryBuilder",
"->",
"getRootEntities",
"(",
")",
"as",
"$",
"rootEntity",
")",
"{",
"/** @var ClassMetadata $rootMetadata */",
"$",
"rootMetadata",
"=",
"$",
"managerRegistry",
"->",
"getManagerForClass",
"(",
"$",
"rootEntity",
")",
"->",
"getClassMetadata",
"(",
"$",
"rootEntity",
")",
";",
"if",
"(",
"$",
"rootMetadata",
"->",
"containsForeignIdentifier",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
]
| Determines whether the QueryBuilder has any root entity with foreign key identifier. | [
"Determines",
"whether",
"the",
"QueryBuilder",
"has",
"any",
"root",
"entity",
"with",
"foreign",
"key",
"identifier",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Bridge/Doctrine/Orm/Util/QueryChecker.php#L46-L60 | train |
api-platform/core | src/Bridge/Doctrine/Orm/Util/QueryChecker.php | QueryChecker.hasRootEntityWithCompositeIdentifier | public static function hasRootEntityWithCompositeIdentifier(QueryBuilder $queryBuilder, ManagerRegistry $managerRegistry): bool
{
foreach ($queryBuilder->getRootEntities() as $rootEntity) {
/** @var ClassMetadata $rootMetadata */
$rootMetadata = $managerRegistry
->getManagerForClass($rootEntity)
->getClassMetadata($rootEntity);
if ($rootMetadata->isIdentifierComposite) {
return true;
}
}
return false;
} | php | public static function hasRootEntityWithCompositeIdentifier(QueryBuilder $queryBuilder, ManagerRegistry $managerRegistry): bool
{
foreach ($queryBuilder->getRootEntities() as $rootEntity) {
/** @var ClassMetadata $rootMetadata */
$rootMetadata = $managerRegistry
->getManagerForClass($rootEntity)
->getClassMetadata($rootEntity);
if ($rootMetadata->isIdentifierComposite) {
return true;
}
}
return false;
} | [
"public",
"static",
"function",
"hasRootEntityWithCompositeIdentifier",
"(",
"QueryBuilder",
"$",
"queryBuilder",
",",
"ManagerRegistry",
"$",
"managerRegistry",
")",
":",
"bool",
"{",
"foreach",
"(",
"$",
"queryBuilder",
"->",
"getRootEntities",
"(",
")",
"as",
"$",
"rootEntity",
")",
"{",
"/** @var ClassMetadata $rootMetadata */",
"$",
"rootMetadata",
"=",
"$",
"managerRegistry",
"->",
"getManagerForClass",
"(",
"$",
"rootEntity",
")",
"->",
"getClassMetadata",
"(",
"$",
"rootEntity",
")",
";",
"if",
"(",
"$",
"rootMetadata",
"->",
"isIdentifierComposite",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
]
| Determines whether the QueryBuilder has any composite identifier. | [
"Determines",
"whether",
"the",
"QueryBuilder",
"has",
"any",
"composite",
"identifier",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Bridge/Doctrine/Orm/Util/QueryChecker.php#L65-L79 | train |
api-platform/core | src/Bridge/Doctrine/Orm/Util/QueryChecker.php | QueryChecker.hasLeftJoin | public static function hasLeftJoin(QueryBuilder $queryBuilder): bool
{
foreach ($queryBuilder->getDQLPart('join') as $joins) {
foreach ($joins as $join) {
if (Join::LEFT_JOIN === $join->getJoinType()) {
return true;
}
}
}
return false;
} | php | public static function hasLeftJoin(QueryBuilder $queryBuilder): bool
{
foreach ($queryBuilder->getDQLPart('join') as $joins) {
foreach ($joins as $join) {
if (Join::LEFT_JOIN === $join->getJoinType()) {
return true;
}
}
}
return false;
} | [
"public",
"static",
"function",
"hasLeftJoin",
"(",
"QueryBuilder",
"$",
"queryBuilder",
")",
":",
"bool",
"{",
"foreach",
"(",
"$",
"queryBuilder",
"->",
"getDQLPart",
"(",
"'join'",
")",
"as",
"$",
"joins",
")",
"{",
"foreach",
"(",
"$",
"joins",
"as",
"$",
"join",
")",
"{",
"if",
"(",
"Join",
"::",
"LEFT_JOIN",
"===",
"$",
"join",
"->",
"getJoinType",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}"
]
| Determines whether the QueryBuilder already has a left join. | [
"Determines",
"whether",
"the",
"QueryBuilder",
"already",
"has",
"a",
"left",
"join",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Bridge/Doctrine/Orm/Util/QueryChecker.php#L168-L179 | train |
api-platform/core | src/Bridge/Doctrine/Orm/Util/QueryChecker.php | QueryChecker.hasJoinedToManyAssociation | public static function hasJoinedToManyAssociation(QueryBuilder $queryBuilder, ManagerRegistry $managerRegistry): bool
{
if (
0 === \count($queryBuilder->getDQLPart('join'))
) {
return false;
}
$joinAliases = array_diff($queryBuilder->getAllAliases(), $queryBuilder->getRootAliases());
if (0 === \count($joinAliases)) {
return false;
}
foreach ($joinAliases as $joinAlias) {
foreach (QueryBuilderHelper::traverseJoins($joinAlias, $queryBuilder, $managerRegistry) as $alias => [$metadata, $association]) {
if (null !== $association && $metadata->isCollectionValuedAssociation($association)) {
return true;
}
}
}
return false;
} | php | public static function hasJoinedToManyAssociation(QueryBuilder $queryBuilder, ManagerRegistry $managerRegistry): bool
{
if (
0 === \count($queryBuilder->getDQLPart('join'))
) {
return false;
}
$joinAliases = array_diff($queryBuilder->getAllAliases(), $queryBuilder->getRootAliases());
if (0 === \count($joinAliases)) {
return false;
}
foreach ($joinAliases as $joinAlias) {
foreach (QueryBuilderHelper::traverseJoins($joinAlias, $queryBuilder, $managerRegistry) as $alias => [$metadata, $association]) {
if (null !== $association && $metadata->isCollectionValuedAssociation($association)) {
return true;
}
}
}
return false;
} | [
"public",
"static",
"function",
"hasJoinedToManyAssociation",
"(",
"QueryBuilder",
"$",
"queryBuilder",
",",
"ManagerRegistry",
"$",
"managerRegistry",
")",
":",
"bool",
"{",
"if",
"(",
"0",
"===",
"\\",
"count",
"(",
"$",
"queryBuilder",
"->",
"getDQLPart",
"(",
"'join'",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"joinAliases",
"=",
"array_diff",
"(",
"$",
"queryBuilder",
"->",
"getAllAliases",
"(",
")",
",",
"$",
"queryBuilder",
"->",
"getRootAliases",
"(",
")",
")",
";",
"if",
"(",
"0",
"===",
"\\",
"count",
"(",
"$",
"joinAliases",
")",
")",
"{",
"return",
"false",
";",
"}",
"foreach",
"(",
"$",
"joinAliases",
"as",
"$",
"joinAlias",
")",
"{",
"foreach",
"(",
"QueryBuilderHelper",
"::",
"traverseJoins",
"(",
"$",
"joinAlias",
",",
"$",
"queryBuilder",
",",
"$",
"managerRegistry",
")",
"as",
"$",
"alias",
"=>",
"[",
"$",
"metadata",
",",
"$",
"association",
"]",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"association",
"&&",
"$",
"metadata",
"->",
"isCollectionValuedAssociation",
"(",
"$",
"association",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}"
]
| Determines whether the QueryBuilder has a joined to-many association. | [
"Determines",
"whether",
"the",
"QueryBuilder",
"has",
"a",
"joined",
"to",
"-",
"many",
"association",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Bridge/Doctrine/Orm/Util/QueryChecker.php#L184-L206 | train |
api-platform/core | src/Util/ErrorFormatGuesser.php | ErrorFormatGuesser.guessErrorFormat | public static function guessErrorFormat(Request $request, array $errorFormats): array
{
$requestFormat = $request->getRequestFormat('');
if ('' !== $requestFormat && isset($errorFormats[$requestFormat])) {
return ['key' => $requestFormat, 'value' => $errorFormats[$requestFormat]];
}
$requestMimeTypes = Request::getMimeTypes($request->getRequestFormat());
$defaultFormat = [];
foreach ($errorFormats as $format => $errorMimeTypes) {
if (array_intersect($requestMimeTypes, $errorMimeTypes)) {
return ['key' => $format, 'value' => $errorMimeTypes];
}
if (!$defaultFormat) {
$defaultFormat = ['key' => $format, 'value' => $errorMimeTypes];
}
}
return $defaultFormat;
} | php | public static function guessErrorFormat(Request $request, array $errorFormats): array
{
$requestFormat = $request->getRequestFormat('');
if ('' !== $requestFormat && isset($errorFormats[$requestFormat])) {
return ['key' => $requestFormat, 'value' => $errorFormats[$requestFormat]];
}
$requestMimeTypes = Request::getMimeTypes($request->getRequestFormat());
$defaultFormat = [];
foreach ($errorFormats as $format => $errorMimeTypes) {
if (array_intersect($requestMimeTypes, $errorMimeTypes)) {
return ['key' => $format, 'value' => $errorMimeTypes];
}
if (!$defaultFormat) {
$defaultFormat = ['key' => $format, 'value' => $errorMimeTypes];
}
}
return $defaultFormat;
} | [
"public",
"static",
"function",
"guessErrorFormat",
"(",
"Request",
"$",
"request",
",",
"array",
"$",
"errorFormats",
")",
":",
"array",
"{",
"$",
"requestFormat",
"=",
"$",
"request",
"->",
"getRequestFormat",
"(",
"''",
")",
";",
"if",
"(",
"''",
"!==",
"$",
"requestFormat",
"&&",
"isset",
"(",
"$",
"errorFormats",
"[",
"$",
"requestFormat",
"]",
")",
")",
"{",
"return",
"[",
"'key'",
"=>",
"$",
"requestFormat",
",",
"'value'",
"=>",
"$",
"errorFormats",
"[",
"$",
"requestFormat",
"]",
"]",
";",
"}",
"$",
"requestMimeTypes",
"=",
"Request",
"::",
"getMimeTypes",
"(",
"$",
"request",
"->",
"getRequestFormat",
"(",
")",
")",
";",
"$",
"defaultFormat",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"errorFormats",
"as",
"$",
"format",
"=>",
"$",
"errorMimeTypes",
")",
"{",
"if",
"(",
"array_intersect",
"(",
"$",
"requestMimeTypes",
",",
"$",
"errorMimeTypes",
")",
")",
"{",
"return",
"[",
"'key'",
"=>",
"$",
"format",
",",
"'value'",
"=>",
"$",
"errorMimeTypes",
"]",
";",
"}",
"if",
"(",
"!",
"$",
"defaultFormat",
")",
"{",
"$",
"defaultFormat",
"=",
"[",
"'key'",
"=>",
"$",
"format",
",",
"'value'",
"=>",
"$",
"errorMimeTypes",
"]",
";",
"}",
"}",
"return",
"$",
"defaultFormat",
";",
"}"
]
| Get the error format and its associated MIME type. | [
"Get",
"the",
"error",
"format",
"and",
"its",
"associated",
"MIME",
"type",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Util/ErrorFormatGuesser.php#L32-L54 | train |
api-platform/core | src/Bridge/Doctrine/Orm/Extension/EagerLoadingExtension.php | EagerLoadingExtension.getNormalizationContext | private function getNormalizationContext(string $resourceClass, string $contextType, array $options): array
{
if (null !== $this->requestStack && null !== $this->serializerContextBuilder && null !== $request = $this->requestStack->getCurrentRequest()) {
return $this->serializerContextBuilder->createFromRequest($request, 'normalization_context' === $contextType);
}
$resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
if (isset($options['collection_operation_name'])) {
$context = $resourceMetadata->getCollectionOperationAttribute($options['collection_operation_name'], $contextType, null, true);
} elseif (isset($options['item_operation_name'])) {
$context = $resourceMetadata->getItemOperationAttribute($options['item_operation_name'], $contextType, null, true);
} else {
$context = $resourceMetadata->getAttribute($contextType);
}
return $context ?? [];
} | php | private function getNormalizationContext(string $resourceClass, string $contextType, array $options): array
{
if (null !== $this->requestStack && null !== $this->serializerContextBuilder && null !== $request = $this->requestStack->getCurrentRequest()) {
return $this->serializerContextBuilder->createFromRequest($request, 'normalization_context' === $contextType);
}
$resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
if (isset($options['collection_operation_name'])) {
$context = $resourceMetadata->getCollectionOperationAttribute($options['collection_operation_name'], $contextType, null, true);
} elseif (isset($options['item_operation_name'])) {
$context = $resourceMetadata->getItemOperationAttribute($options['item_operation_name'], $contextType, null, true);
} else {
$context = $resourceMetadata->getAttribute($contextType);
}
return $context ?? [];
} | [
"private",
"function",
"getNormalizationContext",
"(",
"string",
"$",
"resourceClass",
",",
"string",
"$",
"contextType",
",",
"array",
"$",
"options",
")",
":",
"array",
"{",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"requestStack",
"&&",
"null",
"!==",
"$",
"this",
"->",
"serializerContextBuilder",
"&&",
"null",
"!==",
"$",
"request",
"=",
"$",
"this",
"->",
"requestStack",
"->",
"getCurrentRequest",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"serializerContextBuilder",
"->",
"createFromRequest",
"(",
"$",
"request",
",",
"'normalization_context'",
"===",
"$",
"contextType",
")",
";",
"}",
"$",
"resourceMetadata",
"=",
"$",
"this",
"->",
"resourceMetadataFactory",
"->",
"create",
"(",
"$",
"resourceClass",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'collection_operation_name'",
"]",
")",
")",
"{",
"$",
"context",
"=",
"$",
"resourceMetadata",
"->",
"getCollectionOperationAttribute",
"(",
"$",
"options",
"[",
"'collection_operation_name'",
"]",
",",
"$",
"contextType",
",",
"null",
",",
"true",
")",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"options",
"[",
"'item_operation_name'",
"]",
")",
")",
"{",
"$",
"context",
"=",
"$",
"resourceMetadata",
"->",
"getItemOperationAttribute",
"(",
"$",
"options",
"[",
"'item_operation_name'",
"]",
",",
"$",
"contextType",
",",
"null",
",",
"true",
")",
";",
"}",
"else",
"{",
"$",
"context",
"=",
"$",
"resourceMetadata",
"->",
"getAttribute",
"(",
"$",
"contextType",
")",
";",
"}",
"return",
"$",
"context",
"??",
"[",
"]",
";",
"}"
]
| Gets the serializer context.
@param string $contextType normalization_context or denormalization_context
@param array $options represents the operation name so that groups are the one of the specific operation | [
"Gets",
"the",
"serializer",
"context",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Bridge/Doctrine/Orm/Extension/EagerLoadingExtension.php#L283-L299 | train |
api-platform/core | src/EventListener/SerializeListener.php | SerializeListener.onKernelView | public function onKernelView(GetResponseForControllerResultEvent $event): void
{
$controllerResult = $event->getControllerResult();
$request = $event->getRequest();
if ($controllerResult instanceof Response || !(($attributes = RequestAttributesExtractor::extractAttributes($request))['respond'] ?? $request->attributes->getBoolean('_api_respond', false))) {
return;
}
if (!$attributes) {
$this->serializeRawData($event, $request, $controllerResult);
return;
}
$context = $this->serializerContextBuilder->createFromRequest($request, true, $attributes);
if (isset($context['output']) && \array_key_exists('class', $context['output']) && null === $context['output']['class']) {
$event->setControllerResult(null);
return;
}
if ($included = $request->attributes->get('_api_included')) {
$context['api_included'] = $included;
}
$resources = new ResourceList();
$context['resources'] = &$resources;
$resourcesToPush = new ResourceList();
$context['resources_to_push'] = &$resourcesToPush;
$request->attributes->set('_api_normalization_context', $context);
$event->setControllerResult($this->serializer->serialize($controllerResult, $request->getRequestFormat(), $context));
$request->attributes->set('_resources', $request->attributes->get('_resources', []) + (array) $resources);
if (!\count($resourcesToPush)) {
return;
}
$linkProvider = $request->attributes->get('_links', new GenericLinkProvider());
foreach ($resourcesToPush as $resourceToPush) {
$linkProvider = $linkProvider->withLink(new Link('preload', $resourceToPush));
}
$request->attributes->set('_links', $linkProvider);
} | php | public function onKernelView(GetResponseForControllerResultEvent $event): void
{
$controllerResult = $event->getControllerResult();
$request = $event->getRequest();
if ($controllerResult instanceof Response || !(($attributes = RequestAttributesExtractor::extractAttributes($request))['respond'] ?? $request->attributes->getBoolean('_api_respond', false))) {
return;
}
if (!$attributes) {
$this->serializeRawData($event, $request, $controllerResult);
return;
}
$context = $this->serializerContextBuilder->createFromRequest($request, true, $attributes);
if (isset($context['output']) && \array_key_exists('class', $context['output']) && null === $context['output']['class']) {
$event->setControllerResult(null);
return;
}
if ($included = $request->attributes->get('_api_included')) {
$context['api_included'] = $included;
}
$resources = new ResourceList();
$context['resources'] = &$resources;
$resourcesToPush = new ResourceList();
$context['resources_to_push'] = &$resourcesToPush;
$request->attributes->set('_api_normalization_context', $context);
$event->setControllerResult($this->serializer->serialize($controllerResult, $request->getRequestFormat(), $context));
$request->attributes->set('_resources', $request->attributes->get('_resources', []) + (array) $resources);
if (!\count($resourcesToPush)) {
return;
}
$linkProvider = $request->attributes->get('_links', new GenericLinkProvider());
foreach ($resourcesToPush as $resourceToPush) {
$linkProvider = $linkProvider->withLink(new Link('preload', $resourceToPush));
}
$request->attributes->set('_links', $linkProvider);
} | [
"public",
"function",
"onKernelView",
"(",
"GetResponseForControllerResultEvent",
"$",
"event",
")",
":",
"void",
"{",
"$",
"controllerResult",
"=",
"$",
"event",
"->",
"getControllerResult",
"(",
")",
";",
"$",
"request",
"=",
"$",
"event",
"->",
"getRequest",
"(",
")",
";",
"if",
"(",
"$",
"controllerResult",
"instanceof",
"Response",
"||",
"!",
"(",
"(",
"$",
"attributes",
"=",
"RequestAttributesExtractor",
"::",
"extractAttributes",
"(",
"$",
"request",
")",
")",
"[",
"'respond'",
"]",
"??",
"$",
"request",
"->",
"attributes",
"->",
"getBoolean",
"(",
"'_api_respond'",
",",
"false",
")",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"$",
"attributes",
")",
"{",
"$",
"this",
"->",
"serializeRawData",
"(",
"$",
"event",
",",
"$",
"request",
",",
"$",
"controllerResult",
")",
";",
"return",
";",
"}",
"$",
"context",
"=",
"$",
"this",
"->",
"serializerContextBuilder",
"->",
"createFromRequest",
"(",
"$",
"request",
",",
"true",
",",
"$",
"attributes",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"context",
"[",
"'output'",
"]",
")",
"&&",
"\\",
"array_key_exists",
"(",
"'class'",
",",
"$",
"context",
"[",
"'output'",
"]",
")",
"&&",
"null",
"===",
"$",
"context",
"[",
"'output'",
"]",
"[",
"'class'",
"]",
")",
"{",
"$",
"event",
"->",
"setControllerResult",
"(",
"null",
")",
";",
"return",
";",
"}",
"if",
"(",
"$",
"included",
"=",
"$",
"request",
"->",
"attributes",
"->",
"get",
"(",
"'_api_included'",
")",
")",
"{",
"$",
"context",
"[",
"'api_included'",
"]",
"=",
"$",
"included",
";",
"}",
"$",
"resources",
"=",
"new",
"ResourceList",
"(",
")",
";",
"$",
"context",
"[",
"'resources'",
"]",
"=",
"&",
"$",
"resources",
";",
"$",
"resourcesToPush",
"=",
"new",
"ResourceList",
"(",
")",
";",
"$",
"context",
"[",
"'resources_to_push'",
"]",
"=",
"&",
"$",
"resourcesToPush",
";",
"$",
"request",
"->",
"attributes",
"->",
"set",
"(",
"'_api_normalization_context'",
",",
"$",
"context",
")",
";",
"$",
"event",
"->",
"setControllerResult",
"(",
"$",
"this",
"->",
"serializer",
"->",
"serialize",
"(",
"$",
"controllerResult",
",",
"$",
"request",
"->",
"getRequestFormat",
"(",
")",
",",
"$",
"context",
")",
")",
";",
"$",
"request",
"->",
"attributes",
"->",
"set",
"(",
"'_resources'",
",",
"$",
"request",
"->",
"attributes",
"->",
"get",
"(",
"'_resources'",
",",
"[",
"]",
")",
"+",
"(",
"array",
")",
"$",
"resources",
")",
";",
"if",
"(",
"!",
"\\",
"count",
"(",
"$",
"resourcesToPush",
")",
")",
"{",
"return",
";",
"}",
"$",
"linkProvider",
"=",
"$",
"request",
"->",
"attributes",
"->",
"get",
"(",
"'_links'",
",",
"new",
"GenericLinkProvider",
"(",
")",
")",
";",
"foreach",
"(",
"$",
"resourcesToPush",
"as",
"$",
"resourceToPush",
")",
"{",
"$",
"linkProvider",
"=",
"$",
"linkProvider",
"->",
"withLink",
"(",
"new",
"Link",
"(",
"'preload'",
",",
"$",
"resourceToPush",
")",
")",
";",
"}",
"$",
"request",
"->",
"attributes",
"->",
"set",
"(",
"'_links'",
",",
"$",
"linkProvider",
")",
";",
"}"
]
| Serializes the data to the requested format. | [
"Serializes",
"the",
"data",
"to",
"the",
"requested",
"format",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/EventListener/SerializeListener.php#L47-L93 | train |
api-platform/core | src/Bridge/Doctrine/Orm/Extension/FilterEagerLoadingExtension.php | FilterEagerLoadingExtension.getQueryBuilderWithNewAliases | private function getQueryBuilderWithNewAliases(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $originAlias = 'o', string $replacement = 'o_2'): QueryBuilder
{
$queryBuilderClone = clone $queryBuilder;
$joinParts = $queryBuilder->getDQLPart('join');
$wherePart = $queryBuilder->getDQLPart('where');
//reset parts
$queryBuilderClone->resetDQLPart('join');
$queryBuilderClone->resetDQLPart('where');
$queryBuilderClone->resetDQLPart('orderBy');
$queryBuilderClone->resetDQLPart('groupBy');
$queryBuilderClone->resetDQLPart('having');
//Change from alias
$from = $queryBuilderClone->getDQLPart('from')[0];
$queryBuilderClone->resetDQLPart('from');
$queryBuilderClone->from($from->getFrom(), $replacement);
$aliases = ["$originAlias."];
$replacements = ["$replacement."];
//Change join aliases
foreach ($joinParts[$originAlias] as $joinPart) {
/** @var Join $joinPart */
$joinString = str_replace($aliases, $replacements, $joinPart->getJoin());
$pos = strpos($joinString, '.');
if (false === $pos) {
if (null !== $joinPart->getCondition() && null !== $this->resourceClassResolver && $this->resourceClassResolver->isResourceClass($joinString)) {
$newAlias = $queryNameGenerator->generateJoinAlias($joinPart->getAlias());
$aliases[] = "{$joinPart->getAlias()}.";
$replacements[] = "$newAlias.";
$condition = str_replace($aliases, $replacements, $joinPart->getCondition());
$join = new Join($joinPart->getJoinType(), $joinPart->getJoin(), $newAlias, $joinPart->getConditionType(), $condition);
$queryBuilderClone->add('join', [$replacement => $join], true);
}
continue;
}
$alias = substr($joinString, 0, $pos);
$association = substr($joinString, $pos + 1);
$condition = str_replace($aliases, $replacements, $joinPart->getCondition());
$newAlias = QueryBuilderHelper::addJoinOnce($queryBuilderClone, $queryNameGenerator, $alias, $association, $joinPart->getJoinType(), $joinPart->getConditionType(), $condition, $originAlias);
$aliases[] = "{$joinPart->getAlias()}.";
$replacements[] = "$newAlias.";
}
$queryBuilderClone->add('where', str_replace($aliases, $replacements, (string) $wherePart));
return $queryBuilderClone;
} | php | private function getQueryBuilderWithNewAliases(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $originAlias = 'o', string $replacement = 'o_2'): QueryBuilder
{
$queryBuilderClone = clone $queryBuilder;
$joinParts = $queryBuilder->getDQLPart('join');
$wherePart = $queryBuilder->getDQLPart('where');
//reset parts
$queryBuilderClone->resetDQLPart('join');
$queryBuilderClone->resetDQLPart('where');
$queryBuilderClone->resetDQLPart('orderBy');
$queryBuilderClone->resetDQLPart('groupBy');
$queryBuilderClone->resetDQLPart('having');
//Change from alias
$from = $queryBuilderClone->getDQLPart('from')[0];
$queryBuilderClone->resetDQLPart('from');
$queryBuilderClone->from($from->getFrom(), $replacement);
$aliases = ["$originAlias."];
$replacements = ["$replacement."];
//Change join aliases
foreach ($joinParts[$originAlias] as $joinPart) {
/** @var Join $joinPart */
$joinString = str_replace($aliases, $replacements, $joinPart->getJoin());
$pos = strpos($joinString, '.');
if (false === $pos) {
if (null !== $joinPart->getCondition() && null !== $this->resourceClassResolver && $this->resourceClassResolver->isResourceClass($joinString)) {
$newAlias = $queryNameGenerator->generateJoinAlias($joinPart->getAlias());
$aliases[] = "{$joinPart->getAlias()}.";
$replacements[] = "$newAlias.";
$condition = str_replace($aliases, $replacements, $joinPart->getCondition());
$join = new Join($joinPart->getJoinType(), $joinPart->getJoin(), $newAlias, $joinPart->getConditionType(), $condition);
$queryBuilderClone->add('join', [$replacement => $join], true);
}
continue;
}
$alias = substr($joinString, 0, $pos);
$association = substr($joinString, $pos + 1);
$condition = str_replace($aliases, $replacements, $joinPart->getCondition());
$newAlias = QueryBuilderHelper::addJoinOnce($queryBuilderClone, $queryNameGenerator, $alias, $association, $joinPart->getJoinType(), $joinPart->getConditionType(), $condition, $originAlias);
$aliases[] = "{$joinPart->getAlias()}.";
$replacements[] = "$newAlias.";
}
$queryBuilderClone->add('where', str_replace($aliases, $replacements, (string) $wherePart));
return $queryBuilderClone;
} | [
"private",
"function",
"getQueryBuilderWithNewAliases",
"(",
"QueryBuilder",
"$",
"queryBuilder",
",",
"QueryNameGeneratorInterface",
"$",
"queryNameGenerator",
",",
"string",
"$",
"originAlias",
"=",
"'o'",
",",
"string",
"$",
"replacement",
"=",
"'o_2'",
")",
":",
"QueryBuilder",
"{",
"$",
"queryBuilderClone",
"=",
"clone",
"$",
"queryBuilder",
";",
"$",
"joinParts",
"=",
"$",
"queryBuilder",
"->",
"getDQLPart",
"(",
"'join'",
")",
";",
"$",
"wherePart",
"=",
"$",
"queryBuilder",
"->",
"getDQLPart",
"(",
"'where'",
")",
";",
"//reset parts",
"$",
"queryBuilderClone",
"->",
"resetDQLPart",
"(",
"'join'",
")",
";",
"$",
"queryBuilderClone",
"->",
"resetDQLPart",
"(",
"'where'",
")",
";",
"$",
"queryBuilderClone",
"->",
"resetDQLPart",
"(",
"'orderBy'",
")",
";",
"$",
"queryBuilderClone",
"->",
"resetDQLPart",
"(",
"'groupBy'",
")",
";",
"$",
"queryBuilderClone",
"->",
"resetDQLPart",
"(",
"'having'",
")",
";",
"//Change from alias",
"$",
"from",
"=",
"$",
"queryBuilderClone",
"->",
"getDQLPart",
"(",
"'from'",
")",
"[",
"0",
"]",
";",
"$",
"queryBuilderClone",
"->",
"resetDQLPart",
"(",
"'from'",
")",
";",
"$",
"queryBuilderClone",
"->",
"from",
"(",
"$",
"from",
"->",
"getFrom",
"(",
")",
",",
"$",
"replacement",
")",
";",
"$",
"aliases",
"=",
"[",
"\"$originAlias.\"",
"]",
";",
"$",
"replacements",
"=",
"[",
"\"$replacement.\"",
"]",
";",
"//Change join aliases",
"foreach",
"(",
"$",
"joinParts",
"[",
"$",
"originAlias",
"]",
"as",
"$",
"joinPart",
")",
"{",
"/** @var Join $joinPart */",
"$",
"joinString",
"=",
"str_replace",
"(",
"$",
"aliases",
",",
"$",
"replacements",
",",
"$",
"joinPart",
"->",
"getJoin",
"(",
")",
")",
";",
"$",
"pos",
"=",
"strpos",
"(",
"$",
"joinString",
",",
"'.'",
")",
";",
"if",
"(",
"false",
"===",
"$",
"pos",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"joinPart",
"->",
"getCondition",
"(",
")",
"&&",
"null",
"!==",
"$",
"this",
"->",
"resourceClassResolver",
"&&",
"$",
"this",
"->",
"resourceClassResolver",
"->",
"isResourceClass",
"(",
"$",
"joinString",
")",
")",
"{",
"$",
"newAlias",
"=",
"$",
"queryNameGenerator",
"->",
"generateJoinAlias",
"(",
"$",
"joinPart",
"->",
"getAlias",
"(",
")",
")",
";",
"$",
"aliases",
"[",
"]",
"=",
"\"{$joinPart->getAlias()}.\"",
";",
"$",
"replacements",
"[",
"]",
"=",
"\"$newAlias.\"",
";",
"$",
"condition",
"=",
"str_replace",
"(",
"$",
"aliases",
",",
"$",
"replacements",
",",
"$",
"joinPart",
"->",
"getCondition",
"(",
")",
")",
";",
"$",
"join",
"=",
"new",
"Join",
"(",
"$",
"joinPart",
"->",
"getJoinType",
"(",
")",
",",
"$",
"joinPart",
"->",
"getJoin",
"(",
")",
",",
"$",
"newAlias",
",",
"$",
"joinPart",
"->",
"getConditionType",
"(",
")",
",",
"$",
"condition",
")",
";",
"$",
"queryBuilderClone",
"->",
"add",
"(",
"'join'",
",",
"[",
"$",
"replacement",
"=>",
"$",
"join",
"]",
",",
"true",
")",
";",
"}",
"continue",
";",
"}",
"$",
"alias",
"=",
"substr",
"(",
"$",
"joinString",
",",
"0",
",",
"$",
"pos",
")",
";",
"$",
"association",
"=",
"substr",
"(",
"$",
"joinString",
",",
"$",
"pos",
"+",
"1",
")",
";",
"$",
"condition",
"=",
"str_replace",
"(",
"$",
"aliases",
",",
"$",
"replacements",
",",
"$",
"joinPart",
"->",
"getCondition",
"(",
")",
")",
";",
"$",
"newAlias",
"=",
"QueryBuilderHelper",
"::",
"addJoinOnce",
"(",
"$",
"queryBuilderClone",
",",
"$",
"queryNameGenerator",
",",
"$",
"alias",
",",
"$",
"association",
",",
"$",
"joinPart",
"->",
"getJoinType",
"(",
")",
",",
"$",
"joinPart",
"->",
"getConditionType",
"(",
")",
",",
"$",
"condition",
",",
"$",
"originAlias",
")",
";",
"$",
"aliases",
"[",
"]",
"=",
"\"{$joinPart->getAlias()}.\"",
";",
"$",
"replacements",
"[",
"]",
"=",
"\"$newAlias.\"",
";",
"}",
"$",
"queryBuilderClone",
"->",
"add",
"(",
"'where'",
",",
"str_replace",
"(",
"$",
"aliases",
",",
"$",
"replacements",
",",
"(",
"string",
")",
"$",
"wherePart",
")",
")",
";",
"return",
"$",
"queryBuilderClone",
";",
"}"
]
| Returns a clone of the given query builder where everything gets re-aliased.
@param string $originAlias the base alias
@param string $replacement the replacement for the base alias, will change the from alias | [
"Returns",
"a",
"clone",
"of",
"the",
"given",
"query",
"builder",
"where",
"everything",
"gets",
"re",
"-",
"aliased",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Bridge/Doctrine/Orm/Extension/FilterEagerLoadingExtension.php#L111-L161 | train |
api-platform/core | src/Bridge/Symfony/Routing/OperationMethodResolver.php | OperationMethodResolver.getOperationRoute | private function getOperationRoute(string $resourceClass, string $operationName, string $operationType): Route
{
$routeName = $this->getRouteName($this->resourceMetadataFactory->create($resourceClass), $operationName, $operationType);
if (null !== $routeName) {
return $this->getRoute($routeName);
}
$operationNameKey = sprintf('_api_%s_operation_name', $operationType);
foreach ($this->router->getRouteCollection()->all() as $routeName => $route) {
$currentResourceClass = $route->getDefault('_api_resource_class');
$currentOperationName = $route->getDefault($operationNameKey);
if ($resourceClass === $currentResourceClass && $operationName === $currentOperationName) {
return $route;
}
}
throw new RuntimeException(sprintf('No route found for operation "%s" for type "%s".', $operationName, $resourceClass));
} | php | private function getOperationRoute(string $resourceClass, string $operationName, string $operationType): Route
{
$routeName = $this->getRouteName($this->resourceMetadataFactory->create($resourceClass), $operationName, $operationType);
if (null !== $routeName) {
return $this->getRoute($routeName);
}
$operationNameKey = sprintf('_api_%s_operation_name', $operationType);
foreach ($this->router->getRouteCollection()->all() as $routeName => $route) {
$currentResourceClass = $route->getDefault('_api_resource_class');
$currentOperationName = $route->getDefault($operationNameKey);
if ($resourceClass === $currentResourceClass && $operationName === $currentOperationName) {
return $route;
}
}
throw new RuntimeException(sprintf('No route found for operation "%s" for type "%s".', $operationName, $resourceClass));
} | [
"private",
"function",
"getOperationRoute",
"(",
"string",
"$",
"resourceClass",
",",
"string",
"$",
"operationName",
",",
"string",
"$",
"operationType",
")",
":",
"Route",
"{",
"$",
"routeName",
"=",
"$",
"this",
"->",
"getRouteName",
"(",
"$",
"this",
"->",
"resourceMetadataFactory",
"->",
"create",
"(",
"$",
"resourceClass",
")",
",",
"$",
"operationName",
",",
"$",
"operationType",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"routeName",
")",
"{",
"return",
"$",
"this",
"->",
"getRoute",
"(",
"$",
"routeName",
")",
";",
"}",
"$",
"operationNameKey",
"=",
"sprintf",
"(",
"'_api_%s_operation_name'",
",",
"$",
"operationType",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"router",
"->",
"getRouteCollection",
"(",
")",
"->",
"all",
"(",
")",
"as",
"$",
"routeName",
"=>",
"$",
"route",
")",
"{",
"$",
"currentResourceClass",
"=",
"$",
"route",
"->",
"getDefault",
"(",
"'_api_resource_class'",
")",
";",
"$",
"currentOperationName",
"=",
"$",
"route",
"->",
"getDefault",
"(",
"$",
"operationNameKey",
")",
";",
"if",
"(",
"$",
"resourceClass",
"===",
"$",
"currentResourceClass",
"&&",
"$",
"operationName",
"===",
"$",
"currentOperationName",
")",
"{",
"return",
"$",
"route",
";",
"}",
"}",
"throw",
"new",
"RuntimeException",
"(",
"sprintf",
"(",
"'No route found for operation \"%s\" for type \"%s\".'",
",",
"$",
"operationName",
",",
"$",
"resourceClass",
")",
")",
";",
"}"
]
| Gets the route related to the given operation.
@throws RuntimeException | [
"Gets",
"the",
"route",
"related",
"to",
"the",
"given",
"operation",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Bridge/Symfony/Routing/OperationMethodResolver.php#L101-L120 | train |
api-platform/core | src/Bridge/Symfony/Routing/OperationMethodResolver.php | OperationMethodResolver.getRouteName | private function getRouteName(ResourceMetadata $resourceMetadata, string $operationName, string $operationType): ?string
{
if (OperationType::ITEM === $operationType) {
return $resourceMetadata->getItemOperationAttribute($operationName, 'route_name');
}
return $resourceMetadata->getCollectionOperationAttribute($operationName, 'route_name');
} | php | private function getRouteName(ResourceMetadata $resourceMetadata, string $operationName, string $operationType): ?string
{
if (OperationType::ITEM === $operationType) {
return $resourceMetadata->getItemOperationAttribute($operationName, 'route_name');
}
return $resourceMetadata->getCollectionOperationAttribute($operationName, 'route_name');
} | [
"private",
"function",
"getRouteName",
"(",
"ResourceMetadata",
"$",
"resourceMetadata",
",",
"string",
"$",
"operationName",
",",
"string",
"$",
"operationType",
")",
":",
"?",
"string",
"{",
"if",
"(",
"OperationType",
"::",
"ITEM",
"===",
"$",
"operationType",
")",
"{",
"return",
"$",
"resourceMetadata",
"->",
"getItemOperationAttribute",
"(",
"$",
"operationName",
",",
"'route_name'",
")",
";",
"}",
"return",
"$",
"resourceMetadata",
"->",
"getCollectionOperationAttribute",
"(",
"$",
"operationName",
",",
"'route_name'",
")",
";",
"}"
]
| Gets the route name or null if not defined. | [
"Gets",
"the",
"route",
"name",
"or",
"null",
"if",
"not",
"defined",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Bridge/Symfony/Routing/OperationMethodResolver.php#L125-L132 | train |
api-platform/core | src/Bridge/Symfony/Routing/OperationMethodResolver.php | OperationMethodResolver.getRoute | private function getRoute(string $routeName): Route
{
foreach ($this->router->getRouteCollection() as $name => $route) {
if ($routeName === $name) {
return $route;
}
}
throw new RuntimeException(sprintf('The route "%s" does not exist.', $routeName));
} | php | private function getRoute(string $routeName): Route
{
foreach ($this->router->getRouteCollection() as $name => $route) {
if ($routeName === $name) {
return $route;
}
}
throw new RuntimeException(sprintf('The route "%s" does not exist.', $routeName));
} | [
"private",
"function",
"getRoute",
"(",
"string",
"$",
"routeName",
")",
":",
"Route",
"{",
"foreach",
"(",
"$",
"this",
"->",
"router",
"->",
"getRouteCollection",
"(",
")",
"as",
"$",
"name",
"=>",
"$",
"route",
")",
"{",
"if",
"(",
"$",
"routeName",
"===",
"$",
"name",
")",
"{",
"return",
"$",
"route",
";",
"}",
"}",
"throw",
"new",
"RuntimeException",
"(",
"sprintf",
"(",
"'The route \"%s\" does not exist.'",
",",
"$",
"routeName",
")",
")",
";",
"}"
]
| Gets the route with the given name.
@throws RuntimeException | [
"Gets",
"the",
"route",
"with",
"the",
"given",
"name",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Bridge/Symfony/Routing/OperationMethodResolver.php#L139-L148 | train |
api-platform/core | src/Metadata/Extractor/XmlExtractor.php | XmlExtractor.getOperations | private function getOperations(\SimpleXMLElement $resource, string $operationType): ?array
{
$graphql = 'operation' === $operationType;
if (!$graphql && $legacyOperations = $this->getAttributes($resource, $operationType)) {
@trigger_error(
sprintf('Configuring "%1$s" tags without using a parent "%1$ss" tag is deprecated since API Platform 2.1 and will not be possible anymore in API Platform 3', $operationType),
E_USER_DEPRECATED
);
return $legacyOperations;
}
$operationsParent = $graphql ? 'graphql' : "{$operationType}s";
if (!isset($resource->{$operationsParent})) {
return null;
}
return $this->getAttributes($resource->{$operationsParent}, $operationType, true);
} | php | private function getOperations(\SimpleXMLElement $resource, string $operationType): ?array
{
$graphql = 'operation' === $operationType;
if (!$graphql && $legacyOperations = $this->getAttributes($resource, $operationType)) {
@trigger_error(
sprintf('Configuring "%1$s" tags without using a parent "%1$ss" tag is deprecated since API Platform 2.1 and will not be possible anymore in API Platform 3', $operationType),
E_USER_DEPRECATED
);
return $legacyOperations;
}
$operationsParent = $graphql ? 'graphql' : "{$operationType}s";
if (!isset($resource->{$operationsParent})) {
return null;
}
return $this->getAttributes($resource->{$operationsParent}, $operationType, true);
} | [
"private",
"function",
"getOperations",
"(",
"\\",
"SimpleXMLElement",
"$",
"resource",
",",
"string",
"$",
"operationType",
")",
":",
"?",
"array",
"{",
"$",
"graphql",
"=",
"'operation'",
"===",
"$",
"operationType",
";",
"if",
"(",
"!",
"$",
"graphql",
"&&",
"$",
"legacyOperations",
"=",
"$",
"this",
"->",
"getAttributes",
"(",
"$",
"resource",
",",
"$",
"operationType",
")",
")",
"{",
"@",
"trigger_error",
"(",
"sprintf",
"(",
"'Configuring \"%1$s\" tags without using a parent \"%1$ss\" tag is deprecated since API Platform 2.1 and will not be possible anymore in API Platform 3'",
",",
"$",
"operationType",
")",
",",
"E_USER_DEPRECATED",
")",
";",
"return",
"$",
"legacyOperations",
";",
"}",
"$",
"operationsParent",
"=",
"$",
"graphql",
"?",
"'graphql'",
":",
"\"{$operationType}s\"",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"resource",
"->",
"{",
"$",
"operationsParent",
"}",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"this",
"->",
"getAttributes",
"(",
"$",
"resource",
"->",
"{",
"$",
"operationsParent",
"}",
",",
"$",
"operationType",
",",
"true",
")",
";",
"}"
]
| Returns the array containing configured operations. Returns NULL if there is no operation configuration. | [
"Returns",
"the",
"array",
"containing",
"configured",
"operations",
".",
"Returns",
"NULL",
"if",
"there",
"is",
"no",
"operation",
"configuration",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Metadata/Extractor/XmlExtractor.php#L62-L80 | train |
api-platform/core | src/Metadata/Extractor/XmlExtractor.php | XmlExtractor.getAttributes | private function getAttributes(\SimpleXMLElement $resource, string $elementName, bool $topLevel = false): array
{
$attributes = [];
foreach ($resource->{$elementName} as $attribute) {
$value = isset($attribute->attribute[0]) ? $this->getAttributes($attribute, 'attribute') : XmlUtils::phpize($attribute);
// allow empty operations definition, like <collectionOperation name="post" />
if ($topLevel && '' === $value) {
$value = [];
}
if (isset($attribute['name'])) {
$attributes[(string) $attribute['name']] = $value;
} else {
$attributes[] = $value;
}
}
return $attributes;
} | php | private function getAttributes(\SimpleXMLElement $resource, string $elementName, bool $topLevel = false): array
{
$attributes = [];
foreach ($resource->{$elementName} as $attribute) {
$value = isset($attribute->attribute[0]) ? $this->getAttributes($attribute, 'attribute') : XmlUtils::phpize($attribute);
// allow empty operations definition, like <collectionOperation name="post" />
if ($topLevel && '' === $value) {
$value = [];
}
if (isset($attribute['name'])) {
$attributes[(string) $attribute['name']] = $value;
} else {
$attributes[] = $value;
}
}
return $attributes;
} | [
"private",
"function",
"getAttributes",
"(",
"\\",
"SimpleXMLElement",
"$",
"resource",
",",
"string",
"$",
"elementName",
",",
"bool",
"$",
"topLevel",
"=",
"false",
")",
":",
"array",
"{",
"$",
"attributes",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"resource",
"->",
"{",
"$",
"elementName",
"}",
"as",
"$",
"attribute",
")",
"{",
"$",
"value",
"=",
"isset",
"(",
"$",
"attribute",
"->",
"attribute",
"[",
"0",
"]",
")",
"?",
"$",
"this",
"->",
"getAttributes",
"(",
"$",
"attribute",
",",
"'attribute'",
")",
":",
"XmlUtils",
"::",
"phpize",
"(",
"$",
"attribute",
")",
";",
"// allow empty operations definition, like <collectionOperation name=\"post\" />",
"if",
"(",
"$",
"topLevel",
"&&",
"''",
"===",
"$",
"value",
")",
"{",
"$",
"value",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"attribute",
"[",
"'name'",
"]",
")",
")",
"{",
"$",
"attributes",
"[",
"(",
"string",
")",
"$",
"attribute",
"[",
"'name'",
"]",
"]",
"=",
"$",
"value",
";",
"}",
"else",
"{",
"$",
"attributes",
"[",
"]",
"=",
"$",
"value",
";",
"}",
"}",
"return",
"$",
"attributes",
";",
"}"
]
| Recursively transforms an attribute structure into an associative array. | [
"Recursively",
"transforms",
"an",
"attribute",
"structure",
"into",
"an",
"associative",
"array",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Metadata/Extractor/XmlExtractor.php#L85-L102 | train |
api-platform/core | src/Metadata/Extractor/XmlExtractor.php | XmlExtractor.getProperties | private function getProperties(\SimpleXMLElement $resource): array
{
$properties = [];
foreach ($resource->property as $property) {
$properties[(string) $property['name']] = [
'description' => $this->phpize($property, 'description', 'string'),
'readable' => $this->phpize($property, 'readable', 'bool'),
'writable' => $this->phpize($property, 'writable', 'bool'),
'readableLink' => $this->phpize($property, 'readableLink', 'bool'),
'writableLink' => $this->phpize($property, 'writableLink', 'bool'),
'required' => $this->phpize($property, 'required', 'bool'),
'identifier' => $this->phpize($property, 'identifier', 'bool'),
'iri' => $this->phpize($property, 'iri', 'string'),
'attributes' => $this->getAttributes($property, 'attribute'),
'subresource' => $property->subresource ? [
'collection' => $this->phpize($property->subresource, 'collection', 'bool'),
'resourceClass' => $this->phpize($property->subresource, 'resourceClass', 'string'),
'maxDepth' => $this->phpize($property->subresource, 'maxDepth', 'integer'),
] : null,
];
}
return $properties;
} | php | private function getProperties(\SimpleXMLElement $resource): array
{
$properties = [];
foreach ($resource->property as $property) {
$properties[(string) $property['name']] = [
'description' => $this->phpize($property, 'description', 'string'),
'readable' => $this->phpize($property, 'readable', 'bool'),
'writable' => $this->phpize($property, 'writable', 'bool'),
'readableLink' => $this->phpize($property, 'readableLink', 'bool'),
'writableLink' => $this->phpize($property, 'writableLink', 'bool'),
'required' => $this->phpize($property, 'required', 'bool'),
'identifier' => $this->phpize($property, 'identifier', 'bool'),
'iri' => $this->phpize($property, 'iri', 'string'),
'attributes' => $this->getAttributes($property, 'attribute'),
'subresource' => $property->subresource ? [
'collection' => $this->phpize($property->subresource, 'collection', 'bool'),
'resourceClass' => $this->phpize($property->subresource, 'resourceClass', 'string'),
'maxDepth' => $this->phpize($property->subresource, 'maxDepth', 'integer'),
] : null,
];
}
return $properties;
} | [
"private",
"function",
"getProperties",
"(",
"\\",
"SimpleXMLElement",
"$",
"resource",
")",
":",
"array",
"{",
"$",
"properties",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"resource",
"->",
"property",
"as",
"$",
"property",
")",
"{",
"$",
"properties",
"[",
"(",
"string",
")",
"$",
"property",
"[",
"'name'",
"]",
"]",
"=",
"[",
"'description'",
"=>",
"$",
"this",
"->",
"phpize",
"(",
"$",
"property",
",",
"'description'",
",",
"'string'",
")",
",",
"'readable'",
"=>",
"$",
"this",
"->",
"phpize",
"(",
"$",
"property",
",",
"'readable'",
",",
"'bool'",
")",
",",
"'writable'",
"=>",
"$",
"this",
"->",
"phpize",
"(",
"$",
"property",
",",
"'writable'",
",",
"'bool'",
")",
",",
"'readableLink'",
"=>",
"$",
"this",
"->",
"phpize",
"(",
"$",
"property",
",",
"'readableLink'",
",",
"'bool'",
")",
",",
"'writableLink'",
"=>",
"$",
"this",
"->",
"phpize",
"(",
"$",
"property",
",",
"'writableLink'",
",",
"'bool'",
")",
",",
"'required'",
"=>",
"$",
"this",
"->",
"phpize",
"(",
"$",
"property",
",",
"'required'",
",",
"'bool'",
")",
",",
"'identifier'",
"=>",
"$",
"this",
"->",
"phpize",
"(",
"$",
"property",
",",
"'identifier'",
",",
"'bool'",
")",
",",
"'iri'",
"=>",
"$",
"this",
"->",
"phpize",
"(",
"$",
"property",
",",
"'iri'",
",",
"'string'",
")",
",",
"'attributes'",
"=>",
"$",
"this",
"->",
"getAttributes",
"(",
"$",
"property",
",",
"'attribute'",
")",
",",
"'subresource'",
"=>",
"$",
"property",
"->",
"subresource",
"?",
"[",
"'collection'",
"=>",
"$",
"this",
"->",
"phpize",
"(",
"$",
"property",
"->",
"subresource",
",",
"'collection'",
",",
"'bool'",
")",
",",
"'resourceClass'",
"=>",
"$",
"this",
"->",
"phpize",
"(",
"$",
"property",
"->",
"subresource",
",",
"'resourceClass'",
",",
"'string'",
")",
",",
"'maxDepth'",
"=>",
"$",
"this",
"->",
"phpize",
"(",
"$",
"property",
"->",
"subresource",
",",
"'maxDepth'",
",",
"'integer'",
")",
",",
"]",
":",
"null",
",",
"]",
";",
"}",
"return",
"$",
"properties",
";",
"}"
]
| Gets metadata of a property. | [
"Gets",
"metadata",
"of",
"a",
"property",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Metadata/Extractor/XmlExtractor.php#L107-L130 | train |
api-platform/core | src/Metadata/Extractor/XmlExtractor.php | XmlExtractor.phpize | private function phpize(\SimpleXMLElement $array, string $key, string $type)
{
if (!isset($array[$key])) {
return null;
}
switch ($type) {
case 'string':
return (string) $array[$key];
case 'integer':
return (int) $array[$key];
case 'bool':
return (bool) XmlUtils::phpize($array[$key]);
}
return null;
} | php | private function phpize(\SimpleXMLElement $array, string $key, string $type)
{
if (!isset($array[$key])) {
return null;
}
switch ($type) {
case 'string':
return (string) $array[$key];
case 'integer':
return (int) $array[$key];
case 'bool':
return (bool) XmlUtils::phpize($array[$key]);
}
return null;
} | [
"private",
"function",
"phpize",
"(",
"\\",
"SimpleXMLElement",
"$",
"array",
",",
"string",
"$",
"key",
",",
"string",
"$",
"type",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"array",
"[",
"$",
"key",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"'string'",
":",
"return",
"(",
"string",
")",
"$",
"array",
"[",
"$",
"key",
"]",
";",
"case",
"'integer'",
":",
"return",
"(",
"int",
")",
"$",
"array",
"[",
"$",
"key",
"]",
";",
"case",
"'bool'",
":",
"return",
"(",
"bool",
")",
"XmlUtils",
"::",
"phpize",
"(",
"$",
"array",
"[",
"$",
"key",
"]",
")",
";",
"}",
"return",
"null",
";",
"}"
]
| Transforms an XML attribute's value in a PHP value.
@return string|int|bool|null | [
"Transforms",
"an",
"XML",
"attribute",
"s",
"value",
"in",
"a",
"PHP",
"value",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Metadata/Extractor/XmlExtractor.php#L137-L153 | train |
api-platform/core | src/EventListener/DeserializeListener.php | DeserializeListener.onKernelRequest | public function onKernelRequest(GetResponseEvent $event): void
{
$request = $event->getRequest();
$method = $request->getMethod();
if (
'DELETE' === $method
|| $request->isMethodSafe(false)
|| !($attributes = RequestAttributesExtractor::extractAttributes($request))
|| !$attributes['receive']
|| (
'' === ($requestContent = $request->getContent())
&& ('POST' === $method || 'PUT' === $method)
)
) {
return;
}
$context = $this->serializerContextBuilder->createFromRequest($request, false, $attributes);
if (isset($context['input']) && \array_key_exists('class', $context['input']) && null === $context['input']['class']) {
return;
}
// BC check to be removed in 3.0
if (null !== $this->formatsProvider) {
$this->formats = $this->formatsProvider->getFormatsFromAttributes($attributes);
}
$this->formatMatcher = new FormatMatcher($this->formats);
$format = $this->getFormat($request);
$data = $request->attributes->get('data');
if (null !== $data) {
$context[AbstractNormalizer::OBJECT_TO_POPULATE] = $data;
}
$request->attributes->set(
'data',
$this->serializer->deserialize(
$requestContent, $context['resource_class'], $format, $context
)
);
} | php | public function onKernelRequest(GetResponseEvent $event): void
{
$request = $event->getRequest();
$method = $request->getMethod();
if (
'DELETE' === $method
|| $request->isMethodSafe(false)
|| !($attributes = RequestAttributesExtractor::extractAttributes($request))
|| !$attributes['receive']
|| (
'' === ($requestContent = $request->getContent())
&& ('POST' === $method || 'PUT' === $method)
)
) {
return;
}
$context = $this->serializerContextBuilder->createFromRequest($request, false, $attributes);
if (isset($context['input']) && \array_key_exists('class', $context['input']) && null === $context['input']['class']) {
return;
}
// BC check to be removed in 3.0
if (null !== $this->formatsProvider) {
$this->formats = $this->formatsProvider->getFormatsFromAttributes($attributes);
}
$this->formatMatcher = new FormatMatcher($this->formats);
$format = $this->getFormat($request);
$data = $request->attributes->get('data');
if (null !== $data) {
$context[AbstractNormalizer::OBJECT_TO_POPULATE] = $data;
}
$request->attributes->set(
'data',
$this->serializer->deserialize(
$requestContent, $context['resource_class'], $format, $context
)
);
} | [
"public",
"function",
"onKernelRequest",
"(",
"GetResponseEvent",
"$",
"event",
")",
":",
"void",
"{",
"$",
"request",
"=",
"$",
"event",
"->",
"getRequest",
"(",
")",
";",
"$",
"method",
"=",
"$",
"request",
"->",
"getMethod",
"(",
")",
";",
"if",
"(",
"'DELETE'",
"===",
"$",
"method",
"||",
"$",
"request",
"->",
"isMethodSafe",
"(",
"false",
")",
"||",
"!",
"(",
"$",
"attributes",
"=",
"RequestAttributesExtractor",
"::",
"extractAttributes",
"(",
"$",
"request",
")",
")",
"||",
"!",
"$",
"attributes",
"[",
"'receive'",
"]",
"||",
"(",
"''",
"===",
"(",
"$",
"requestContent",
"=",
"$",
"request",
"->",
"getContent",
"(",
")",
")",
"&&",
"(",
"'POST'",
"===",
"$",
"method",
"||",
"'PUT'",
"===",
"$",
"method",
")",
")",
")",
"{",
"return",
";",
"}",
"$",
"context",
"=",
"$",
"this",
"->",
"serializerContextBuilder",
"->",
"createFromRequest",
"(",
"$",
"request",
",",
"false",
",",
"$",
"attributes",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"context",
"[",
"'input'",
"]",
")",
"&&",
"\\",
"array_key_exists",
"(",
"'class'",
",",
"$",
"context",
"[",
"'input'",
"]",
")",
"&&",
"null",
"===",
"$",
"context",
"[",
"'input'",
"]",
"[",
"'class'",
"]",
")",
"{",
"return",
";",
"}",
"// BC check to be removed in 3.0",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"formatsProvider",
")",
"{",
"$",
"this",
"->",
"formats",
"=",
"$",
"this",
"->",
"formatsProvider",
"->",
"getFormatsFromAttributes",
"(",
"$",
"attributes",
")",
";",
"}",
"$",
"this",
"->",
"formatMatcher",
"=",
"new",
"FormatMatcher",
"(",
"$",
"this",
"->",
"formats",
")",
";",
"$",
"format",
"=",
"$",
"this",
"->",
"getFormat",
"(",
"$",
"request",
")",
";",
"$",
"data",
"=",
"$",
"request",
"->",
"attributes",
"->",
"get",
"(",
"'data'",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"data",
")",
"{",
"$",
"context",
"[",
"AbstractNormalizer",
"::",
"OBJECT_TO_POPULATE",
"]",
"=",
"$",
"data",
";",
"}",
"$",
"request",
"->",
"attributes",
"->",
"set",
"(",
"'data'",
",",
"$",
"this",
"->",
"serializer",
"->",
"deserialize",
"(",
"$",
"requestContent",
",",
"$",
"context",
"[",
"'resource_class'",
"]",
",",
"$",
"format",
",",
"$",
"context",
")",
")",
";",
"}"
]
| Deserializes the data sent in the requested format. | [
"Deserializes",
"the",
"data",
"sent",
"in",
"the",
"requested",
"format",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/EventListener/DeserializeListener.php#L62-L103 | train |
api-platform/core | src/EventListener/DeserializeListener.php | DeserializeListener.getFormat | private function getFormat(Request $request): string
{
/**
* @var string|null
*/
$contentType = $request->headers->get('CONTENT_TYPE');
if (null === $contentType) {
throw new NotAcceptableHttpException('The "Content-Type" header must exist.');
}
$format = $this->formatMatcher->getFormat($contentType);
if (null === $format || !isset($this->formats[$format])) {
$supportedMimeTypes = [];
foreach ($this->formats as $mimeTypes) {
foreach ($mimeTypes as $mimeType) {
$supportedMimeTypes[] = $mimeType;
}
}
throw new NotAcceptableHttpException(sprintf(
'The content-type "%s" is not supported. Supported MIME types are "%s".',
$contentType,
implode('", "', $supportedMimeTypes)
));
}
return $format;
} | php | private function getFormat(Request $request): string
{
/**
* @var string|null
*/
$contentType = $request->headers->get('CONTENT_TYPE');
if (null === $contentType) {
throw new NotAcceptableHttpException('The "Content-Type" header must exist.');
}
$format = $this->formatMatcher->getFormat($contentType);
if (null === $format || !isset($this->formats[$format])) {
$supportedMimeTypes = [];
foreach ($this->formats as $mimeTypes) {
foreach ($mimeTypes as $mimeType) {
$supportedMimeTypes[] = $mimeType;
}
}
throw new NotAcceptableHttpException(sprintf(
'The content-type "%s" is not supported. Supported MIME types are "%s".',
$contentType,
implode('", "', $supportedMimeTypes)
));
}
return $format;
} | [
"private",
"function",
"getFormat",
"(",
"Request",
"$",
"request",
")",
":",
"string",
"{",
"/**\n * @var string|null\n */",
"$",
"contentType",
"=",
"$",
"request",
"->",
"headers",
"->",
"get",
"(",
"'CONTENT_TYPE'",
")",
";",
"if",
"(",
"null",
"===",
"$",
"contentType",
")",
"{",
"throw",
"new",
"NotAcceptableHttpException",
"(",
"'The \"Content-Type\" header must exist.'",
")",
";",
"}",
"$",
"format",
"=",
"$",
"this",
"->",
"formatMatcher",
"->",
"getFormat",
"(",
"$",
"contentType",
")",
";",
"if",
"(",
"null",
"===",
"$",
"format",
"||",
"!",
"isset",
"(",
"$",
"this",
"->",
"formats",
"[",
"$",
"format",
"]",
")",
")",
"{",
"$",
"supportedMimeTypes",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"formats",
"as",
"$",
"mimeTypes",
")",
"{",
"foreach",
"(",
"$",
"mimeTypes",
"as",
"$",
"mimeType",
")",
"{",
"$",
"supportedMimeTypes",
"[",
"]",
"=",
"$",
"mimeType",
";",
"}",
"}",
"throw",
"new",
"NotAcceptableHttpException",
"(",
"sprintf",
"(",
"'The content-type \"%s\" is not supported. Supported MIME types are \"%s\".'",
",",
"$",
"contentType",
",",
"implode",
"(",
"'\", \"'",
",",
"$",
"supportedMimeTypes",
")",
")",
")",
";",
"}",
"return",
"$",
"format",
";",
"}"
]
| Extracts the format from the Content-Type header and check that it is supported.
@throws NotAcceptableHttpException | [
"Extracts",
"the",
"format",
"from",
"the",
"Content",
"-",
"Type",
"header",
"and",
"check",
"that",
"it",
"is",
"supported",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/EventListener/DeserializeListener.php#L110-L137 | train |
api-platform/core | src/Util/ClassInfoTrait.php | ClassInfoTrait.getRealClassName | private function getRealClassName(string $className): string
{
// __CG__: Doctrine Common Marker for Proxy (ODM < 2.0 and ORM < 3.0)
// __PM__: Ocramius Proxy Manager (ODM >= 2.0)
if ((false === $positionCg = strrpos($className, '\\__CG__\\')) &&
(false === $positionPm = strrpos($className, '\\__PM__\\'))) {
return $className;
}
if (false !== $positionCg) {
return substr($className, $positionCg + 8);
}
$className = ltrim($className, '\\');
return substr(
$className,
8 + $positionPm,
strrpos($className, '\\') - ($positionPm + 8)
);
} | php | private function getRealClassName(string $className): string
{
// __CG__: Doctrine Common Marker for Proxy (ODM < 2.0 and ORM < 3.0)
// __PM__: Ocramius Proxy Manager (ODM >= 2.0)
if ((false === $positionCg = strrpos($className, '\\__CG__\\')) &&
(false === $positionPm = strrpos($className, '\\__PM__\\'))) {
return $className;
}
if (false !== $positionCg) {
return substr($className, $positionCg + 8);
}
$className = ltrim($className, '\\');
return substr(
$className,
8 + $positionPm,
strrpos($className, '\\') - ($positionPm + 8)
);
} | [
"private",
"function",
"getRealClassName",
"(",
"string",
"$",
"className",
")",
":",
"string",
"{",
"// __CG__: Doctrine Common Marker for Proxy (ODM < 2.0 and ORM < 3.0)",
"// __PM__: Ocramius Proxy Manager (ODM >= 2.0)",
"if",
"(",
"(",
"false",
"===",
"$",
"positionCg",
"=",
"strrpos",
"(",
"$",
"className",
",",
"'\\\\__CG__\\\\'",
")",
")",
"&&",
"(",
"false",
"===",
"$",
"positionPm",
"=",
"strrpos",
"(",
"$",
"className",
",",
"'\\\\__PM__\\\\'",
")",
")",
")",
"{",
"return",
"$",
"className",
";",
"}",
"if",
"(",
"false",
"!==",
"$",
"positionCg",
")",
"{",
"return",
"substr",
"(",
"$",
"className",
",",
"$",
"positionCg",
"+",
"8",
")",
";",
"}",
"$",
"className",
"=",
"ltrim",
"(",
"$",
"className",
",",
"'\\\\'",
")",
";",
"return",
"substr",
"(",
"$",
"className",
",",
"8",
"+",
"$",
"positionPm",
",",
"strrpos",
"(",
"$",
"className",
",",
"'\\\\'",
")",
"-",
"(",
"$",
"positionPm",
"+",
"8",
")",
")",
";",
"}"
]
| Get the real class name of a class name that could be a proxy. | [
"Get",
"the",
"real",
"class",
"name",
"of",
"a",
"class",
"name",
"that",
"could",
"be",
"a",
"proxy",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Util/ClassInfoTrait.php#L38-L58 | train |
api-platform/core | src/DataProvider/OperationDataProviderTrait.php | OperationDataProviderTrait.getItemData | private function getItemData($identifiers, array $attributes, array $context)
{
return $this->itemDataProvider->getItem($attributes['resource_class'], $identifiers, $attributes['item_operation_name'], $context);
} | php | private function getItemData($identifiers, array $attributes, array $context)
{
return $this->itemDataProvider->getItem($attributes['resource_class'], $identifiers, $attributes['item_operation_name'], $context);
} | [
"private",
"function",
"getItemData",
"(",
"$",
"identifiers",
",",
"array",
"$",
"attributes",
",",
"array",
"$",
"context",
")",
"{",
"return",
"$",
"this",
"->",
"itemDataProvider",
"->",
"getItem",
"(",
"$",
"attributes",
"[",
"'resource_class'",
"]",
",",
"$",
"identifiers",
",",
"$",
"attributes",
"[",
"'item_operation_name'",
"]",
",",
"$",
"context",
")",
";",
"}"
]
| Gets data for an item operation.
@return object|null | [
"Gets",
"data",
"for",
"an",
"item",
"operation",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/DataProvider/OperationDataProviderTrait.php#L60-L63 | train |
api-platform/core | src/DataProvider/OperationDataProviderTrait.php | OperationDataProviderTrait.getSubresourceData | private function getSubresourceData($identifiers, array $attributes, array $context)
{
if (null === $this->subresourceDataProvider) {
throw new RuntimeException('Subresources not supported');
}
return $this->subresourceDataProvider->getSubresource($attributes['resource_class'], $identifiers, $attributes['subresource_context'] + $context, $attributes['subresource_operation_name']);
} | php | private function getSubresourceData($identifiers, array $attributes, array $context)
{
if (null === $this->subresourceDataProvider) {
throw new RuntimeException('Subresources not supported');
}
return $this->subresourceDataProvider->getSubresource($attributes['resource_class'], $identifiers, $attributes['subresource_context'] + $context, $attributes['subresource_operation_name']);
} | [
"private",
"function",
"getSubresourceData",
"(",
"$",
"identifiers",
",",
"array",
"$",
"attributes",
",",
"array",
"$",
"context",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"subresourceDataProvider",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Subresources not supported'",
")",
";",
"}",
"return",
"$",
"this",
"->",
"subresourceDataProvider",
"->",
"getSubresource",
"(",
"$",
"attributes",
"[",
"'resource_class'",
"]",
",",
"$",
"identifiers",
",",
"$",
"attributes",
"[",
"'subresource_context'",
"]",
"+",
"$",
"context",
",",
"$",
"attributes",
"[",
"'subresource_operation_name'",
"]",
")",
";",
"}"
]
| Gets data for a nested operation.
@throws RuntimeException
@return array|object|null | [
"Gets",
"data",
"for",
"a",
"nested",
"operation",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/DataProvider/OperationDataProviderTrait.php#L72-L79 | train |
api-platform/core | src/Bridge/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php | ApiPlatformExtension.registerSwaggerConfiguration | private function registerSwaggerConfiguration(ContainerBuilder $container, array $config, XmlFileLoader $loader): void
{
if (!$config['enable_swagger']) {
return;
}
$loader->load('swagger.xml');
if ($config['enable_swagger_ui'] || $config['enable_re_doc']) {
$loader->load('swagger-ui.xml');
$container->setParameter('api_platform.enable_swagger_ui', $config['enable_swagger_ui']);
$container->setParameter('api_platform.enable_re_doc', $config['enable_re_doc']);
}
$container->setParameter('api_platform.enable_swagger', $config['enable_swagger']);
$container->setParameter('api_platform.swagger.api_keys', $config['swagger']['api_keys']);
} | php | private function registerSwaggerConfiguration(ContainerBuilder $container, array $config, XmlFileLoader $loader): void
{
if (!$config['enable_swagger']) {
return;
}
$loader->load('swagger.xml');
if ($config['enable_swagger_ui'] || $config['enable_re_doc']) {
$loader->load('swagger-ui.xml');
$container->setParameter('api_platform.enable_swagger_ui', $config['enable_swagger_ui']);
$container->setParameter('api_platform.enable_re_doc', $config['enable_re_doc']);
}
$container->setParameter('api_platform.enable_swagger', $config['enable_swagger']);
$container->setParameter('api_platform.swagger.api_keys', $config['swagger']['api_keys']);
} | [
"private",
"function",
"registerSwaggerConfiguration",
"(",
"ContainerBuilder",
"$",
"container",
",",
"array",
"$",
"config",
",",
"XmlFileLoader",
"$",
"loader",
")",
":",
"void",
"{",
"if",
"(",
"!",
"$",
"config",
"[",
"'enable_swagger'",
"]",
")",
"{",
"return",
";",
"}",
"$",
"loader",
"->",
"load",
"(",
"'swagger.xml'",
")",
";",
"if",
"(",
"$",
"config",
"[",
"'enable_swagger_ui'",
"]",
"||",
"$",
"config",
"[",
"'enable_re_doc'",
"]",
")",
"{",
"$",
"loader",
"->",
"load",
"(",
"'swagger-ui.xml'",
")",
";",
"$",
"container",
"->",
"setParameter",
"(",
"'api_platform.enable_swagger_ui'",
",",
"$",
"config",
"[",
"'enable_swagger_ui'",
"]",
")",
";",
"$",
"container",
"->",
"setParameter",
"(",
"'api_platform.enable_re_doc'",
",",
"$",
"config",
"[",
"'enable_re_doc'",
"]",
")",
";",
"}",
"$",
"container",
"->",
"setParameter",
"(",
"'api_platform.enable_swagger'",
",",
"$",
"config",
"[",
"'enable_swagger'",
"]",
")",
";",
"$",
"container",
"->",
"setParameter",
"(",
"'api_platform.swagger.api_keys'",
",",
"$",
"config",
"[",
"'swagger'",
"]",
"[",
"'api_keys'",
"]",
")",
";",
"}"
]
| Registers the Swagger, ReDoc and Swagger UI configuration. | [
"Registers",
"the",
"Swagger",
"ReDoc",
"and",
"Swagger",
"UI",
"configuration",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Bridge/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php#L296-L312 | train |
api-platform/core | src/Bridge/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php | ApiPlatformExtension.getFormats | private function getFormats(array $configFormats): array
{
$formats = [];
foreach ($configFormats as $format => $value) {
foreach ($value['mime_types'] as $mimeType) {
$formats[$format][] = $mimeType;
}
}
return $formats;
} | php | private function getFormats(array $configFormats): array
{
$formats = [];
foreach ($configFormats as $format => $value) {
foreach ($value['mime_types'] as $mimeType) {
$formats[$format][] = $mimeType;
}
}
return $formats;
} | [
"private",
"function",
"getFormats",
"(",
"array",
"$",
"configFormats",
")",
":",
"array",
"{",
"$",
"formats",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"configFormats",
"as",
"$",
"format",
"=>",
"$",
"value",
")",
"{",
"foreach",
"(",
"$",
"value",
"[",
"'mime_types'",
"]",
"as",
"$",
"mimeType",
")",
"{",
"$",
"formats",
"[",
"$",
"format",
"]",
"[",
"]",
"=",
"$",
"mimeType",
";",
"}",
"}",
"return",
"$",
"formats",
";",
"}"
]
| Normalizes the format from config to the one accepted by Symfony HttpFoundation. | [
"Normalizes",
"the",
"format",
"from",
"config",
"to",
"the",
"one",
"accepted",
"by",
"Symfony",
"HttpFoundation",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Bridge/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php#L488-L498 | train |
api-platform/core | src/JsonLd/Serializer/JsonLdContextTrait.php | JsonLdContextTrait.addJsonLdContext | private function addJsonLdContext(ContextBuilderInterface $contextBuilder, string $resourceClass, array &$context, array $data = []): array
{
if (isset($context['jsonld_has_context'])) {
return $data;
}
$context['jsonld_has_context'] = true;
if (isset($context['jsonld_embed_context'])) {
$data['@context'] = $contextBuilder->getResourceContext($resourceClass);
return $data;
}
$data['@context'] = $contextBuilder->getResourceContextUri($resourceClass);
return $data;
} | php | private function addJsonLdContext(ContextBuilderInterface $contextBuilder, string $resourceClass, array &$context, array $data = []): array
{
if (isset($context['jsonld_has_context'])) {
return $data;
}
$context['jsonld_has_context'] = true;
if (isset($context['jsonld_embed_context'])) {
$data['@context'] = $contextBuilder->getResourceContext($resourceClass);
return $data;
}
$data['@context'] = $contextBuilder->getResourceContextUri($resourceClass);
return $data;
} | [
"private",
"function",
"addJsonLdContext",
"(",
"ContextBuilderInterface",
"$",
"contextBuilder",
",",
"string",
"$",
"resourceClass",
",",
"array",
"&",
"$",
"context",
",",
"array",
"$",
"data",
"=",
"[",
"]",
")",
":",
"array",
"{",
"if",
"(",
"isset",
"(",
"$",
"context",
"[",
"'jsonld_has_context'",
"]",
")",
")",
"{",
"return",
"$",
"data",
";",
"}",
"$",
"context",
"[",
"'jsonld_has_context'",
"]",
"=",
"true",
";",
"if",
"(",
"isset",
"(",
"$",
"context",
"[",
"'jsonld_embed_context'",
"]",
")",
")",
"{",
"$",
"data",
"[",
"'@context'",
"]",
"=",
"$",
"contextBuilder",
"->",
"getResourceContext",
"(",
"$",
"resourceClass",
")",
";",
"return",
"$",
"data",
";",
"}",
"$",
"data",
"[",
"'@context'",
"]",
"=",
"$",
"contextBuilder",
"->",
"getResourceContextUri",
"(",
"$",
"resourceClass",
")",
";",
"return",
"$",
"data",
";",
"}"
]
| Updates the given JSON-LD document to add its @context key. | [
"Updates",
"the",
"given",
"JSON",
"-",
"LD",
"document",
"to",
"add",
"its"
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/JsonLd/Serializer/JsonLdContextTrait.php#L31-L48 | train |
api-platform/core | src/EventListener/AddFormatListener.php | AddFormatListener.addRequestFormats | private function addRequestFormats(Request $request, array $formats): void
{
foreach ($formats as $format => $mimeTypes) {
$request->setFormat($format, (array) $mimeTypes);
}
} | php | private function addRequestFormats(Request $request, array $formats): void
{
foreach ($formats as $format => $mimeTypes) {
$request->setFormat($format, (array) $mimeTypes);
}
} | [
"private",
"function",
"addRequestFormats",
"(",
"Request",
"$",
"request",
",",
"array",
"$",
"formats",
")",
":",
"void",
"{",
"foreach",
"(",
"$",
"formats",
"as",
"$",
"format",
"=>",
"$",
"mimeTypes",
")",
"{",
"$",
"request",
"->",
"setFormat",
"(",
"$",
"format",
",",
"(",
"array",
")",
"$",
"mimeTypes",
")",
";",
"}",
"}"
]
| Adds the supported formats to the request.
This is necessary for {@see Request::getMimeType} and {@see Request::getMimeTypes} to work. | [
"Adds",
"the",
"supported",
"formats",
"to",
"the",
"request",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/EventListener/AddFormatListener.php#L125-L130 | train |
api-platform/core | src/EventListener/AddFormatListener.php | AddFormatListener.getNotAcceptableHttpException | private function getNotAcceptableHttpException(string $accept, array $mimeTypes = null): NotAcceptableHttpException
{
if (null === $mimeTypes) {
$mimeTypes = array_keys($this->mimeTypes);
}
return new NotAcceptableHttpException(sprintf(
'Requested format "%s" is not supported. Supported MIME types are "%s".',
$accept,
implode('", "', $mimeTypes)
));
} | php | private function getNotAcceptableHttpException(string $accept, array $mimeTypes = null): NotAcceptableHttpException
{
if (null === $mimeTypes) {
$mimeTypes = array_keys($this->mimeTypes);
}
return new NotAcceptableHttpException(sprintf(
'Requested format "%s" is not supported. Supported MIME types are "%s".',
$accept,
implode('", "', $mimeTypes)
));
} | [
"private",
"function",
"getNotAcceptableHttpException",
"(",
"string",
"$",
"accept",
",",
"array",
"$",
"mimeTypes",
"=",
"null",
")",
":",
"NotAcceptableHttpException",
"{",
"if",
"(",
"null",
"===",
"$",
"mimeTypes",
")",
"{",
"$",
"mimeTypes",
"=",
"array_keys",
"(",
"$",
"this",
"->",
"mimeTypes",
")",
";",
"}",
"return",
"new",
"NotAcceptableHttpException",
"(",
"sprintf",
"(",
"'Requested format \"%s\" is not supported. Supported MIME types are \"%s\".'",
",",
"$",
"accept",
",",
"implode",
"(",
"'\", \"'",
",",
"$",
"mimeTypes",
")",
")",
")",
";",
"}"
]
| Retrieves an instance of NotAcceptableHttpException.
@param string[]|null $mimeTypes | [
"Retrieves",
"an",
"instance",
"of",
"NotAcceptableHttpException",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/EventListener/AddFormatListener.php#L154-L165 | train |
api-platform/core | src/Util/Reflection.php | Reflection.getProperty | public function getProperty(string $methodName): ?string
{
$pattern = implode('|', array_merge(self::ACCESSOR_PREFIXES, self::MUTATOR_PREFIXES));
if (preg_match('/^('.$pattern.')(.+)$/i', $methodName, $matches)) {
return $matches[2];
}
return null;
} | php | public function getProperty(string $methodName): ?string
{
$pattern = implode('|', array_merge(self::ACCESSOR_PREFIXES, self::MUTATOR_PREFIXES));
if (preg_match('/^('.$pattern.')(.+)$/i', $methodName, $matches)) {
return $matches[2];
}
return null;
} | [
"public",
"function",
"getProperty",
"(",
"string",
"$",
"methodName",
")",
":",
"?",
"string",
"{",
"$",
"pattern",
"=",
"implode",
"(",
"'|'",
",",
"array_merge",
"(",
"self",
"::",
"ACCESSOR_PREFIXES",
",",
"self",
"::",
"MUTATOR_PREFIXES",
")",
")",
";",
"if",
"(",
"preg_match",
"(",
"'/^('",
".",
"$",
"pattern",
".",
"')(.+)$/i'",
",",
"$",
"methodName",
",",
"$",
"matches",
")",
")",
"{",
"return",
"$",
"matches",
"[",
"2",
"]",
";",
"}",
"return",
"null",
";",
"}"
]
| Gets the property name associated with an accessor method. | [
"Gets",
"the",
"property",
"name",
"associated",
"with",
"an",
"accessor",
"method",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/Util/Reflection.php#L31-L40 | train |
api-platform/core | src/DataProvider/Pagination.php | Pagination.getOffset | public function getOffset(string $resourceClass = null, string $operationName = null, array $context = []): int
{
$graphql = $context['graphql'] ?? false;
$limit = $this->getLimit($resourceClass, $operationName, $context);
if ($graphql && null !== ($after = $this->getParameterFromContext($context, 'after'))) {
return false === ($after = base64_decode($after, true)) ? 0 : (int) $after + 1;
}
if ($graphql && null !== ($before = $this->getParameterFromContext($context, 'before'))) {
return ($offset = (false === ($before = base64_decode($before, true)) ? 0 : (int) $before - $limit)) < 0 ? 0 : $offset;
}
if ($graphql && null !== ($last = $this->getParameterFromContext($context, 'last'))) {
return ($offset = ($context['count'] ?? 0) - $last) < 0 ? 0 : $offset;
}
return ($this->getPage($context) - 1) * $limit;
} | php | public function getOffset(string $resourceClass = null, string $operationName = null, array $context = []): int
{
$graphql = $context['graphql'] ?? false;
$limit = $this->getLimit($resourceClass, $operationName, $context);
if ($graphql && null !== ($after = $this->getParameterFromContext($context, 'after'))) {
return false === ($after = base64_decode($after, true)) ? 0 : (int) $after + 1;
}
if ($graphql && null !== ($before = $this->getParameterFromContext($context, 'before'))) {
return ($offset = (false === ($before = base64_decode($before, true)) ? 0 : (int) $before - $limit)) < 0 ? 0 : $offset;
}
if ($graphql && null !== ($last = $this->getParameterFromContext($context, 'last'))) {
return ($offset = ($context['count'] ?? 0) - $last) < 0 ? 0 : $offset;
}
return ($this->getPage($context) - 1) * $limit;
} | [
"public",
"function",
"getOffset",
"(",
"string",
"$",
"resourceClass",
"=",
"null",
",",
"string",
"$",
"operationName",
"=",
"null",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
":",
"int",
"{",
"$",
"graphql",
"=",
"$",
"context",
"[",
"'graphql'",
"]",
"??",
"false",
";",
"$",
"limit",
"=",
"$",
"this",
"->",
"getLimit",
"(",
"$",
"resourceClass",
",",
"$",
"operationName",
",",
"$",
"context",
")",
";",
"if",
"(",
"$",
"graphql",
"&&",
"null",
"!==",
"(",
"$",
"after",
"=",
"$",
"this",
"->",
"getParameterFromContext",
"(",
"$",
"context",
",",
"'after'",
")",
")",
")",
"{",
"return",
"false",
"===",
"(",
"$",
"after",
"=",
"base64_decode",
"(",
"$",
"after",
",",
"true",
")",
")",
"?",
"0",
":",
"(",
"int",
")",
"$",
"after",
"+",
"1",
";",
"}",
"if",
"(",
"$",
"graphql",
"&&",
"null",
"!==",
"(",
"$",
"before",
"=",
"$",
"this",
"->",
"getParameterFromContext",
"(",
"$",
"context",
",",
"'before'",
")",
")",
")",
"{",
"return",
"(",
"$",
"offset",
"=",
"(",
"false",
"===",
"(",
"$",
"before",
"=",
"base64_decode",
"(",
"$",
"before",
",",
"true",
")",
")",
"?",
"0",
":",
"(",
"int",
")",
"$",
"before",
"-",
"$",
"limit",
")",
")",
"<",
"0",
"?",
"0",
":",
"$",
"offset",
";",
"}",
"if",
"(",
"$",
"graphql",
"&&",
"null",
"!==",
"(",
"$",
"last",
"=",
"$",
"this",
"->",
"getParameterFromContext",
"(",
"$",
"context",
",",
"'last'",
")",
")",
")",
"{",
"return",
"(",
"$",
"offset",
"=",
"(",
"$",
"context",
"[",
"'count'",
"]",
"??",
"0",
")",
"-",
"$",
"last",
")",
"<",
"0",
"?",
"0",
":",
"$",
"offset",
";",
"}",
"return",
"(",
"$",
"this",
"->",
"getPage",
"(",
"$",
"context",
")",
"-",
"1",
")",
"*",
"$",
"limit",
";",
"}"
]
| Gets the current offset. | [
"Gets",
"the",
"current",
"offset",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/DataProvider/Pagination.php#L71-L90 | train |
api-platform/core | src/DataProvider/Pagination.php | Pagination.getLimit | public function getLimit(string $resourceClass = null, string $operationName = null, array $context = []): int
{
$graphql = $context['graphql'] ?? false;
$limit = $this->options['items_per_page'];
$clientLimit = $this->options['client_items_per_page'];
if (null !== $resourceClass) {
$resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
$limit = $resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_items_per_page', $limit, true);
$clientLimit = $resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_client_items_per_page', $clientLimit, true);
}
if ($graphql && null !== ($first = $this->getParameterFromContext($context, 'first'))) {
$limit = $first;
}
if ($graphql && null !== ($last = $this->getParameterFromContext($context, 'last'))) {
$limit = $last;
}
if ($graphql && null !== ($before = $this->getParameterFromContext($context, 'before'))
&& (false === ($before = base64_decode($before, true)) ? 0 : (int) $before - $limit) < 0) {
$limit = (int) $before;
}
if ($clientLimit) {
$limit = (int) $this->getParameterFromContext($context, $this->options['items_per_page_parameter_name'], $limit);
$maxItemsPerPage = $this->options['maximum_items_per_page'];
if (null !== $resourceClass) {
$resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
$maxItemsPerPage = $resourceMetadata->getCollectionOperationAttribute($operationName, 'maximum_items_per_page', $maxItemsPerPage, true);
}
if (null !== $maxItemsPerPage && $limit > $maxItemsPerPage) {
$limit = $maxItemsPerPage;
}
}
if (0 > $limit) {
throw new InvalidArgumentException('Limit should not be less than 0');
}
return $limit;
} | php | public function getLimit(string $resourceClass = null, string $operationName = null, array $context = []): int
{
$graphql = $context['graphql'] ?? false;
$limit = $this->options['items_per_page'];
$clientLimit = $this->options['client_items_per_page'];
if (null !== $resourceClass) {
$resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
$limit = $resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_items_per_page', $limit, true);
$clientLimit = $resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_client_items_per_page', $clientLimit, true);
}
if ($graphql && null !== ($first = $this->getParameterFromContext($context, 'first'))) {
$limit = $first;
}
if ($graphql && null !== ($last = $this->getParameterFromContext($context, 'last'))) {
$limit = $last;
}
if ($graphql && null !== ($before = $this->getParameterFromContext($context, 'before'))
&& (false === ($before = base64_decode($before, true)) ? 0 : (int) $before - $limit) < 0) {
$limit = (int) $before;
}
if ($clientLimit) {
$limit = (int) $this->getParameterFromContext($context, $this->options['items_per_page_parameter_name'], $limit);
$maxItemsPerPage = $this->options['maximum_items_per_page'];
if (null !== $resourceClass) {
$resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
$maxItemsPerPage = $resourceMetadata->getCollectionOperationAttribute($operationName, 'maximum_items_per_page', $maxItemsPerPage, true);
}
if (null !== $maxItemsPerPage && $limit > $maxItemsPerPage) {
$limit = $maxItemsPerPage;
}
}
if (0 > $limit) {
throw new InvalidArgumentException('Limit should not be less than 0');
}
return $limit;
} | [
"public",
"function",
"getLimit",
"(",
"string",
"$",
"resourceClass",
"=",
"null",
",",
"string",
"$",
"operationName",
"=",
"null",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
":",
"int",
"{",
"$",
"graphql",
"=",
"$",
"context",
"[",
"'graphql'",
"]",
"??",
"false",
";",
"$",
"limit",
"=",
"$",
"this",
"->",
"options",
"[",
"'items_per_page'",
"]",
";",
"$",
"clientLimit",
"=",
"$",
"this",
"->",
"options",
"[",
"'client_items_per_page'",
"]",
";",
"if",
"(",
"null",
"!==",
"$",
"resourceClass",
")",
"{",
"$",
"resourceMetadata",
"=",
"$",
"this",
"->",
"resourceMetadataFactory",
"->",
"create",
"(",
"$",
"resourceClass",
")",
";",
"$",
"limit",
"=",
"$",
"resourceMetadata",
"->",
"getCollectionOperationAttribute",
"(",
"$",
"operationName",
",",
"'pagination_items_per_page'",
",",
"$",
"limit",
",",
"true",
")",
";",
"$",
"clientLimit",
"=",
"$",
"resourceMetadata",
"->",
"getCollectionOperationAttribute",
"(",
"$",
"operationName",
",",
"'pagination_client_items_per_page'",
",",
"$",
"clientLimit",
",",
"true",
")",
";",
"}",
"if",
"(",
"$",
"graphql",
"&&",
"null",
"!==",
"(",
"$",
"first",
"=",
"$",
"this",
"->",
"getParameterFromContext",
"(",
"$",
"context",
",",
"'first'",
")",
")",
")",
"{",
"$",
"limit",
"=",
"$",
"first",
";",
"}",
"if",
"(",
"$",
"graphql",
"&&",
"null",
"!==",
"(",
"$",
"last",
"=",
"$",
"this",
"->",
"getParameterFromContext",
"(",
"$",
"context",
",",
"'last'",
")",
")",
")",
"{",
"$",
"limit",
"=",
"$",
"last",
";",
"}",
"if",
"(",
"$",
"graphql",
"&&",
"null",
"!==",
"(",
"$",
"before",
"=",
"$",
"this",
"->",
"getParameterFromContext",
"(",
"$",
"context",
",",
"'before'",
")",
")",
"&&",
"(",
"false",
"===",
"(",
"$",
"before",
"=",
"base64_decode",
"(",
"$",
"before",
",",
"true",
")",
")",
"?",
"0",
":",
"(",
"int",
")",
"$",
"before",
"-",
"$",
"limit",
")",
"<",
"0",
")",
"{",
"$",
"limit",
"=",
"(",
"int",
")",
"$",
"before",
";",
"}",
"if",
"(",
"$",
"clientLimit",
")",
"{",
"$",
"limit",
"=",
"(",
"int",
")",
"$",
"this",
"->",
"getParameterFromContext",
"(",
"$",
"context",
",",
"$",
"this",
"->",
"options",
"[",
"'items_per_page_parameter_name'",
"]",
",",
"$",
"limit",
")",
";",
"$",
"maxItemsPerPage",
"=",
"$",
"this",
"->",
"options",
"[",
"'maximum_items_per_page'",
"]",
";",
"if",
"(",
"null",
"!==",
"$",
"resourceClass",
")",
"{",
"$",
"resourceMetadata",
"=",
"$",
"this",
"->",
"resourceMetadataFactory",
"->",
"create",
"(",
"$",
"resourceClass",
")",
";",
"$",
"maxItemsPerPage",
"=",
"$",
"resourceMetadata",
"->",
"getCollectionOperationAttribute",
"(",
"$",
"operationName",
",",
"'maximum_items_per_page'",
",",
"$",
"maxItemsPerPage",
",",
"true",
")",
";",
"}",
"if",
"(",
"null",
"!==",
"$",
"maxItemsPerPage",
"&&",
"$",
"limit",
">",
"$",
"maxItemsPerPage",
")",
"{",
"$",
"limit",
"=",
"$",
"maxItemsPerPage",
";",
"}",
"}",
"if",
"(",
"0",
">",
"$",
"limit",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Limit should not be less than 0'",
")",
";",
"}",
"return",
"$",
"limit",
";",
"}"
]
| Gets the current limit.
@throws InvalidArgumentException | [
"Gets",
"the",
"current",
"limit",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/DataProvider/Pagination.php#L97-L142 | train |
api-platform/core | src/DataProvider/Pagination.php | Pagination.getPagination | public function getPagination(string $resourceClass = null, string $operationName = null, array $context = []): array
{
$page = $this->getPage($context);
$limit = $this->getLimit($resourceClass, $operationName, $context);
if (0 === $limit && 1 < $page) {
throw new InvalidArgumentException('Page should not be greater than 1 if limit is equal to 0');
}
return [$page, $this->getOffset($resourceClass, $operationName, $context), $limit];
} | php | public function getPagination(string $resourceClass = null, string $operationName = null, array $context = []): array
{
$page = $this->getPage($context);
$limit = $this->getLimit($resourceClass, $operationName, $context);
if (0 === $limit && 1 < $page) {
throw new InvalidArgumentException('Page should not be greater than 1 if limit is equal to 0');
}
return [$page, $this->getOffset($resourceClass, $operationName, $context), $limit];
} | [
"public",
"function",
"getPagination",
"(",
"string",
"$",
"resourceClass",
"=",
"null",
",",
"string",
"$",
"operationName",
"=",
"null",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
":",
"array",
"{",
"$",
"page",
"=",
"$",
"this",
"->",
"getPage",
"(",
"$",
"context",
")",
";",
"$",
"limit",
"=",
"$",
"this",
"->",
"getLimit",
"(",
"$",
"resourceClass",
",",
"$",
"operationName",
",",
"$",
"context",
")",
";",
"if",
"(",
"0",
"===",
"$",
"limit",
"&&",
"1",
"<",
"$",
"page",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Page should not be greater than 1 if limit is equal to 0'",
")",
";",
"}",
"return",
"[",
"$",
"page",
",",
"$",
"this",
"->",
"getOffset",
"(",
"$",
"resourceClass",
",",
"$",
"operationName",
",",
"$",
"context",
")",
",",
"$",
"limit",
"]",
";",
"}"
]
| Gets info about the pagination.
Returns an array with the following info as values:
- the page {@see Pagination::getPage()}
- the offset {@see Pagination::getOffset()}
- the limit {@see Pagination::getLimit()}
@throws InvalidArgumentException | [
"Gets",
"info",
"about",
"the",
"pagination",
"."
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/DataProvider/Pagination.php#L154-L164 | train |
api-platform/core | src/DataProvider/Pagination.php | Pagination.isEnabled | public function isEnabled(string $resourceClass = null, string $operationName = null, array $context = []): bool
{
return $this->getEnabled($context, $resourceClass, $operationName);
} | php | public function isEnabled(string $resourceClass = null, string $operationName = null, array $context = []): bool
{
return $this->getEnabled($context, $resourceClass, $operationName);
} | [
"public",
"function",
"isEnabled",
"(",
"string",
"$",
"resourceClass",
"=",
"null",
",",
"string",
"$",
"operationName",
"=",
"null",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
":",
"bool",
"{",
"return",
"$",
"this",
"->",
"getEnabled",
"(",
"$",
"context",
",",
"$",
"resourceClass",
",",
"$",
"operationName",
")",
";",
"}"
]
| Is the pagination enabled? | [
"Is",
"the",
"pagination",
"enabled?"
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/DataProvider/Pagination.php#L169-L172 | train |
api-platform/core | src/DataProvider/Pagination.php | Pagination.isPartialEnabled | public function isPartialEnabled(string $resourceClass = null, string $operationName = null, array $context = []): bool
{
return $this->getEnabled($context, $resourceClass, $operationName, true);
} | php | public function isPartialEnabled(string $resourceClass = null, string $operationName = null, array $context = []): bool
{
return $this->getEnabled($context, $resourceClass, $operationName, true);
} | [
"public",
"function",
"isPartialEnabled",
"(",
"string",
"$",
"resourceClass",
"=",
"null",
",",
"string",
"$",
"operationName",
"=",
"null",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
":",
"bool",
"{",
"return",
"$",
"this",
"->",
"getEnabled",
"(",
"$",
"context",
",",
"$",
"resourceClass",
",",
"$",
"operationName",
",",
"true",
")",
";",
"}"
]
| Is the partial pagination enabled? | [
"Is",
"the",
"partial",
"pagination",
"enabled?"
]
| 0888bf33429a37d031345bf7c720f23010a50de4 | https://github.com/api-platform/core/blob/0888bf33429a37d031345bf7c720f23010a50de4/src/DataProvider/Pagination.php#L177-L180 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.