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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
Domraider/rxnet | src/Rxnet/Statsd/Statsd.php | Statsd.decrement | public function decrement($stats, $sampleRate = 1, array $tags = null)
{
return $this->updateStats($stats, -1, $sampleRate, $tags);
} | php | public function decrement($stats, $sampleRate = 1, array $tags = null)
{
return $this->updateStats($stats, -1, $sampleRate, $tags);
} | [
"public",
"function",
"decrement",
"(",
"$",
"stats",
",",
"$",
"sampleRate",
"=",
"1",
",",
"array",
"$",
"tags",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"updateStats",
"(",
"$",
"stats",
",",
"-",
"1",
",",
"$",
"sampleRate",
",",
"$"... | Decrements one or more stats counters.
@param string|array $stats The metric(s) to decrement.
@param float|1 $sampleRate the rate (0-1) for sampling.
@param array|null $tags
@return Observable | [
"Decrements",
"one",
"or",
"more",
"stats",
"counters",
"."
] | 1dcbf616dc5999c6ac28b8fd858ab234d2c5e723 | https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/Statsd/Statsd.php#L126-L129 | train |
Domraider/rxnet | src/Rxnet/Statsd/Statsd.php | Statsd.updateStats | public function updateStats($stats, $delta = 1, $sampleRate = 1, array $tags = null)
{
if (!is_array($stats)) {
$stats = array($stats);
}
$data = array();
foreach ($stats as $stat) {
$data[$stat] = "$delta|c";
}
return $this->send($data, $sampleRate, $tags);
} | php | public function updateStats($stats, $delta = 1, $sampleRate = 1, array $tags = null)
{
if (!is_array($stats)) {
$stats = array($stats);
}
$data = array();
foreach ($stats as $stat) {
$data[$stat] = "$delta|c";
}
return $this->send($data, $sampleRate, $tags);
} | [
"public",
"function",
"updateStats",
"(",
"$",
"stats",
",",
"$",
"delta",
"=",
"1",
",",
"$",
"sampleRate",
"=",
"1",
",",
"array",
"$",
"tags",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"stats",
")",
")",
"{",
"$",
"stats",
... | Updates one or more stats counters by arbitrary amounts.
@param string|array $stats The metric(s) to update. Should be either a string or array of metrics.
@param int|1 $delta The amount to increment/decrement each metric by.
@param float|1 $sampleRate the rate (0-1) for sampling.
@param array|string $tags Key Value array of Tag => Value, or single tag as string
@return Observable | [
"Updates",
"one",
"or",
"more",
"stats",
"counters",
"by",
"arbitrary",
"amounts",
"."
] | 1dcbf616dc5999c6ac28b8fd858ab234d2c5e723 | https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/Statsd/Statsd.php#L141-L151 | train |
joecampo/random-user-agent | src/UserAgent.php | UserAgent.random | public static function random($filterBy = [])
{
$agents = self::loadUserAgents($filterBy);
if (empty($agents)) {
throw new \Exception('No user agents matched the filter');
}
return $agents[mt_rand(0, count($agents) - 1)];
} | php | public static function random($filterBy = [])
{
$agents = self::loadUserAgents($filterBy);
if (empty($agents)) {
throw new \Exception('No user agents matched the filter');
}
return $agents[mt_rand(0, count($agents) - 1)];
} | [
"public",
"static",
"function",
"random",
"(",
"$",
"filterBy",
"=",
"[",
"]",
")",
"{",
"$",
"agents",
"=",
"self",
"::",
"loadUserAgents",
"(",
"$",
"filterBy",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"agents",
")",
")",
"{",
"throw",
"new",
"\\"... | Grab a random user agent from the library's agent list
@param array $filterBy
@return string
@throws \Exception | [
"Grab",
"a",
"random",
"user",
"agent",
"from",
"the",
"library",
"s",
"agent",
"list"
] | 4a88bd90f66ca398b050b19848e3c6ea143ce8a0 | https://github.com/joecampo/random-user-agent/blob/4a88bd90f66ca398b050b19848e3c6ea143ce8a0/src/UserAgent.php#L31-L40 | train |
joecampo/random-user-agent | src/UserAgent.php | UserAgent.validateFilter | private static function validateFilter($filterBy = [])
{
// Components of $filterBy that will not be ignored
$filterParams = [
'agent_name',
'agent_type',
'device_type',
'os_name',
'os_type',
];
$outputFilter = [];
foreach ($filterParams as $field) {
if (!empty($filterBy[$field])) {
$outputFilter[$field] = $filterBy[$field];
}
}
return $outputFilter;
} | php | private static function validateFilter($filterBy = [])
{
// Components of $filterBy that will not be ignored
$filterParams = [
'agent_name',
'agent_type',
'device_type',
'os_name',
'os_type',
];
$outputFilter = [];
foreach ($filterParams as $field) {
if (!empty($filterBy[$field])) {
$outputFilter[$field] = $filterBy[$field];
}
}
return $outputFilter;
} | [
"private",
"static",
"function",
"validateFilter",
"(",
"$",
"filterBy",
"=",
"[",
"]",
")",
"{",
"// Components of $filterBy that will not be ignored",
"$",
"filterParams",
"=",
"[",
"'agent_name'",
",",
"'agent_type'",
",",
"'device_type'",
",",
"'os_name'",
",",
... | Validates the filter so that no unexpected values make their way through
@param array $filterBy
@return array | [
"Validates",
"the",
"filter",
"so",
"that",
"no",
"unexpected",
"values",
"make",
"their",
"way",
"through"
] | 4a88bd90f66ca398b050b19848e3c6ea143ce8a0 | https://github.com/joecampo/random-user-agent/blob/4a88bd90f66ca398b050b19848e3c6ea143ce8a0/src/UserAgent.php#L127-L147 | train |
joecampo/random-user-agent | src/UserAgent.php | UserAgent.loadUserAgents | private static function loadUserAgents($filterBy = [])
{
$filterBy = self::validateFilter($filterBy);
$agentDetails = self::getAgentDetails();
$agentStrings = [];
for ($i = 0; $i < count($agentDetails); $i++) {
foreach ($filterBy as $key => $value) {
if (!isset($agentDetails[$i][$key]) || !self::inFilter($agentDetails[$i][$key], $value)) {
continue 2;
}
}
$agentStrings[] = $agentDetails[$i]['agent_string'];
}
return array_values($agentStrings);
} | php | private static function loadUserAgents($filterBy = [])
{
$filterBy = self::validateFilter($filterBy);
$agentDetails = self::getAgentDetails();
$agentStrings = [];
for ($i = 0; $i < count($agentDetails); $i++) {
foreach ($filterBy as $key => $value) {
if (!isset($agentDetails[$i][$key]) || !self::inFilter($agentDetails[$i][$key], $value)) {
continue 2;
}
}
$agentStrings[] = $agentDetails[$i]['agent_string'];
}
return array_values($agentStrings);
} | [
"private",
"static",
"function",
"loadUserAgents",
"(",
"$",
"filterBy",
"=",
"[",
"]",
")",
"{",
"$",
"filterBy",
"=",
"self",
"::",
"validateFilter",
"(",
"$",
"filterBy",
")",
";",
"$",
"agentDetails",
"=",
"self",
"::",
"getAgentDetails",
"(",
")",
"... | Returns an array of user agents that match a filter if one is provided
@param array $filterBy
@return array | [
"Returns",
"an",
"array",
"of",
"user",
"agents",
"that",
"match",
"a",
"filter",
"if",
"one",
"is",
"provided"
] | 4a88bd90f66ca398b050b19848e3c6ea143ce8a0 | https://github.com/joecampo/random-user-agent/blob/4a88bd90f66ca398b050b19848e3c6ea143ce8a0/src/UserAgent.php#L155-L172 | train |
libgraviton/graviton | src/Graviton/CoreBundle/Controller/VersionController.php | VersionController.versionsAction | public function versionsAction()
{
$versions = [
'versions' => $this->versionInformation
];
$response = $this->getResponse()
->setStatusCode(Response::HTTP_OK)
->setContent(json_encode($versions));
$response->headers->set('Content-Type', 'application/json');
return $response;
} | php | public function versionsAction()
{
$versions = [
'versions' => $this->versionInformation
];
$response = $this->getResponse()
->setStatusCode(Response::HTTP_OK)
->setContent(json_encode($versions));
$response->headers->set('Content-Type', 'application/json');
return $response;
} | [
"public",
"function",
"versionsAction",
"(",
")",
"{",
"$",
"versions",
"=",
"[",
"'versions'",
"=>",
"$",
"this",
"->",
"versionInformation",
"]",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"getResponse",
"(",
")",
"->",
"setStatusCode",
"(",
"Response... | Returns all version numbers
@return \Symfony\Component\HttpFoundation\Response $response Response with result or error | [
"Returns",
"all",
"version",
"numbers"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Controller/VersionController.php#L38-L51 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php | ConstraintUtils.getSerializedEntity | public function getSerializedEntity($documentClass, $recordId, array $fields = null)
{
if (is_array($fields)) {
return $this->getSingleEntity($documentClass, $recordId, $fields);
}
if (!isset($this->entities[$documentClass][$recordId])) {
$current = $this->getSingleEntity($documentClass, $recordId, $fields);
if (is_null($current)) {
$this->entities[$documentClass][$recordId] = null;
} else {
$this->entities[$documentClass][$recordId] = $current;
}
}
return $this->entities[$documentClass][$recordId];
} | php | public function getSerializedEntity($documentClass, $recordId, array $fields = null)
{
if (is_array($fields)) {
return $this->getSingleEntity($documentClass, $recordId, $fields);
}
if (!isset($this->entities[$documentClass][$recordId])) {
$current = $this->getSingleEntity($documentClass, $recordId, $fields);
if (is_null($current)) {
$this->entities[$documentClass][$recordId] = null;
} else {
$this->entities[$documentClass][$recordId] = $current;
}
}
return $this->entities[$documentClass][$recordId];
} | [
"public",
"function",
"getSerializedEntity",
"(",
"$",
"documentClass",
",",
"$",
"recordId",
",",
"array",
"$",
"fields",
"=",
"null",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"fields",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getSingleEntity",
"(... | Gets a entity from the database as a generic object. All constraints that need the saved data to compare
values or anything should call this function to get what they need. As this is cached in the instance,
it will fetched only once even if multiple constraints need that object.
@param string $documentClass document class
@param string $recordId record id
@param array $fields if you only need certain fields, you can specify them here
@throws \Exception
@return object|null entity | [
"Gets",
"a",
"entity",
"from",
"the",
"database",
"as",
"a",
"generic",
"object",
".",
"All",
"constraints",
"that",
"need",
"the",
"saved",
"data",
"to",
"compare",
"values",
"or",
"anything",
"should",
"call",
"this",
"function",
"to",
"get",
"what",
"th... | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php#L71-L88 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php | ConstraintUtils.getSingleEntity | private function getSingleEntity($documentClass, $recordId, array $fields = null)
{
// only get certain fields! will not be cached in instance
$queryBuilder = $this->dm->createQueryBuilder($documentClass);
$queryBuilder->field('id')->equals($recordId);
if (is_array($fields)) {
$queryBuilder->select($fields);
}
$query = $queryBuilder->getQuery();
$query->setRefresh(true);
$records = array_values($query->execute()->toArray());
if (is_array($records) && !empty($records)) {
return json_decode($this->restUtils->serializeContent($records[0]));
}
return null;
} | php | private function getSingleEntity($documentClass, $recordId, array $fields = null)
{
// only get certain fields! will not be cached in instance
$queryBuilder = $this->dm->createQueryBuilder($documentClass);
$queryBuilder->field('id')->equals($recordId);
if (is_array($fields)) {
$queryBuilder->select($fields);
}
$query = $queryBuilder->getQuery();
$query->setRefresh(true);
$records = array_values($query->execute()->toArray());
if (is_array($records) && !empty($records)) {
return json_decode($this->restUtils->serializeContent($records[0]));
}
return null;
} | [
"private",
"function",
"getSingleEntity",
"(",
"$",
"documentClass",
",",
"$",
"recordId",
",",
"array",
"$",
"fields",
"=",
"null",
")",
"{",
"// only get certain fields! will not be cached in instance",
"$",
"queryBuilder",
"=",
"$",
"this",
"->",
"dm",
"->",
"c... | returns an already serialized entity depending on fields, making sure the
query is fresh
@param string $documentClass document class
@param string $recordId record id
@param array $fields if you only need certain fields, you can specify them here
@throws \Exception
@return object|null entity | [
"returns",
"an",
"already",
"serialized",
"entity",
"depending",
"on",
"fields",
"making",
"sure",
"the",
"query",
"is",
"fresh"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php#L102-L119 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php | ConstraintUtils.getCurrentRequestMethod | public function getCurrentRequestMethod()
{
if ($this->requestStack->getCurrentRequest() instanceof Request) {
return $this->requestStack->getCurrentRequest()->getMethod();
}
return null;
} | php | public function getCurrentRequestMethod()
{
if ($this->requestStack->getCurrentRequest() instanceof Request) {
return $this->requestStack->getCurrentRequest()->getMethod();
}
return null;
} | [
"public",
"function",
"getCurrentRequestMethod",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"requestStack",
"->",
"getCurrentRequest",
"(",
")",
"instanceof",
"Request",
")",
"{",
"return",
"$",
"this",
"->",
"requestStack",
"->",
"getCurrentRequest",
"(",
"... | Returns the request method of the current request
@return null|string the request method | [
"Returns",
"the",
"request",
"method",
"of",
"the",
"current",
"request"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php#L159-L165 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php | ConstraintUtils.getCurrentRequestContent | public function getCurrentRequestContent()
{
if ($this->requestStack->getCurrentRequest() instanceof Request) {
return $this->requestStack->getCurrentRequest()->getContent();
}
return null;
} | php | public function getCurrentRequestContent()
{
if ($this->requestStack->getCurrentRequest() instanceof Request) {
return $this->requestStack->getCurrentRequest()->getContent();
}
return null;
} | [
"public",
"function",
"getCurrentRequestContent",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"requestStack",
"->",
"getCurrentRequest",
"(",
")",
"instanceof",
"Request",
")",
"{",
"return",
"$",
"this",
"->",
"requestStack",
"->",
"getCurrentRequest",
"(",
... | Returns the current request content
@return bool|null|resource|string the content | [
"Returns",
"the",
"current",
"request",
"content"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php#L172-L178 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php | ConstraintUtils.getNormalizedPathFromPointer | public function getNormalizedPathFromPointer(JsonPointer $pointer = null)
{
$result = array_map(
function ($path) {
return sprintf(is_numeric($path) ? '[%d]' : '.%s', $path);
},
$pointer->getPropertyPaths()
);
return trim(implode('', $result), '.');
} | php | public function getNormalizedPathFromPointer(JsonPointer $pointer = null)
{
$result = array_map(
function ($path) {
return sprintf(is_numeric($path) ? '[%d]' : '.%s', $path);
},
$pointer->getPropertyPaths()
);
return trim(implode('', $result), '.');
} | [
"public",
"function",
"getNormalizedPathFromPointer",
"(",
"JsonPointer",
"$",
"pointer",
"=",
"null",
")",
"{",
"$",
"result",
"=",
"array_map",
"(",
"function",
"(",
"$",
"path",
")",
"{",
"return",
"sprintf",
"(",
"is_numeric",
"(",
"$",
"path",
")",
"?... | own function to get standard path from a JsonPointer object
@param JsonPointer|null $pointer pointer
@return string path as string | [
"own",
"function",
"to",
"get",
"standard",
"path",
"from",
"a",
"JsonPointer",
"object"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php#L208-L217 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php | ConstraintUtils.onSchemaValidation | public function onSchemaValidation(ConstraintEventSchema $event)
{
$this->currentSchema = $event->getSchema();
$this->currentData = $event->getElement();
} | php | public function onSchemaValidation(ConstraintEventSchema $event)
{
$this->currentSchema = $event->getSchema();
$this->currentData = $event->getElement();
} | [
"public",
"function",
"onSchemaValidation",
"(",
"ConstraintEventSchema",
"$",
"event",
")",
"{",
"$",
"this",
"->",
"currentSchema",
"=",
"$",
"event",
"->",
"getSchema",
"(",
")",
";",
"$",
"this",
"->",
"currentData",
"=",
"$",
"event",
"->",
"getElement"... | called on the first schema validation, before anything else.
@param ConstraintEventSchema $event event
@return void | [
"called",
"on",
"the",
"first",
"schema",
"validation",
"before",
"anything",
"else",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/ConstraintUtils.php#L226-L230 | train |
libgraviton/graviton | src/Graviton/RestBundle/Listener/SpecialMimetypeRequestListener.php | SpecialMimetypeRequestListener.onKernelRequest | public function onKernelRequest(RestEvent $event)
{
$request = $event->getRequest();
if ($request->headers->has('Accept')) {
$format = $request->getFormat($request->headers->get('Accept'));
if (empty($format)) {
foreach ($this->container->getParameter('graviton.rest.special_mimetypes') as $format => $types) {
$mimetypes = $request->getMimeType($format);
if (!empty($mimetypes)) {
$mimetypes = is_array($mimetypes)? $mimetypes : array($mimetypes);
$types = array_unique(array_merge_recursive($mimetypes, $types));
}
$request->setFormat($format, $types);
}
}
}
} | php | public function onKernelRequest(RestEvent $event)
{
$request = $event->getRequest();
if ($request->headers->has('Accept')) {
$format = $request->getFormat($request->headers->get('Accept'));
if (empty($format)) {
foreach ($this->container->getParameter('graviton.rest.special_mimetypes') as $format => $types) {
$mimetypes = $request->getMimeType($format);
if (!empty($mimetypes)) {
$mimetypes = is_array($mimetypes)? $mimetypes : array($mimetypes);
$types = array_unique(array_merge_recursive($mimetypes, $types));
}
$request->setFormat($format, $types);
}
}
}
} | [
"public",
"function",
"onKernelRequest",
"(",
"RestEvent",
"$",
"event",
")",
"{",
"$",
"request",
"=",
"$",
"event",
"->",
"getRequest",
"(",
")",
";",
"if",
"(",
"$",
"request",
"->",
"headers",
"->",
"has",
"(",
"'Accept'",
")",
")",
"{",
"$",
"fo... | Adds the configured formats and mimetypes to the request.
@param RestEvent $event Event
@return void|null | [
"Adds",
"the",
"configured",
"formats",
"and",
"mimetypes",
"to",
"the",
"request",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Listener/SpecialMimetypeRequestListener.php#L42-L61 | train |
libgraviton/graviton | src/Graviton/CacheBundle/Listener/ETagResponseListener.php | ETagResponseListener.onKernelResponse | public function onKernelResponse(FilterResponseEvent $event)
{
$response = $event->getResponse();
/**
* the "W/" prefix is necessary to qualify it as a "weak" Etag.
* only then a proxy like nginx will leave the tag alone because a strong cannot
* match if gzip is applied.
*/
$response->headers->set('ETag', 'W/'.sha1($response->getContent()));
} | php | public function onKernelResponse(FilterResponseEvent $event)
{
$response = $event->getResponse();
/**
* the "W/" prefix is necessary to qualify it as a "weak" Etag.
* only then a proxy like nginx will leave the tag alone because a strong cannot
* match if gzip is applied.
*/
$response->headers->set('ETag', 'W/'.sha1($response->getContent()));
} | [
"public",
"function",
"onKernelResponse",
"(",
"FilterResponseEvent",
"$",
"event",
")",
"{",
"$",
"response",
"=",
"$",
"event",
"->",
"getResponse",
"(",
")",
";",
"/**\n * the \"W/\" prefix is necessary to qualify it as a \"weak\" Etag.\n * only then a proxy ... | add a ETag header to the response
@param FilterResponseEvent $event response listener event
@return void | [
"add",
"a",
"ETag",
"header",
"to",
"the",
"response"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CacheBundle/Listener/ETagResponseListener.php#L26-L36 | train |
libgraviton/graviton | src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php | EventStatusLinkResponseListener.onKernelResponse | public function onKernelResponse(FilterResponseEvent $event)
{
/**
* @var Response $response
*/
$response = $event->getResponse();
// exit if not master request, uninteresting method or an error occurred
if (!$event->isMasterRequest() || $this->isNotConcerningRequest() || !$response->isSuccessful()) {
return;
}
// we can always safely call this, it doesn't need much resources.
// only if we have subscribers, it will create more load as it persists an EventStatus
$queueEvent = $this->createQueueEventObject();
if (!empty($queueEvent->getStatusurl()) && !empty($queueEvent->getEvent())) {
$linkHeader = LinkHeader::fromResponse($response);
$linkHeader->add(
new LinkHeaderItem(
$queueEvent->getStatusurl(),
array('rel' => 'eventStatus')
)
);
$response->headers->set(
'Link',
(string) $linkHeader
);
}
// let's send it to the queue(s) if appropriate
if (!empty($queueEvent->getEvent())) {
$queuesForEvent = $this->getSubscribedWorkerIds($queueEvent);
// if needed and activated, change urls relative to workers
if (!empty($queuesForEvent) && $this->workerRelativeUrl instanceof Uri) {
$queueEvent = $this->getWorkerQueueEvent($queueEvent);
}
foreach ($queuesForEvent as $queueForEvent) {
// declare the Queue for the Event if its not there already declared
$this->rabbitMqProducer->getChannel()->queue_declare($queueForEvent, false, true, false, false);
$this->rabbitMqProducer->publish(json_encode($queueEvent), $queueForEvent);
}
}
} | php | public function onKernelResponse(FilterResponseEvent $event)
{
/**
* @var Response $response
*/
$response = $event->getResponse();
// exit if not master request, uninteresting method or an error occurred
if (!$event->isMasterRequest() || $this->isNotConcerningRequest() || !$response->isSuccessful()) {
return;
}
// we can always safely call this, it doesn't need much resources.
// only if we have subscribers, it will create more load as it persists an EventStatus
$queueEvent = $this->createQueueEventObject();
if (!empty($queueEvent->getStatusurl()) && !empty($queueEvent->getEvent())) {
$linkHeader = LinkHeader::fromResponse($response);
$linkHeader->add(
new LinkHeaderItem(
$queueEvent->getStatusurl(),
array('rel' => 'eventStatus')
)
);
$response->headers->set(
'Link',
(string) $linkHeader
);
}
// let's send it to the queue(s) if appropriate
if (!empty($queueEvent->getEvent())) {
$queuesForEvent = $this->getSubscribedWorkerIds($queueEvent);
// if needed and activated, change urls relative to workers
if (!empty($queuesForEvent) && $this->workerRelativeUrl instanceof Uri) {
$queueEvent = $this->getWorkerQueueEvent($queueEvent);
}
foreach ($queuesForEvent as $queueForEvent) {
// declare the Queue for the Event if its not there already declared
$this->rabbitMqProducer->getChannel()->queue_declare($queueForEvent, false, true, false, false);
$this->rabbitMqProducer->publish(json_encode($queueEvent), $queueForEvent);
}
}
} | [
"public",
"function",
"onKernelResponse",
"(",
"FilterResponseEvent",
"$",
"event",
")",
"{",
"/**\n * @var Response $response\n */",
"$",
"response",
"=",
"$",
"event",
"->",
"getResponse",
"(",
")",
";",
"// exit if not master request, uninteresting method o... | add a rel=eventStatus Link header to the response if necessary
@param FilterResponseEvent $event response listener event
@return void | [
"add",
"a",
"rel",
"=",
"eventStatus",
"Link",
"header",
"to",
"the",
"response",
"if",
"necessary"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php#L160-L206 | train |
libgraviton/graviton | src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php | EventStatusLinkResponseListener.getStatusUrl | private function getStatusUrl($queueEvent)
{
// this has to be checked after cause we should not call getSubscribedWorkerIds() if above is true
$workerIds = $this->getSubscribedWorkerIds($queueEvent);
if (empty($workerIds)) {
return '';
}
// we have subscribers; create the EventStatus entry
/** @var EventStatus $eventStatus **/
$eventStatus = new $this->eventStatusClassname();
$eventStatus->setCreatedate(new \DateTime());
$eventStatus->setEventname($queueEvent->getEvent());
// if available, transport the ref document to the eventStatus instance
if (!empty($queueEvent->getDocumenturl())) {
$eventStatusResource = new $this->eventStatusEventResourceClassname();
$eventStatusResource->setRef($this->extRefConverter->getExtReference($queueEvent->getDocumenturl()));
$eventStatus->setEventresource($eventStatusResource);
}
foreach ($workerIds as $workerId) {
/** @var \GravitonDyn\EventStatusBundle\Document\EventStatusStatus $eventStatusStatus **/
$eventStatusStatus = new $this->eventStatusStatusClassname();
$eventStatusStatus->setWorkerid($workerId);
$eventStatusStatus->setStatus('opened');
$eventStatus->addStatus($eventStatusStatus);
}
// Set username to Event
$eventStatus->setUserid($this->getSecurityUsername());
$this->documentManager->persist($eventStatus);
$this->documentManager->flush();
// get the url..
$url = $this->router->generate(
$this->eventStatusRouteName,
[
'id' => $eventStatus->getId()
],
UrlGeneratorInterface::ABSOLUTE_URL
);
return $url;
} | php | private function getStatusUrl($queueEvent)
{
// this has to be checked after cause we should not call getSubscribedWorkerIds() if above is true
$workerIds = $this->getSubscribedWorkerIds($queueEvent);
if (empty($workerIds)) {
return '';
}
// we have subscribers; create the EventStatus entry
/** @var EventStatus $eventStatus **/
$eventStatus = new $this->eventStatusClassname();
$eventStatus->setCreatedate(new \DateTime());
$eventStatus->setEventname($queueEvent->getEvent());
// if available, transport the ref document to the eventStatus instance
if (!empty($queueEvent->getDocumenturl())) {
$eventStatusResource = new $this->eventStatusEventResourceClassname();
$eventStatusResource->setRef($this->extRefConverter->getExtReference($queueEvent->getDocumenturl()));
$eventStatus->setEventresource($eventStatusResource);
}
foreach ($workerIds as $workerId) {
/** @var \GravitonDyn\EventStatusBundle\Document\EventStatusStatus $eventStatusStatus **/
$eventStatusStatus = new $this->eventStatusStatusClassname();
$eventStatusStatus->setWorkerid($workerId);
$eventStatusStatus->setStatus('opened');
$eventStatus->addStatus($eventStatusStatus);
}
// Set username to Event
$eventStatus->setUserid($this->getSecurityUsername());
$this->documentManager->persist($eventStatus);
$this->documentManager->flush();
// get the url..
$url = $this->router->generate(
$this->eventStatusRouteName,
[
'id' => $eventStatus->getId()
],
UrlGeneratorInterface::ABSOLUTE_URL
);
return $url;
} | [
"private",
"function",
"getStatusUrl",
"(",
"$",
"queueEvent",
")",
"{",
"// this has to be checked after cause we should not call getSubscribedWorkerIds() if above is true",
"$",
"workerIds",
"=",
"$",
"this",
"->",
"getSubscribedWorkerIds",
"(",
"$",
"queueEvent",
")",
";",... | Creates a EventStatus object that gets persisted..
@param QueueEvent $queueEvent queueEvent object
@return string | [
"Creates",
"a",
"EventStatus",
"object",
"that",
"gets",
"persisted",
".."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php#L270-L315 | train |
libgraviton/graviton | src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php | EventStatusLinkResponseListener.getSubscribedWorkerIds | private function getSubscribedWorkerIds(QueueEvent $queueEvent)
{
// compose our regex to match stars ;-)
// results in = /((\*|document)+)\.((\*|dude)+)\.((\*|config)+)\.((\*|update)+)/
$routingArgs = explode('.', $queueEvent->getEvent());
$regex =
'/'.
implode(
'\.',
array_map(
function ($arg) {
return '((\*|'.$arg.')+)';
},
$routingArgs
)
).
'/';
// look up workers by class name
$qb = $this->documentManager->createQueryBuilder($this->eventWorkerClassname);
$data = $qb
->select('id')
->field('subscription.event')
->equals(new \MongoRegex($regex))
->getQuery()
->execute()
->toArray();
return array_keys($data);
} | php | private function getSubscribedWorkerIds(QueueEvent $queueEvent)
{
// compose our regex to match stars ;-)
// results in = /((\*|document)+)\.((\*|dude)+)\.((\*|config)+)\.((\*|update)+)/
$routingArgs = explode('.', $queueEvent->getEvent());
$regex =
'/'.
implode(
'\.',
array_map(
function ($arg) {
return '((\*|'.$arg.')+)';
},
$routingArgs
)
).
'/';
// look up workers by class name
$qb = $this->documentManager->createQueryBuilder($this->eventWorkerClassname);
$data = $qb
->select('id')
->field('subscription.event')
->equals(new \MongoRegex($regex))
->getQuery()
->execute()
->toArray();
return array_keys($data);
} | [
"private",
"function",
"getSubscribedWorkerIds",
"(",
"QueueEvent",
"$",
"queueEvent",
")",
"{",
"// compose our regex to match stars ;-)",
"// results in = /((\\*|document)+)\\.((\\*|dude)+)\\.((\\*|config)+)\\.((\\*|update)+)/",
"$",
"routingArgs",
"=",
"explode",
"(",
"'.'",
","... | Checks EventWorker for worker that are subscribed to our event and returns
their workerIds as array
@param QueueEvent $queueEvent queueEvent object
@return array array of worker ids | [
"Checks",
"EventWorker",
"for",
"worker",
"that",
"are",
"subscribed",
"to",
"our",
"event",
"and",
"returns",
"their",
"workerIds",
"as",
"array"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php#L325-L354 | train |
libgraviton/graviton | src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php | EventStatusLinkResponseListener.getWorkerQueueEvent | private function getWorkerQueueEvent(QueueEvent $queueEvent)
{
$queueEvent->setDocumenturl($this->getWorkerRelativeUrl($queueEvent->getDocumenturl()));
$queueEvent->setStatusurl($this->getWorkerRelativeUrl($queueEvent->getStatusurl()));
return $queueEvent;
} | php | private function getWorkerQueueEvent(QueueEvent $queueEvent)
{
$queueEvent->setDocumenturl($this->getWorkerRelativeUrl($queueEvent->getDocumenturl()));
$queueEvent->setStatusurl($this->getWorkerRelativeUrl($queueEvent->getStatusurl()));
return $queueEvent;
} | [
"private",
"function",
"getWorkerQueueEvent",
"(",
"QueueEvent",
"$",
"queueEvent",
")",
"{",
"$",
"queueEvent",
"->",
"setDocumenturl",
"(",
"$",
"this",
"->",
"getWorkerRelativeUrl",
"(",
"$",
"queueEvent",
"->",
"getDocumenturl",
"(",
")",
")",
")",
";",
"$... | Changes the urls in the QueueEvent for the workers
@param QueueEvent $queueEvent queue event
@return QueueEvent altered queue event | [
"Changes",
"the",
"urls",
"in",
"the",
"QueueEvent",
"for",
"the",
"workers"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php#L377-L382 | train |
libgraviton/graviton | src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php | EventStatusLinkResponseListener.getWorkerRelativeUrl | private function getWorkerRelativeUrl($uri)
{
$uri = new Uri($uri);
$uri = $uri
->withHost($this->workerRelativeUrl->getHost())
->withScheme($this->workerRelativeUrl->getScheme())
->withPort($this->workerRelativeUrl->getPort());
return (string) $uri;
} | php | private function getWorkerRelativeUrl($uri)
{
$uri = new Uri($uri);
$uri = $uri
->withHost($this->workerRelativeUrl->getHost())
->withScheme($this->workerRelativeUrl->getScheme())
->withPort($this->workerRelativeUrl->getPort());
return (string) $uri;
} | [
"private",
"function",
"getWorkerRelativeUrl",
"(",
"$",
"uri",
")",
"{",
"$",
"uri",
"=",
"new",
"Uri",
"(",
"$",
"uri",
")",
";",
"$",
"uri",
"=",
"$",
"uri",
"->",
"withHost",
"(",
"$",
"this",
"->",
"workerRelativeUrl",
"->",
"getHost",
"(",
")",... | changes an uri for the workers
@param string $uri uri
@return string changed uri | [
"changes",
"an",
"uri",
"for",
"the",
"workers"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RabbitMqBundle/Listener/EventStatusLinkResponseListener.php#L391-L399 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Serializer/Handler/SchemaTypeHandler.php | SchemaTypeHandler.serializeSchemaTypeToJson | public function serializeSchemaTypeToJson(
JsonSerializationVisitor $visitor,
SchemaType $schemaType,
array $type,
Context $context
) {
$types = $schemaType->getTypes();
if (count($types) === 1) {
return array_pop($types);
}
return $types;
} | php | public function serializeSchemaTypeToJson(
JsonSerializationVisitor $visitor,
SchemaType $schemaType,
array $type,
Context $context
) {
$types = $schemaType->getTypes();
if (count($types) === 1) {
return array_pop($types);
}
return $types;
} | [
"public",
"function",
"serializeSchemaTypeToJson",
"(",
"JsonSerializationVisitor",
"$",
"visitor",
",",
"SchemaType",
"$",
"schemaType",
",",
"array",
"$",
"type",
",",
"Context",
"$",
"context",
")",
"{",
"$",
"types",
"=",
"$",
"schemaType",
"->",
"getTypes",... | Serialize SchemaType to JSON
@param JsonSerializationVisitor $visitor Visitor
@param SchemaType $schemaType type
@param array $type Type
@param Context $context Context
@return array | [
"Serialize",
"SchemaType",
"to",
"JSON"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Serializer/Handler/SchemaTypeHandler.php#L30-L43 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/Serializer/Handler/HashHandler.php | HashHandler.serializeHashToJson | public function serializeHashToJson(
JsonSerializationVisitor $visitor,
Hash $data,
array $type,
Context $context
) {
return new Hash($data);
} | php | public function serializeHashToJson(
JsonSerializationVisitor $visitor,
Hash $data,
array $type,
Context $context
) {
return new Hash($data);
} | [
"public",
"function",
"serializeHashToJson",
"(",
"JsonSerializationVisitor",
"$",
"visitor",
",",
"Hash",
"$",
"data",
",",
"array",
"$",
"type",
",",
"Context",
"$",
"context",
")",
"{",
"return",
"new",
"Hash",
"(",
"$",
"data",
")",
";",
"}"
] | Serialize Hash object
@param JsonSerializationVisitor $visitor Visitor
@param Hash $data Data
@param array $type Type
@param Context $context Context
@return Hash | [
"Serialize",
"Hash",
"object"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Serializer/Handler/HashHandler.php#L58-L65 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/Serializer/Handler/HashHandler.php | HashHandler.deserializeHashFromJson | public function deserializeHashFromJson(
JsonDeserializationVisitor $visitor,
array $data,
array $type,
Context $context
) {
$currentPath = $context->getCurrentPath();
$currentRequestContent = $this->getCurrentRequestContent();
$dataObj = null;
if (!is_null($currentRequestContent)) {
$dataObj = $currentRequestContent;
foreach ($currentPath as $pathElement) {
if (isset($dataObj->{$pathElement})) {
$dataObj = $dataObj->{$pathElement};
} else {
$dataObj = null;
break;
}
}
}
if (!is_null($dataObj)) {
if ($this->isSequentialArrayCase($dataObj, $data)) {
$dataObj = $dataObj[$this->getLocationCounter($currentPath)];
}
$data = $dataObj;
}
return new Hash($visitor->visitArray((array) $data, $type, $context));
} | php | public function deserializeHashFromJson(
JsonDeserializationVisitor $visitor,
array $data,
array $type,
Context $context
) {
$currentPath = $context->getCurrentPath();
$currentRequestContent = $this->getCurrentRequestContent();
$dataObj = null;
if (!is_null($currentRequestContent)) {
$dataObj = $currentRequestContent;
foreach ($currentPath as $pathElement) {
if (isset($dataObj->{$pathElement})) {
$dataObj = $dataObj->{$pathElement};
} else {
$dataObj = null;
break;
}
}
}
if (!is_null($dataObj)) {
if ($this->isSequentialArrayCase($dataObj, $data)) {
$dataObj = $dataObj[$this->getLocationCounter($currentPath)];
}
$data = $dataObj;
}
return new Hash($visitor->visitArray((array) $data, $type, $context));
} | [
"public",
"function",
"deserializeHashFromJson",
"(",
"JsonDeserializationVisitor",
"$",
"visitor",
",",
"array",
"$",
"data",
",",
"array",
"$",
"type",
",",
"Context",
"$",
"context",
")",
"{",
"$",
"currentPath",
"=",
"$",
"context",
"->",
"getCurrentPath",
... | Deserialize Hash object
@param JsonDeserializationVisitor $visitor Visitor
@param array $data Data
@param array $type Type
@param Context $context Context
@return Hash | [
"Deserialize",
"Hash",
"object"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Serializer/Handler/HashHandler.php#L76-L107 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/Serializer/Handler/HashHandler.php | HashHandler.getCurrentRequestContent | private function getCurrentRequestContent()
{
$currentRequest = $this->requestStack->getCurrentRequest();
if (!is_null($currentRequest)) {
$this->currentRequestContent = json_decode($currentRequest->getContent());
}
return $this->currentRequestContent;
} | php | private function getCurrentRequestContent()
{
$currentRequest = $this->requestStack->getCurrentRequest();
if (!is_null($currentRequest)) {
$this->currentRequestContent = json_decode($currentRequest->getContent());
}
return $this->currentRequestContent;
} | [
"private",
"function",
"getCurrentRequestContent",
"(",
")",
"{",
"$",
"currentRequest",
"=",
"$",
"this",
"->",
"requestStack",
"->",
"getCurrentRequest",
"(",
")",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"currentRequest",
")",
")",
"{",
"$",
"this",
"-... | returns the json_decoded content of the current request. if there is no request, it
will return null
@return mixed|null|object the json_decoded request content | [
"returns",
"the",
"json_decoded",
"content",
"of",
"the",
"current",
"request",
".",
"if",
"there",
"is",
"no",
"request",
"it",
"will",
"return",
"null"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Serializer/Handler/HashHandler.php#L115-L122 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/Serializer/Handler/HashHandler.php | HashHandler.getLocationCounter | private function getLocationCounter($location)
{
$locationHash = md5(implode(',', $location));
if (!isset($this->seenCounter[$locationHash])) {
$this->seenCounter[$locationHash] = 0;
} else {
$this->seenCounter[$locationHash]++;
}
return $this->seenCounter[$locationHash];
} | php | private function getLocationCounter($location)
{
$locationHash = md5(implode(',', $location));
if (!isset($this->seenCounter[$locationHash])) {
$this->seenCounter[$locationHash] = 0;
} else {
$this->seenCounter[$locationHash]++;
}
return $this->seenCounter[$locationHash];
} | [
"private",
"function",
"getLocationCounter",
"(",
"$",
"location",
")",
"{",
"$",
"locationHash",
"=",
"md5",
"(",
"implode",
"(",
"','",
",",
"$",
"location",
")",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"seenCounter",
"[",
"$",
"... | convenience function for the location counting for the "sequential array case" as described above.
@param array $location the current path from the serializer
@return int the counter | [
"convenience",
"function",
"for",
"the",
"location",
"counting",
"for",
"the",
"sequential",
"array",
"case",
"as",
"described",
"above",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Serializer/Handler/HashHandler.php#L154-L163 | train |
libgraviton/graviton | src/Graviton/SecurityBundle/Authentication/Strategies/AbstractHttpStrategy.php | AbstractHttpStrategy.extractFieldInfo | protected function extractFieldInfo($header, $fieldName)
{
if ($header instanceof ParameterBag || $header instanceof HeaderBag) {
$this->validateField($header, $fieldName);
return $header->get($fieldName, '');
}
throw new \InvalidArgumentException('Provided request information are not valid.');
} | php | protected function extractFieldInfo($header, $fieldName)
{
if ($header instanceof ParameterBag || $header instanceof HeaderBag) {
$this->validateField($header, $fieldName);
return $header->get($fieldName, '');
}
throw new \InvalidArgumentException('Provided request information are not valid.');
} | [
"protected",
"function",
"extractFieldInfo",
"(",
"$",
"header",
",",
"$",
"fieldName",
")",
"{",
"if",
"(",
"$",
"header",
"instanceof",
"ParameterBag",
"||",
"$",
"header",
"instanceof",
"HeaderBag",
")",
"{",
"$",
"this",
"->",
"validateField",
"(",
"$",
... | Extracts information from the a request header field.
@param ParameterBag|HeaderBag $header object representation of the request header.
@param string $fieldName Name of the field to be read.
@return string | [
"Extracts",
"information",
"from",
"the",
"a",
"request",
"header",
"field",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SecurityBundle/Authentication/Strategies/AbstractHttpStrategy.php#L36-L44 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Generator/AbstractGenerator.php | AbstractGenerator.renderFile | protected function renderFile($template, $target, $parameters)
{
$this->fs->dumpFile(
$target,
$this->render($template, $parameters)
);
} | php | protected function renderFile($template, $target, $parameters)
{
$this->fs->dumpFile(
$target,
$this->render($template, $parameters)
);
} | [
"protected",
"function",
"renderFile",
"(",
"$",
"template",
",",
"$",
"target",
",",
"$",
"parameters",
")",
"{",
"$",
"this",
"->",
"fs",
"->",
"dumpFile",
"(",
"$",
"target",
",",
"$",
"this",
"->",
"render",
"(",
"$",
"template",
",",
"$",
"param... | renders a file form a twig template
@param string $template template filename
@param string $target where to generate to
@param array $parameters template params
@return void | [
"renders",
"a",
"file",
"form",
"a",
"twig",
"template"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Generator/AbstractGenerator.php#L89-L95 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Constraint/RecordOriginConstraint.php | RecordOriginConstraint.convertDatetimeToUTC | private function convertDatetimeToUTC($object, $schema, \DateTimeZone $timezone)
{
foreach ($schema->properties as $field => $property) {
if (isset($property->format) && $property->format == 'date-time' && isset($object->{$field})) {
$dateTime = Rfc3339::createFromString($object->{$field});
$dateTime->setTimezone($timezone);
$object->{$field} = $dateTime->format(\DateTime::ISO8601);
} elseif (isset($property->properties) && isset($object->{$field})) {
$object->{$field} = $this->convertDatetimeToUTC($object->{$field}, $property, $timezone);
}
}
return $object;
} | php | private function convertDatetimeToUTC($object, $schema, \DateTimeZone $timezone)
{
foreach ($schema->properties as $field => $property) {
if (isset($property->format) && $property->format == 'date-time' && isset($object->{$field})) {
$dateTime = Rfc3339::createFromString($object->{$field});
$dateTime->setTimezone($timezone);
$object->{$field} = $dateTime->format(\DateTime::ISO8601);
} elseif (isset($property->properties) && isset($object->{$field})) {
$object->{$field} = $this->convertDatetimeToUTC($object->{$field}, $property, $timezone);
}
}
return $object;
} | [
"private",
"function",
"convertDatetimeToUTC",
"(",
"$",
"object",
",",
"$",
"schema",
",",
"\\",
"DateTimeZone",
"$",
"timezone",
")",
"{",
"foreach",
"(",
"$",
"schema",
"->",
"properties",
"as",
"$",
"field",
"=>",
"$",
"property",
")",
"{",
"if",
"("... | Recursive convert date time to UTC
@param object $object Form data to be verified
@param object $schema Entity schema
@param \DateTimeZone $timezone to be converted to
@return object | [
"Recursive",
"convert",
"date",
"time",
"to",
"UTC"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/RecordOriginConstraint.php#L185-L197 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Constraint/RecordOriginConstraint.php | RecordOriginConstraint.addProperties | private function addProperties($expression, $obj)
{
$val = &$obj;
$parts = explode('.', $expression);
$numParts = count($parts);
if ($numParts == 1) {
$val->{$parts[0]} = null;
} else {
$iteration = 1;
foreach ($parts as $part) {
if ($iteration < $numParts) {
if (!isset($val->{$part}) || !is_object($val->{$part})) {
$val->{$part} = new \stdClass();
}
$val = &$val->{$part};
} else {
$val->{$part} = null;
}
$iteration++;
}
}
return $val;
} | php | private function addProperties($expression, $obj)
{
$val = &$obj;
$parts = explode('.', $expression);
$numParts = count($parts);
if ($numParts == 1) {
$val->{$parts[0]} = null;
} else {
$iteration = 1;
foreach ($parts as $part) {
if ($iteration < $numParts) {
if (!isset($val->{$part}) || !is_object($val->{$part})) {
$val->{$part} = new \stdClass();
}
$val = &$val->{$part};
} else {
$val->{$part} = null;
}
$iteration++;
}
}
return $val;
} | [
"private",
"function",
"addProperties",
"(",
"$",
"expression",
",",
"$",
"obj",
")",
"{",
"$",
"val",
"=",
"&",
"$",
"obj",
";",
"$",
"parts",
"=",
"explode",
"(",
"'.'",
",",
"$",
"expression",
")",
";",
"$",
"numParts",
"=",
"count",
"(",
"$",
... | if the user provides properties that are in the exception list but not on the currently saved
object, we try here to synthetically add them to our representation. and yes, this won't support
exclusions in an array structure for the moment, but that is also not needed for now.
@param string $expression the expression
@param object $obj the object
@return object the modified object | [
"if",
"the",
"user",
"provides",
"properties",
"that",
"are",
"in",
"the",
"exception",
"list",
"but",
"not",
"on",
"the",
"currently",
"saved",
"object",
"we",
"try",
"here",
"to",
"synthetically",
"add",
"them",
"to",
"our",
"representation",
".",
"and",
... | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/RecordOriginConstraint.php#L233-L257 | train |
libgraviton/graviton | src/Graviton/SwaggerBundle/Service/Swagger.php | Swagger.getBasicPathStructure | protected function getBasicPathStructure($isCollectionRequest, $entityName, $entityClassName, $idType)
{
$thisPath = array(
'consumes' => array('application/json'),
'produces' => array('application/json')
);
// collection return or not?
if (!$isCollectionRequest) {
// add object response
$thisPath['responses'] = array(
200 => array(
'description' => $entityName . ' response',
'schema' => array('$ref' => '#/definitions/' . $entityClassName)
),
404 => array(
'description' => 'Resource not found'
)
);
// add id param
$thisPath['parameters'][] = array(
'name' => 'id',
'in' => 'path',
'description' => 'ID of ' . $entityName . ' item to fetch/update',
'required' => true,
'type' => $idType
);
} else {
// add array response
$thisPath['responses'][200] = array(
'description' => $entityName . ' response',
'schema' => array(
'type' => 'array',
'items' => array('$ref' => '#/definitions/' . $entityClassName)
)
);
}
return $thisPath;
} | php | protected function getBasicPathStructure($isCollectionRequest, $entityName, $entityClassName, $idType)
{
$thisPath = array(
'consumes' => array('application/json'),
'produces' => array('application/json')
);
// collection return or not?
if (!$isCollectionRequest) {
// add object response
$thisPath['responses'] = array(
200 => array(
'description' => $entityName . ' response',
'schema' => array('$ref' => '#/definitions/' . $entityClassName)
),
404 => array(
'description' => 'Resource not found'
)
);
// add id param
$thisPath['parameters'][] = array(
'name' => 'id',
'in' => 'path',
'description' => 'ID of ' . $entityName . ' item to fetch/update',
'required' => true,
'type' => $idType
);
} else {
// add array response
$thisPath['responses'][200] = array(
'description' => $entityName . ' response',
'schema' => array(
'type' => 'array',
'items' => array('$ref' => '#/definitions/' . $entityClassName)
)
);
}
return $thisPath;
} | [
"protected",
"function",
"getBasicPathStructure",
"(",
"$",
"isCollectionRequest",
",",
"$",
"entityName",
",",
"$",
"entityClassName",
",",
"$",
"idType",
")",
"{",
"$",
"thisPath",
"=",
"array",
"(",
"'consumes'",
"=>",
"array",
"(",
"'application/json'",
")",... | Return the basic structure of a path element
@param bool $isCollectionRequest if collection request
@param string $entityName entity name
@param string $entityClassName class name
@param string $idType type of id field
@return array Path spec | [
"Return",
"the",
"basic",
"structure",
"of",
"a",
"path",
"element"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SwaggerBundle/Service/Swagger.php#L213-L253 | train |
libgraviton/graviton | src/Graviton/SwaggerBundle/Service/Swagger.php | Swagger.getSummary | protected function getSummary($method, $isCollectionRequest, $entityName)
{
$ret = '';
// meaningful descriptions..
switch ($method) {
case 'get':
if ($isCollectionRequest) {
$ret = 'Get collection of ' . $entityName . ' resources';
} else {
$ret = 'Get single ' . $entityName . ' resources';
}
break;
case 'post':
$ret = 'Create new ' . $entityName . ' resource';
break;
case 'put':
$ret = 'Update existing ' . $entityName . ' resource';
break;
case 'delete':
$ret = 'Delete existing ' . $entityName . ' resource';
}
return $ret;
} | php | protected function getSummary($method, $isCollectionRequest, $entityName)
{
$ret = '';
// meaningful descriptions..
switch ($method) {
case 'get':
if ($isCollectionRequest) {
$ret = 'Get collection of ' . $entityName . ' resources';
} else {
$ret = 'Get single ' . $entityName . ' resources';
}
break;
case 'post':
$ret = 'Create new ' . $entityName . ' resource';
break;
case 'put':
$ret = 'Update existing ' . $entityName . ' resource';
break;
case 'delete':
$ret = 'Delete existing ' . $entityName . ' resource';
}
return $ret;
} | [
"protected",
"function",
"getSummary",
"(",
"$",
"method",
",",
"$",
"isCollectionRequest",
",",
"$",
"entityName",
")",
"{",
"$",
"ret",
"=",
"''",
";",
"// meaningful descriptions..",
"switch",
"(",
"$",
"method",
")",
"{",
"case",
"'get'",
":",
"if",
"(... | Returns a meaningful summary depending on certain conditions
@param string $method Method
@param bool $isCollectionRequest If collection request
@param string $entityName Name of entity
@return string summary | [
"Returns",
"a",
"meaningful",
"summary",
"depending",
"on",
"certain",
"conditions"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SwaggerBundle/Service/Swagger.php#L282-L304 | train |
libgraviton/graviton | src/Graviton/FileBundle/Controller/FileController.php | FileController.postAction | public function postAction(Request $request)
{
$file = new File();
$request = $this->requestManager->updateFileRequest($request);
if ($formData = $request->get('metadata')) {
$file = $this->restUtils->validateRequest($formData, $this->getModel());
}
/** @var FileModel $model */
$model = $this->getModel();
$file = $this->fileManager->handleSaveRequest($file, $request, $model);
// Set status code and content
$response = $this->getResponse();
$response->setStatusCode(Response::HTTP_CREATED);
$response->headers->set(
'Location',
$this->getRouter()->generate('gravitondyn.file.rest.file.get', array('id' => $file->getId()))
);
return $response;
} | php | public function postAction(Request $request)
{
$file = new File();
$request = $this->requestManager->updateFileRequest($request);
if ($formData = $request->get('metadata')) {
$file = $this->restUtils->validateRequest($formData, $this->getModel());
}
/** @var FileModel $model */
$model = $this->getModel();
$file = $this->fileManager->handleSaveRequest($file, $request, $model);
// Set status code and content
$response = $this->getResponse();
$response->setStatusCode(Response::HTTP_CREATED);
$response->headers->set(
'Location',
$this->getRouter()->generate('gravitondyn.file.rest.file.get', array('id' => $file->getId()))
);
return $response;
} | [
"public",
"function",
"postAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"file",
"=",
"new",
"File",
"(",
")",
";",
"$",
"request",
"=",
"$",
"this",
"->",
"requestManager",
"->",
"updateFileRequest",
"(",
"$",
"request",
")",
";",
"if",
"(",... | Writes a new Entry to the database
Can accept either direct Post data or Form upload
@param Request $request Current http request
@return Response $response Result of action with data (if successful) | [
"Writes",
"a",
"new",
"Entry",
"to",
"the",
"database",
"Can",
"accept",
"either",
"direct",
"Post",
"data",
"or",
"Form",
"upload"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/FileBundle/Controller/FileController.php#L66-L87 | train |
libgraviton/graviton | src/Graviton/FileBundle/Controller/FileController.php | FileController.getAction | public function getAction(Request $request, $id)
{
// If a json request, let parent handle it
if (in_array('application/json', $request->getAcceptableContentTypes())) {
return parent::getAction($request, $id);
}
/** @var File $file */
$file = $this->getModel()->find($id);
/** @var Response $response */
return $this->fileManager->buildGetContentResponse(
$this->getResponse(),
$file
);
} | php | public function getAction(Request $request, $id)
{
// If a json request, let parent handle it
if (in_array('application/json', $request->getAcceptableContentTypes())) {
return parent::getAction($request, $id);
}
/** @var File $file */
$file = $this->getModel()->find($id);
/** @var Response $response */
return $this->fileManager->buildGetContentResponse(
$this->getResponse(),
$file
);
} | [
"public",
"function",
"getAction",
"(",
"Request",
"$",
"request",
",",
"$",
"id",
")",
"{",
"// If a json request, let parent handle it",
"if",
"(",
"in_array",
"(",
"'application/json'",
",",
"$",
"request",
"->",
"getAcceptableContentTypes",
"(",
")",
")",
")",... | respond with document if non json mime-type is requested
@param Request $request Current http request
@param string $id id of file
@return Response | [
"respond",
"with",
"document",
"if",
"non",
"json",
"mime",
"-",
"type",
"is",
"requested"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/FileBundle/Controller/FileController.php#L97-L112 | train |
libgraviton/graviton | src/Graviton/FileBundle/Controller/FileController.php | FileController.patchAction | public function patchAction($id, Request $request)
{
// Update modified date
$content = json_decode($request->getContent(), true);
if ($content) {
// Checking so update time is correct
$now = new \DateTime();
$patch = [
'op' => 'replace',
'path' => '/metadata/modificationDate',
'value' => $now->format(DATE_ISO8601)
];
// It can be a simple patch or a multi array patching.
if (array_key_exists(0, $content)) {
$content[] = $patch;
} else {
$content = [$content, $patch];
}
$request = new Request(
$request->query->all(),
$request->request->all(),
$request->attributes->all(),
$request->cookies->all(),
$request->files->all(),
$request->server->all(),
json_encode($content)
);
}
return parent::patchAction($id, $request);
} | php | public function patchAction($id, Request $request)
{
// Update modified date
$content = json_decode($request->getContent(), true);
if ($content) {
// Checking so update time is correct
$now = new \DateTime();
$patch = [
'op' => 'replace',
'path' => '/metadata/modificationDate',
'value' => $now->format(DATE_ISO8601)
];
// It can be a simple patch or a multi array patching.
if (array_key_exists(0, $content)) {
$content[] = $patch;
} else {
$content = [$content, $patch];
}
$request = new Request(
$request->query->all(),
$request->request->all(),
$request->attributes->all(),
$request->cookies->all(),
$request->files->all(),
$request->server->all(),
json_encode($content)
);
}
return parent::patchAction($id, $request);
} | [
"public",
"function",
"patchAction",
"(",
"$",
"id",
",",
"Request",
"$",
"request",
")",
"{",
"// Update modified date",
"$",
"content",
"=",
"json_decode",
"(",
"$",
"request",
"->",
"getContent",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"$",
"conte... | Patch a record, we add here a patch on Modification Data.
@param Number $id ID of record
@param Request $request Current http request
@throws MalformedInputException
@return Response $response Result of action with data (if successful) | [
"Patch",
"a",
"record",
"we",
"add",
"here",
"a",
"patch",
"on",
"Modification",
"Data",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/FileBundle/Controller/FileController.php#L170-L201 | train |
libgraviton/graviton | src/Graviton/CoreBundle/Controller/MainController.php | MainController.indexAction | public function indexAction()
{
$response = $this->response;
$mainPage = new \stdClass();
$mainPage->services = $this->determineServices(
$this->restUtils->getOptionRoutes()
);
$mainPage->thirdparty = $this->registerThirdPartyServices();
$response->setContent(json_encode($mainPage));
$response->setStatusCode(Response::HTTP_OK);
$response->headers->set('Link', $this->prepareLinkHeader());
// todo: make sure, that the correct content type is set.
// todo: this should be covered by a kernel.response event listener?
$response->headers->set('Content-Type', 'application/json');
return $response;
} | php | public function indexAction()
{
$response = $this->response;
$mainPage = new \stdClass();
$mainPage->services = $this->determineServices(
$this->restUtils->getOptionRoutes()
);
$mainPage->thirdparty = $this->registerThirdPartyServices();
$response->setContent(json_encode($mainPage));
$response->setStatusCode(Response::HTTP_OK);
$response->headers->set('Link', $this->prepareLinkHeader());
// todo: make sure, that the correct content type is set.
// todo: this should be covered by a kernel.response event listener?
$response->headers->set('Content-Type', 'application/json');
return $response;
} | [
"public",
"function",
"indexAction",
"(",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"response",
";",
"$",
"mainPage",
"=",
"new",
"\\",
"stdClass",
"(",
")",
";",
"$",
"mainPage",
"->",
"services",
"=",
"$",
"this",
"->",
"determineServices",
... | create simple start page.
@return Response $response Response with result or error | [
"create",
"simple",
"start",
"page",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Controller/MainController.php#L103-L123 | train |
libgraviton/graviton | src/Graviton/CoreBundle/Controller/MainController.php | MainController.determineServices | protected function determineServices(array $optionRoutes)
{
$router = $this->router;
foreach ($this->addditionalRoutes as $route) {
$optionRoutes[$route] = null;
}
$services = array_map(
function ($routeName) use ($router) {
$routeParts = explode('.', $routeName);
if (count($routeParts) > 3) {
list($app, $bundle, $rest, $document) = $routeParts;
$schemaRoute = implode('.', [$app, $bundle, $rest, $document, 'canonicalSchema']);
return [
'$ref' => $router->generate($routeName, [], UrlGeneratorInterface::ABSOLUTE_URL),
'profile' => $router->generate($schemaRoute, [], UrlGeneratorInterface::ABSOLUTE_URL),
];
}
},
array_keys($optionRoutes)
);
$sortArr = [];
foreach ($services as $key => $val) {
if ($this->isRelevantForMainPage($val) && !in_array($val['$ref'], $sortArr)) {
$sortArr[$key] = $val['$ref'];
} else {
unset($services[$key]);
}
}
// get additional routes
$additionalRoutes = $this->getAdditionalRoutes($sortArr);
$services = array_merge($services, $additionalRoutes);
array_multisort($sortArr, SORT_ASC, $services);
return $services;
} | php | protected function determineServices(array $optionRoutes)
{
$router = $this->router;
foreach ($this->addditionalRoutes as $route) {
$optionRoutes[$route] = null;
}
$services = array_map(
function ($routeName) use ($router) {
$routeParts = explode('.', $routeName);
if (count($routeParts) > 3) {
list($app, $bundle, $rest, $document) = $routeParts;
$schemaRoute = implode('.', [$app, $bundle, $rest, $document, 'canonicalSchema']);
return [
'$ref' => $router->generate($routeName, [], UrlGeneratorInterface::ABSOLUTE_URL),
'profile' => $router->generate($schemaRoute, [], UrlGeneratorInterface::ABSOLUTE_URL),
];
}
},
array_keys($optionRoutes)
);
$sortArr = [];
foreach ($services as $key => $val) {
if ($this->isRelevantForMainPage($val) && !in_array($val['$ref'], $sortArr)) {
$sortArr[$key] = $val['$ref'];
} else {
unset($services[$key]);
}
}
// get additional routes
$additionalRoutes = $this->getAdditionalRoutes($sortArr);
$services = array_merge($services, $additionalRoutes);
array_multisort($sortArr, SORT_ASC, $services);
return $services;
} | [
"protected",
"function",
"determineServices",
"(",
"array",
"$",
"optionRoutes",
")",
"{",
"$",
"router",
"=",
"$",
"this",
"->",
"router",
";",
"foreach",
"(",
"$",
"this",
"->",
"addditionalRoutes",
"as",
"$",
"route",
")",
"{",
"$",
"optionRoutes",
"[",... | Determines what service endpoints are available.
@param array $optionRoutes List of routing options.
@return array | [
"Determines",
"what",
"service",
"endpoints",
"are",
"available",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Controller/MainController.php#L132-L172 | train |
libgraviton/graviton | src/Graviton/CoreBundle/Controller/MainController.php | MainController.prepareLinkHeader | protected function prepareLinkHeader()
{
$links = new LinkHeader(array());
$links->add(
new LinkHeaderItem(
$this->router->generate('graviton.core.rest.app.all', array (), UrlGeneratorInterface::ABSOLUTE_URL),
array ('rel' => 'apps', 'type' => 'application/json')
)
);
return (string) $links;
} | php | protected function prepareLinkHeader()
{
$links = new LinkHeader(array());
$links->add(
new LinkHeaderItem(
$this->router->generate('graviton.core.rest.app.all', array (), UrlGeneratorInterface::ABSOLUTE_URL),
array ('rel' => 'apps', 'type' => 'application/json')
)
);
return (string) $links;
} | [
"protected",
"function",
"prepareLinkHeader",
"(",
")",
"{",
"$",
"links",
"=",
"new",
"LinkHeader",
"(",
"array",
"(",
")",
")",
";",
"$",
"links",
"->",
"add",
"(",
"new",
"LinkHeaderItem",
"(",
"$",
"this",
"->",
"router",
"->",
"generate",
"(",
"'g... | Prepares the header field containing information about pagination.
@return string | [
"Prepares",
"the",
"header",
"field",
"containing",
"information",
"about",
"pagination",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Controller/MainController.php#L208-L219 | train |
libgraviton/graviton | src/Graviton/CoreBundle/Controller/MainController.php | MainController.isRelevantForMainPage | private function isRelevantForMainPage($val)
{
return (substr($val['$ref'], -1) === '/')
|| in_array(parse_url($val['$ref'], PHP_URL_PATH), $this->pathWhitelist);
} | php | private function isRelevantForMainPage($val)
{
return (substr($val['$ref'], -1) === '/')
|| in_array(parse_url($val['$ref'], PHP_URL_PATH), $this->pathWhitelist);
} | [
"private",
"function",
"isRelevantForMainPage",
"(",
"$",
"val",
")",
"{",
"return",
"(",
"substr",
"(",
"$",
"val",
"[",
"'$ref'",
"]",
",",
"-",
"1",
")",
"===",
"'/'",
")",
"||",
"in_array",
"(",
"parse_url",
"(",
"$",
"val",
"[",
"'$ref'",
"]",
... | tells if a service is relevant for the mainpage
@param array $val value of service spec
@return boolean | [
"tells",
"if",
"a",
"service",
"is",
"relevant",
"for",
"the",
"mainpage"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Controller/MainController.php#L228-L232 | train |
libgraviton/graviton | src/Graviton/CoreBundle/Controller/MainController.php | MainController.determineThirdPartyServices | protected function determineThirdPartyServices(array $thirdApiRoutes)
{
$definition = $this->apiLoader;
$mainRoute = $this->router->generate(
'graviton.core.static.main.all',
[],
UrlGeneratorInterface::ABSOLUTE_URL
);
$services = array_map(
function ($apiRoute) use ($mainRoute, $definition) {
return array (
'$ref' => $mainRoute.$apiRoute,
'profile' => $mainRoute."schema/".$apiRoute."/item",
);
},
$thirdApiRoutes
);
return $services;
} | php | protected function determineThirdPartyServices(array $thirdApiRoutes)
{
$definition = $this->apiLoader;
$mainRoute = $this->router->generate(
'graviton.core.static.main.all',
[],
UrlGeneratorInterface::ABSOLUTE_URL
);
$services = array_map(
function ($apiRoute) use ($mainRoute, $definition) {
return array (
'$ref' => $mainRoute.$apiRoute,
'profile' => $mainRoute."schema/".$apiRoute."/item",
);
},
$thirdApiRoutes
);
return $services;
} | [
"protected",
"function",
"determineThirdPartyServices",
"(",
"array",
"$",
"thirdApiRoutes",
")",
"{",
"$",
"definition",
"=",
"$",
"this",
"->",
"apiLoader",
";",
"$",
"mainRoute",
"=",
"$",
"this",
"->",
"router",
"->",
"generate",
"(",
"'graviton.core.static.... | Resolves all third party routes and add schema info
@param array $thirdApiRoutes list of all routes from an API
@return array | [
"Resolves",
"all",
"third",
"party",
"routes",
"and",
"add",
"schema",
"info"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Controller/MainController.php#L241-L261 | train |
libgraviton/graviton | src/Graviton/CoreBundle/Controller/MainController.php | MainController.registerThirdPartyServices | private function registerThirdPartyServices()
{
$services = [];
// getenv()... it's a workaround for run all tests on travis! will be removed!
if (getenv('USER') !== 'travis' && getenv('HAS_JOSH_K_SEAL_OF_APPROVAL') !== true) {
foreach (array_keys($this->proxySourceConfiguration) as $source) {
foreach ($this->proxySourceConfiguration[$source] as $thirdparty => $option) {
$this->apiLoader->resetDefinitionLoader();
$this->apiLoader->setOption($option);
$this->apiLoader->addOptions($this->decideApiAndEndpoint($option));
$services[$thirdparty] = $this->determineThirdPartyServices(
$this->apiLoader->getAllEndpoints(false, true)
);
}
}
}
return $services;
} | php | private function registerThirdPartyServices()
{
$services = [];
// getenv()... it's a workaround for run all tests on travis! will be removed!
if (getenv('USER') !== 'travis' && getenv('HAS_JOSH_K_SEAL_OF_APPROVAL') !== true) {
foreach (array_keys($this->proxySourceConfiguration) as $source) {
foreach ($this->proxySourceConfiguration[$source] as $thirdparty => $option) {
$this->apiLoader->resetDefinitionLoader();
$this->apiLoader->setOption($option);
$this->apiLoader->addOptions($this->decideApiAndEndpoint($option));
$services[$thirdparty] = $this->determineThirdPartyServices(
$this->apiLoader->getAllEndpoints(false, true)
);
}
}
}
return $services;
} | [
"private",
"function",
"registerThirdPartyServices",
"(",
")",
"{",
"$",
"services",
"=",
"[",
"]",
";",
"// getenv()... it's a workaround for run all tests on travis! will be removed!",
"if",
"(",
"getenv",
"(",
"'USER'",
")",
"!==",
"'travis'",
"&&",
"getenv",
"(",
... | Finds configured external apis to be exposed via G2.
@return array | [
"Finds",
"configured",
"external",
"apis",
"to",
"be",
"exposed",
"via",
"G2",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Controller/MainController.php#L268-L287 | train |
libgraviton/graviton | src/Graviton/RestBundle/Event/ModelEvent.php | ModelEvent.setActionByDispatchName | public function setActionByDispatchName($dispatchName)
{
if (array_key_exists($dispatchName, $this->availableEvents)) {
$this->action = $this->availableEvents[$dispatchName];
} else {
throw new \RuntimeException('Document Model event dispatch type not found: ' . $dispatchName);
}
} | php | public function setActionByDispatchName($dispatchName)
{
if (array_key_exists($dispatchName, $this->availableEvents)) {
$this->action = $this->availableEvents[$dispatchName];
} else {
throw new \RuntimeException('Document Model event dispatch type not found: ' . $dispatchName);
}
} | [
"public",
"function",
"setActionByDispatchName",
"(",
"$",
"dispatchName",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"dispatchName",
",",
"$",
"this",
"->",
"availableEvents",
")",
")",
"{",
"$",
"this",
"->",
"action",
"=",
"$",
"this",
"->",
"av... | Set the event ACTION name based on the fired name
@param string $dispatchName the CONST value for dispatch names
@return string
@throws Exception | [
"Set",
"the",
"event",
"ACTION",
"name",
"based",
"on",
"the",
"fired",
"name"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Event/ModelEvent.php#L82-L89 | train |
libgraviton/graviton | src/Graviton/RestBundle/HttpFoundation/LinkHeader.php | LinkHeader.fromString | public static function fromString($headerValue)
{
return new self(
array_map(
function ($itemValue) use (&$index) {
$item = LinkHeaderItem::fromString(trim($itemValue));
return $item;
},
preg_split('/(".+?"|[^,]+)(?:,|$)/', $headerValue, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)
)
);
} | php | public static function fromString($headerValue)
{
return new self(
array_map(
function ($itemValue) use (&$index) {
$item = LinkHeaderItem::fromString(trim($itemValue));
return $item;
},
preg_split('/(".+?"|[^,]+)(?:,|$)/', $headerValue, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)
)
);
} | [
"public",
"static",
"function",
"fromString",
"(",
"$",
"headerValue",
")",
"{",
"return",
"new",
"self",
"(",
"array_map",
"(",
"function",
"(",
"$",
"itemValue",
")",
"use",
"(",
"&",
"$",
"index",
")",
"{",
"$",
"item",
"=",
"LinkHeaderItem",
"::",
... | Builds a LinkHeader instance from a string.
@param string $headerValue value of complete header
@return LinkHeader | [
"Builds",
"a",
"LinkHeader",
"instance",
"from",
"a",
"string",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/HttpFoundation/LinkHeader.php#L41-L53 | train |
libgraviton/graviton | src/Graviton/RestBundle/HttpFoundation/LinkHeader.php | LinkHeader.fromResponse | public static function fromResponse(Response $response)
{
$header = $response->headers->get('Link');
if (is_array($header)) {
implode(',', $header);
}
return self::fromString($header);
} | php | public static function fromResponse(Response $response)
{
$header = $response->headers->get('Link');
if (is_array($header)) {
implode(',', $header);
}
return self::fromString($header);
} | [
"public",
"static",
"function",
"fromResponse",
"(",
"Response",
"$",
"response",
")",
"{",
"$",
"header",
"=",
"$",
"response",
"->",
"headers",
"->",
"get",
"(",
"'Link'",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"header",
")",
")",
"{",
"implode",... | get LinkHeader instance from response
@param \Symfony\Component\HttpFoundation\Response $response response to get header from
@return LinkHeader | [
"get",
"LinkHeader",
"instance",
"from",
"response"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/HttpFoundation/LinkHeader.php#L62-L70 | train |
duncan3dc/domparser | src/Xml/Writer.php | Writer.toString | public function toString($format = null)
{
if ($format) {
$this->dom->formatOutput = true;
}
return $this->dom->saveXML();
} | php | public function toString($format = null)
{
if ($format) {
$this->dom->formatOutput = true;
}
return $this->dom->saveXML();
} | [
"public",
"function",
"toString",
"(",
"$",
"format",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"format",
")",
"{",
"$",
"this",
"->",
"dom",
"->",
"formatOutput",
"=",
"true",
";",
"}",
"return",
"$",
"this",
"->",
"dom",
"->",
"saveXML",
"(",
")",
... | Convert the internal dom instance to a string.
@param boolean $format Whether to pretty format the string or not
@return string | [
"Convert",
"the",
"internal",
"dom",
"instance",
"to",
"a",
"string",
"."
] | d5523b58337cab3b9ad90e8d135f87793795f93f | https://github.com/duncan3dc/domparser/blob/d5523b58337cab3b9ad90e8d135f87793795f93f/src/Xml/Writer.php#L53-L59 | train |
duncan3dc/domparser | src/Xml/Writer.php | Writer.addElement | public function addElement($name, $params, $parent)
{
$name = preg_replace("/_[0-9]+$/", "", $name);
$element = $this->dom->createElement($name);
if (!is_array($params)) {
$this->setElementValue($element, $params);
} else {
foreach ($params as $key => $val) {
if ($key == "_attributes") {
foreach ($val as $k => $v) {
$element->setAttribute($k, $v);
}
} elseif ($key == "_value") {
$this->setElementValue($element, $val);
} else {
$this->addElement($key, $val, $element);
}
}
}
$parent->appendChild($element);
return $element;
} | php | public function addElement($name, $params, $parent)
{
$name = preg_replace("/_[0-9]+$/", "", $name);
$element = $this->dom->createElement($name);
if (!is_array($params)) {
$this->setElementValue($element, $params);
} else {
foreach ($params as $key => $val) {
if ($key == "_attributes") {
foreach ($val as $k => $v) {
$element->setAttribute($k, $v);
}
} elseif ($key == "_value") {
$this->setElementValue($element, $val);
} else {
$this->addElement($key, $val, $element);
}
}
}
$parent->appendChild($element);
return $element;
} | [
"public",
"function",
"addElement",
"(",
"$",
"name",
",",
"$",
"params",
",",
"$",
"parent",
")",
"{",
"$",
"name",
"=",
"preg_replace",
"(",
"\"/_[0-9]+$/\"",
",",
"\"\"",
",",
"$",
"name",
")",
";",
"$",
"element",
"=",
"$",
"this",
"->",
"dom",
... | Append an element recursively to a dom instance.
@param string $name The name of the element to append
@param mixed $params The value to set the new element to, or the elements to append to it
@param mixed $parent The dom instance to append the element to
@return \DOMElement | [
"Append",
"an",
"element",
"recursively",
"to",
"a",
"dom",
"instance",
"."
] | d5523b58337cab3b9ad90e8d135f87793795f93f | https://github.com/duncan3dc/domparser/blob/d5523b58337cab3b9ad90e8d135f87793795f93f/src/Xml/Writer.php#L71-L96 | train |
duncan3dc/domparser | src/Xml/Writer.php | Writer.setElementValue | public function setElementValue($element, $value)
{
$node = $this->dom->createTextNode($value);
$element->appendChild($node);
} | php | public function setElementValue($element, $value)
{
$node = $this->dom->createTextNode($value);
$element->appendChild($node);
} | [
"public",
"function",
"setElementValue",
"(",
"$",
"element",
",",
"$",
"value",
")",
"{",
"$",
"node",
"=",
"$",
"this",
"->",
"dom",
"->",
"createTextNode",
"(",
"$",
"value",
")",
";",
"$",
"element",
"->",
"appendChild",
"(",
"$",
"node",
")",
";... | Append an element on to the xml document with a simple value.
@param mixed $element The dom instance to append the element to
@param mixed $value The value to set the new element to
@return void | [
"Append",
"an",
"element",
"on",
"to",
"the",
"xml",
"document",
"with",
"a",
"simple",
"value",
"."
] | d5523b58337cab3b9ad90e8d135f87793795f93f | https://github.com/duncan3dc/domparser/blob/d5523b58337cab3b9ad90e8d135f87793795f93f/src/Xml/Writer.php#L107-L111 | train |
duncan3dc/domparser | src/Xml/Writer.php | Writer.createXml | public static function createXml($structure, $encoding = null)
{
$writer = new static($structure, $encoding);
return trim($writer->toString());
} | php | public static function createXml($structure, $encoding = null)
{
$writer = new static($structure, $encoding);
return trim($writer->toString());
} | [
"public",
"static",
"function",
"createXml",
"(",
"$",
"structure",
",",
"$",
"encoding",
"=",
"null",
")",
"{",
"$",
"writer",
"=",
"new",
"static",
"(",
"$",
"structure",
",",
"$",
"encoding",
")",
";",
"return",
"trim",
"(",
"$",
"writer",
"->",
"... | Convert the passed array structure to an xml string.
@param array $structure The array representation of the xml structure
@param string $encoding The encoding to declare in the <?xml tag
@return string | [
"Convert",
"the",
"passed",
"array",
"structure",
"to",
"an",
"xml",
"string",
"."
] | d5523b58337cab3b9ad90e8d135f87793795f93f | https://github.com/duncan3dc/domparser/blob/d5523b58337cab3b9ad90e8d135f87793795f93f/src/Xml/Writer.php#L122-L126 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/Listener/ExtReferenceSearchListener.php | ExtReferenceSearchListener.processScalarNode | private function processScalarNode(AbstractScalarOperatorNode $node)
{
$copy = clone $node;
$copy->setValue($this->getDbRefValue($node->getValue()));
return $copy;
} | php | private function processScalarNode(AbstractScalarOperatorNode $node)
{
$copy = clone $node;
$copy->setValue($this->getDbRefValue($node->getValue()));
return $copy;
} | [
"private",
"function",
"processScalarNode",
"(",
"AbstractScalarOperatorNode",
"$",
"node",
")",
"{",
"$",
"copy",
"=",
"clone",
"$",
"node",
";",
"$",
"copy",
"->",
"setValue",
"(",
"$",
"this",
"->",
"getDbRefValue",
"(",
"$",
"node",
"->",
"getValue",
"... | Process scalar condition
@param AbstractScalarOperatorNode $node Query node
@return AbstractScalarOperatorNode | [
"Process",
"scalar",
"condition"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Listener/ExtReferenceSearchListener.php#L83-L88 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/Listener/ExtReferenceSearchListener.php | ExtReferenceSearchListener.processArrayNode | private function processArrayNode(AbstractArrayOperatorNode $node)
{
$copy = clone $node;
$copy->setValues(array_map([$this, 'getDbRefValue'], $node->getValues()));
return $copy;
} | php | private function processArrayNode(AbstractArrayOperatorNode $node)
{
$copy = clone $node;
$copy->setValues(array_map([$this, 'getDbRefValue'], $node->getValues()));
return $copy;
} | [
"private",
"function",
"processArrayNode",
"(",
"AbstractArrayOperatorNode",
"$",
"node",
")",
"{",
"$",
"copy",
"=",
"clone",
"$",
"node",
";",
"$",
"copy",
"->",
"setValues",
"(",
"array_map",
"(",
"[",
"$",
"this",
",",
"'getDbRefValue'",
"]",
",",
"$",... | Process array condition
@param AbstractArrayOperatorNode $node Query node
@return AbstractArrayOperatorNode | [
"Process",
"array",
"condition"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Listener/ExtReferenceSearchListener.php#L96-L101 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/Listener/ExtReferenceSearchListener.php | ExtReferenceSearchListener.getDbRefValue | private function getDbRefValue($url)
{
if ($url === null) {
return null;
}
try {
$extref = $this->converter->getExtReference($url);
return \MongoDBRef::create($extref->getRef(), $extref->getId());
} catch (\InvalidArgumentException $e) {
//make up some invalid refs to ensure we find nothing if an invalid url was given
return \MongoDBRef::create(false, false);
}
} | php | private function getDbRefValue($url)
{
if ($url === null) {
return null;
}
try {
$extref = $this->converter->getExtReference($url);
return \MongoDBRef::create($extref->getRef(), $extref->getId());
} catch (\InvalidArgumentException $e) {
//make up some invalid refs to ensure we find nothing if an invalid url was given
return \MongoDBRef::create(false, false);
}
} | [
"private",
"function",
"getDbRefValue",
"(",
"$",
"url",
")",
"{",
"if",
"(",
"$",
"url",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"try",
"{",
"$",
"extref",
"=",
"$",
"this",
"->",
"converter",
"->",
"getExtReference",
"(",
"$",
"url",
... | Get DbRef from extref URL
@param string $url Extref URL representation
@return object | [
"Get",
"DbRef",
"from",
"extref",
"URL"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Listener/ExtReferenceSearchListener.php#L109-L122 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Document/Schema.php | Schema.removeProperty | public function removeProperty($name)
{
if ($this->properties->containsKey($name)) {
$this->properties->remove($name);
}
} | php | public function removeProperty($name)
{
if ($this->properties->containsKey($name)) {
$this->properties->remove($name);
}
} | [
"public",
"function",
"removeProperty",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"properties",
"->",
"containsKey",
"(",
"$",
"name",
")",
")",
"{",
"$",
"this",
"->",
"properties",
"->",
"remove",
"(",
"$",
"name",
")",
";",
"}",
... | removes a property
@param string $name property name
@return void | [
"removes",
"a",
"property"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Document/Schema.php#L664-L669 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Document/Schema.php | Schema.getProperty | public function getProperty($name = null)
{
if (is_null($name)) {
return null;
}
return $this->properties->get($name);
} | php | public function getProperty($name = null)
{
if (is_null($name)) {
return null;
}
return $this->properties->get($name);
} | [
"public",
"function",
"getProperty",
"(",
"$",
"name",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"name",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"this",
"->",
"properties",
"->",
"get",
"(",
"$",
"name",
")",
";",
"... | returns a property
@param string $name property name
@return null|Schema property | [
"returns",
"a",
"property"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Document/Schema.php#L678-L684 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/DependencyInjection/Compiler/RecordOriginExceptionFieldsCompilerPass.php | RecordOriginExceptionFieldsCompilerPass.process | public function process(ContainerBuilder $container)
{
$this->documentMap = $container->get('graviton.document.map');
$map = [];
foreach ($this->documentMap->getDocuments() as $document) {
$recordOriginExceptionFields = $this->documentMap->getFieldNamesFlat(
$document,
'',
'',
function ($field) {
return $field->isRecordOriginException();
}
);
if (!empty($recordOriginExceptionFields)) {
foreach ($recordOriginExceptionFields as $key => $recordOriginExceptionField) {
if (substr($recordOriginExceptionField, -2) == '.0') {
unset($recordOriginExceptionFields[$key]);
}
}
$map[$document->getClass()] = array_values($recordOriginExceptionFields);
}
}
$container->setParameter('graviton.document.recordoriginexception.fields', $map);
} | php | public function process(ContainerBuilder $container)
{
$this->documentMap = $container->get('graviton.document.map');
$map = [];
foreach ($this->documentMap->getDocuments() as $document) {
$recordOriginExceptionFields = $this->documentMap->getFieldNamesFlat(
$document,
'',
'',
function ($field) {
return $field->isRecordOriginException();
}
);
if (!empty($recordOriginExceptionFields)) {
foreach ($recordOriginExceptionFields as $key => $recordOriginExceptionField) {
if (substr($recordOriginExceptionField, -2) == '.0') {
unset($recordOriginExceptionFields[$key]);
}
}
$map[$document->getClass()] = array_values($recordOriginExceptionFields);
}
}
$container->setParameter('graviton.document.recordoriginexception.fields', $map);
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"this",
"->",
"documentMap",
"=",
"$",
"container",
"->",
"get",
"(",
"'graviton.document.map'",
")",
";",
"$",
"map",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"th... | Make recordOriginException fields map and set it to parameter
@param ContainerBuilder $container container builder
@return void | [
"Make",
"recordOriginException",
"fields",
"map",
"and",
"set",
"it",
"to",
"parameter"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/RecordOriginExceptionFieldsCompilerPass.php#L31-L58 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php | SwaggerStrategy.supports | public function supports($input)
{
/**
* @var array $swagger
*/
$swagger = $this->decodeJson($input, true);
if (empty($swagger)) {
return false;
}
$mandatoryFields = ['swagger', 'info', 'paths', 'version', 'title', 'definitions'];
$fields = array_merge(array_keys($swagger), array_keys($swagger['info']));
$intersect = array_intersect($mandatoryFields, $fields);
// every mandatory field was found in provided json definition.
return empty(array_diff($mandatoryFields, $intersect));
} | php | public function supports($input)
{
/**
* @var array $swagger
*/
$swagger = $this->decodeJson($input, true);
if (empty($swagger)) {
return false;
}
$mandatoryFields = ['swagger', 'info', 'paths', 'version', 'title', 'definitions'];
$fields = array_merge(array_keys($swagger), array_keys($swagger['info']));
$intersect = array_intersect($mandatoryFields, $fields);
// every mandatory field was found in provided json definition.
return empty(array_diff($mandatoryFields, $intersect));
} | [
"public",
"function",
"supports",
"(",
"$",
"input",
")",
"{",
"/**\n * @var array $swagger\n */",
"$",
"swagger",
"=",
"$",
"this",
"->",
"decodeJson",
"(",
"$",
"input",
",",
"true",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"swagger",
")",
... | is input data valid json
@param string $input json string
@return boolean | [
"is",
"input",
"data",
"valid",
"json"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php#L92-L109 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php | SwaggerStrategy.decodeJson | private function decodeJson($input, $assoc = false)
{
$input = trim($input);
return json_decode($input, $assoc);
} | php | private function decodeJson($input, $assoc = false)
{
$input = trim($input);
return json_decode($input, $assoc);
} | [
"private",
"function",
"decodeJson",
"(",
"$",
"input",
",",
"$",
"assoc",
"=",
"false",
")",
"{",
"$",
"input",
"=",
"trim",
"(",
"$",
"input",
")",
";",
"return",
"json_decode",
"(",
"$",
"input",
",",
"$",
"assoc",
")",
";",
"}"
] | decode a json string
@param string $input json string
@param bool $assoc Force the encoded result to be a hash.
@return array|\stdClass | [
"decode",
"a",
"json",
"string"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php#L119-L124 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php | SwaggerStrategy.setBaseValues | private function setBaseValues(ApiDefinition $apiDef)
{
$this->registerHost($apiDef);
$basePath = $this->document->getBasePath();
if (isset($basePath)) {
$apiDef->setBasePath($basePath);
}
} | php | private function setBaseValues(ApiDefinition $apiDef)
{
$this->registerHost($apiDef);
$basePath = $this->document->getBasePath();
if (isset($basePath)) {
$apiDef->setBasePath($basePath);
}
} | [
"private",
"function",
"setBaseValues",
"(",
"ApiDefinition",
"$",
"apiDef",
")",
"{",
"$",
"this",
"->",
"registerHost",
"(",
"$",
"apiDef",
")",
";",
"$",
"basePath",
"=",
"$",
"this",
"->",
"document",
"->",
"getBasePath",
"(",
")",
";",
"if",
"(",
... | set base values
@param ApiDefinition $apiDef API definition
@return void | [
"set",
"base",
"values"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php#L133-L140 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php | SwaggerStrategy.getServiceSchema | private function getServiceSchema($service)
{
$operation = $service->getOperation();
$schema = new \stdClass();
switch (strtolower($service->getMethod())) {
case "post":
case "put":
try {
$parameters = $operation->getDocumentObjectProperty('parameters', Parameter\Body::class, true);
} catch (MissingDocumentPropertyException $e) {
// request has no params
break;
}
foreach ($parameters as $parameter) {
/**
* there is no schema information available, if $action->parameters[0]->in != 'body'
*
* @link http://swagger.io/specification/#parameterObject
*/
if ($parameter instanceof Parameter\Body && $parameter->getIn() === 'body') {
$ref = $parameter->getDocumentObjectProperty('schema', Reference::class)->getDocument();
$schema = $this->resolveSchema($ref);
break;
}
}
break;
case "get":
try {
$response = $operation->getResponses()->getHttpStatusCode(200);
} catch (MissingDocumentPropertyException $e) {
// no response with status code 200 is defined
break;
}
$schema = $this->resolveSchema($response->getSchema()->getDocument());
break;
}
return $schema;
} | php | private function getServiceSchema($service)
{
$operation = $service->getOperation();
$schema = new \stdClass();
switch (strtolower($service->getMethod())) {
case "post":
case "put":
try {
$parameters = $operation->getDocumentObjectProperty('parameters', Parameter\Body::class, true);
} catch (MissingDocumentPropertyException $e) {
// request has no params
break;
}
foreach ($parameters as $parameter) {
/**
* there is no schema information available, if $action->parameters[0]->in != 'body'
*
* @link http://swagger.io/specification/#parameterObject
*/
if ($parameter instanceof Parameter\Body && $parameter->getIn() === 'body') {
$ref = $parameter->getDocumentObjectProperty('schema', Reference::class)->getDocument();
$schema = $this->resolveSchema($ref);
break;
}
}
break;
case "get":
try {
$response = $operation->getResponses()->getHttpStatusCode(200);
} catch (MissingDocumentPropertyException $e) {
// no response with status code 200 is defined
break;
}
$schema = $this->resolveSchema($response->getSchema()->getDocument());
break;
}
return $schema;
} | [
"private",
"function",
"getServiceSchema",
"(",
"$",
"service",
")",
"{",
"$",
"operation",
"=",
"$",
"service",
"->",
"getOperation",
"(",
")",
";",
"$",
"schema",
"=",
"new",
"\\",
"stdClass",
"(",
")",
";",
"switch",
"(",
"strtolower",
"(",
"$",
"se... | get the schema
@param OperationReference $service service endpoint
@return \stdClass | [
"get",
"the",
"schema"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php#L149-L187 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php | SwaggerStrategy.registerHost | private function registerHost(ApiDefinition $apiDef)
{
try {
$host = $this->document->getHost();
} catch (MissingDocumentPropertyException $e) {
$host = $this->fallbackData['host'];
}
$apiDef->setHost($host);
} | php | private function registerHost(ApiDefinition $apiDef)
{
try {
$host = $this->document->getHost();
} catch (MissingDocumentPropertyException $e) {
$host = $this->fallbackData['host'];
}
$apiDef->setHost($host);
} | [
"private",
"function",
"registerHost",
"(",
"ApiDefinition",
"$",
"apiDef",
")",
"{",
"try",
"{",
"$",
"host",
"=",
"$",
"this",
"->",
"document",
"->",
"getHost",
"(",
")",
";",
"}",
"catch",
"(",
"MissingDocumentPropertyException",
"$",
"e",
")",
"{",
... | Sets the destination host for the api definition.
@param ApiDefinition $apiDef Configuration for the swagger api to be recognized.
@return void | [
"Sets",
"the",
"destination",
"host",
"for",
"the",
"api",
"definition",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Definition/Loader/DispersalStrategy/SwaggerStrategy.php#L233-L241 | train |
libgraviton/graviton | src/Graviton/AnalyticsBundle/Compiler/AnalyticsCompilerPass.php | AnalyticsCompilerPass.process | public function process(ContainerBuilder $container)
{
$services = [];
$finder = Finder::create()
->files()
->in(Graviton::getBundleScanDir())
->path('/\/analytics\//i')
->name('*.json')
->notName('_*')
->notName('*.pipeline.*')
->sortByName();
foreach ($finder as $file) {
$key = $file->getFilename();
$data = json_decode($file->getContents(), true);
if (json_last_error()) {
throw new InvalidConfigurationException(
sprintf('Analytics file: %s could not be loaded due to error: %s', $key, json_last_error_msg())
);
}
if (isset($data['route']) && !empty($data['route'])) {
$services[$data['route']] = $data;
} else {
$services[] = $data;
}
}
$container->setParameter('analytics.services', $services);
} | php | public function process(ContainerBuilder $container)
{
$services = [];
$finder = Finder::create()
->files()
->in(Graviton::getBundleScanDir())
->path('/\/analytics\//i')
->name('*.json')
->notName('_*')
->notName('*.pipeline.*')
->sortByName();
foreach ($finder as $file) {
$key = $file->getFilename();
$data = json_decode($file->getContents(), true);
if (json_last_error()) {
throw new InvalidConfigurationException(
sprintf('Analytics file: %s could not be loaded due to error: %s', $key, json_last_error_msg())
);
}
if (isset($data['route']) && !empty($data['route'])) {
$services[$data['route']] = $data;
} else {
$services[] = $data;
}
}
$container->setParameter('analytics.services', $services);
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"services",
"=",
"[",
"]",
";",
"$",
"finder",
"=",
"Finder",
"::",
"create",
"(",
")",
"->",
"files",
"(",
")",
"->",
"in",
"(",
"Graviton",
"::",
"getBundleSca... | add our map of the available analytics services
@param ContainerBuilder $container container
@return void | [
"add",
"our",
"map",
"of",
"the",
"available",
"analytics",
"services"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/AnalyticsBundle/Compiler/AnalyticsCompilerPass.php#L27-L56 | train |
libgraviton/graviton | src/Graviton/I18nBundle/Listener/I18nRqlParsingListener.php | I18nRqlParsingListener.getAlteredQueryNode | private function getAlteredQueryNode($fieldName, array $values)
{
$newNode = new OrNode();
$defaultLanguageFieldName = $fieldName.'.'.$this->intUtils->getDefaultLanguage();
foreach ($values as $singleValue) {
$newNode->addQuery($this->getEqNode($fieldName, $singleValue));
// search default language field (as new structure only has 'en' set after creation and no save)
$newNode->addQuery(
$this->getEqNode(
$defaultLanguageFieldName,
$singleValue
)
);
}
// add default match
$newNode->addQuery($this->getEqNode($this->node->getField(), $this->getNodeValue()));
if (!$this->nodeFieldNameHasLanguage()) {
// if no language, we add it to the query to default node for default language
$newNode->addQuery(
$this->getEqNode(
$defaultLanguageFieldName,
$this->getNodeValue()
)
);
}
return $newNode;
} | php | private function getAlteredQueryNode($fieldName, array $values)
{
$newNode = new OrNode();
$defaultLanguageFieldName = $fieldName.'.'.$this->intUtils->getDefaultLanguage();
foreach ($values as $singleValue) {
$newNode->addQuery($this->getEqNode($fieldName, $singleValue));
// search default language field (as new structure only has 'en' set after creation and no save)
$newNode->addQuery(
$this->getEqNode(
$defaultLanguageFieldName,
$singleValue
)
);
}
// add default match
$newNode->addQuery($this->getEqNode($this->node->getField(), $this->getNodeValue()));
if (!$this->nodeFieldNameHasLanguage()) {
// if no language, we add it to the query to default node for default language
$newNode->addQuery(
$this->getEqNode(
$defaultLanguageFieldName,
$this->getNodeValue()
)
);
}
return $newNode;
} | [
"private",
"function",
"getAlteredQueryNode",
"(",
"$",
"fieldName",
",",
"array",
"$",
"values",
")",
"{",
"$",
"newNode",
"=",
"new",
"OrNode",
"(",
")",
";",
"$",
"defaultLanguageFieldName",
"=",
"$",
"fieldName",
".",
"'.'",
".",
"$",
"this",
"->",
"... | Gets a new query node
@param string $fieldName target fieldname
@param array $values the values to set
@return OrNode some node | [
"Gets",
"a",
"new",
"query",
"node"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Listener/I18nRqlParsingListener.php#L105-L135 | train |
libgraviton/graviton | src/Graviton/I18nBundle/Listener/I18nRqlParsingListener.php | I18nRqlParsingListener.getNodeValue | private function getNodeValue()
{
if ($this->node->getValue() instanceof \Xiag\Rql\Parser\DataType\Glob) {
return new \MongoRegex($this->node->getValue()->toRegex());
}
return $this->node->getValue();
} | php | private function getNodeValue()
{
if ($this->node->getValue() instanceof \Xiag\Rql\Parser\DataType\Glob) {
return new \MongoRegex($this->node->getValue()->toRegex());
}
return $this->node->getValue();
} | [
"private",
"function",
"getNodeValue",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"node",
"->",
"getValue",
"(",
")",
"instanceof",
"\\",
"Xiag",
"\\",
"Rql",
"\\",
"Parser",
"\\",
"DataType",
"\\",
"Glob",
")",
"{",
"return",
"new",
"\\",
"MongoRege... | gets the node value
@throws \MongoException
@return \MongoRegex|string value | [
"gets",
"the",
"node",
"value"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Listener/I18nRqlParsingListener.php#L144-L151 | train |
libgraviton/graviton | src/Graviton/I18nBundle/Listener/I18nRqlParsingListener.php | I18nRqlParsingListener.isTranslatableFieldNode | private function isTranslatableFieldNode()
{
$isTranslatableField = false;
if (isset($this->mapping[$this->className]) &&
in_array($this->getDocumentFieldName(), $this->mapping[$this->className])
) {
$isTranslatableField = true;
}
return $isTranslatableField;
} | php | private function isTranslatableFieldNode()
{
$isTranslatableField = false;
if (isset($this->mapping[$this->className]) &&
in_array($this->getDocumentFieldName(), $this->mapping[$this->className])
) {
$isTranslatableField = true;
}
return $isTranslatableField;
} | [
"private",
"function",
"isTranslatableFieldNode",
"(",
")",
"{",
"$",
"isTranslatableField",
"=",
"false",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"mapping",
"[",
"$",
"this",
"->",
"className",
"]",
")",
"&&",
"in_array",
"(",
"$",
"this",
"->"... | Returns true if the current node affects a translatable field
@return bool true if yes, false if not | [
"Returns",
"true",
"if",
"the",
"current",
"node",
"affects",
"a",
"translatable",
"field"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Listener/I18nRqlParsingListener.php#L158-L168 | train |
libgraviton/graviton | src/Graviton/I18nBundle/Listener/I18nRqlParsingListener.php | I18nRqlParsingListener.getEqNode | private function getEqNode($fieldName, $fieldValue)
{
$node = new EqNode($fieldName, $fieldValue);
$this->createdNodes[] = $node;
return $node;
} | php | private function getEqNode($fieldName, $fieldValue)
{
$node = new EqNode($fieldName, $fieldValue);
$this->createdNodes[] = $node;
return $node;
} | [
"private",
"function",
"getEqNode",
"(",
"$",
"fieldName",
",",
"$",
"fieldValue",
")",
"{",
"$",
"node",
"=",
"new",
"EqNode",
"(",
"$",
"fieldName",
",",
"$",
"fieldValue",
")",
";",
"$",
"this",
"->",
"createdNodes",
"[",
"]",
"=",
"$",
"node",
";... | get EqNode instance and remember that we created it..
@param string $fieldName field name
@param string $fieldValue field value
@return EqNode node | [
"get",
"EqNode",
"instance",
"and",
"remember",
"that",
"we",
"created",
"it",
".."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Listener/I18nRqlParsingListener.php#L178-L183 | train |
libgraviton/graviton | src/Graviton/I18nBundle/Listener/I18nRqlParsingListener.php | I18nRqlParsingListener.isOurNode | private function isOurNode($node)
{
foreach ($this->createdNodes as $createdNode) {
if ($createdNode == $node) {
return true;
}
}
return false;
} | php | private function isOurNode($node)
{
foreach ($this->createdNodes as $createdNode) {
if ($createdNode == $node) {
return true;
}
}
return false;
} | [
"private",
"function",
"isOurNode",
"(",
"$",
"node",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"createdNodes",
"as",
"$",
"createdNode",
")",
"{",
"if",
"(",
"$",
"createdNode",
"==",
"$",
"node",
")",
"{",
"return",
"true",
";",
"}",
"}",
"retur... | check if we created the node previously
@param EqNode $node node
@return bool true if yes, false otherwise | [
"check",
"if",
"we",
"created",
"the",
"node",
"previously"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Listener/I18nRqlParsingListener.php#L192-L200 | train |
libgraviton/graviton | src/Graviton/I18nBundle/Listener/I18nRqlParsingListener.php | I18nRqlParsingListener.nodeFieldNameHasLanguage | private function nodeFieldNameHasLanguage()
{
$parts = explode('.', $this->node->getField());
if (!empty($parts)) {
$lastPart = $parts[count($parts) - 1];
// only remove when language
if (in_array($lastPart, $this->intUtils->getLanguages())) {
return true;
}
}
return false;
} | php | private function nodeFieldNameHasLanguage()
{
$parts = explode('.', $this->node->getField());
if (!empty($parts)) {
$lastPart = $parts[count($parts) - 1];
// only remove when language
if (in_array($lastPart, $this->intUtils->getLanguages())) {
return true;
}
}
return false;
} | [
"private",
"function",
"nodeFieldNameHasLanguage",
"(",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"'.'",
",",
"$",
"this",
"->",
"node",
"->",
"getField",
"(",
")",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"parts",
")",
")",
"{",
"$",
"lastP... | if the node field name targets a language or not
@return bool true if yes, false otherwise | [
"if",
"the",
"node",
"field",
"name",
"targets",
"a",
"language",
"or",
"not"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Listener/I18nRqlParsingListener.php#L223-L234 | train |
libgraviton/graviton | src/Graviton/I18nBundle/Listener/I18nRqlParsingListener.php | I18nRqlParsingListener.getAllPossibleTranslatableStrings | private function getAllPossibleTranslatableStrings()
{
$matchingTranslations = [];
// is it a glob?
if ($this->node->getValue() instanceof \Xiag\Rql\Parser\DataType\Glob) {
$userValue = $this->node->getValue()->toRegex();
$useWildcard = true;
} else {
$userValue = $this->node->getValue();
$useWildcard = false;
}
$matchingTranslatables = $this->intUtils->findMatchingTranslatables(
$userValue,
$this->getClientSearchLanguage(),
$useWildcard
);
foreach ($matchingTranslatables as $translatable) {
$originalString = $translatable->getOriginal();
if (!empty($originalString)) {
$matchingTranslations[] = $originalString;
}
}
return array_unique($matchingTranslations);
} | php | private function getAllPossibleTranslatableStrings()
{
$matchingTranslations = [];
// is it a glob?
if ($this->node->getValue() instanceof \Xiag\Rql\Parser\DataType\Glob) {
$userValue = $this->node->getValue()->toRegex();
$useWildcard = true;
} else {
$userValue = $this->node->getValue();
$useWildcard = false;
}
$matchingTranslatables = $this->intUtils->findMatchingTranslatables(
$userValue,
$this->getClientSearchLanguage(),
$useWildcard
);
foreach ($matchingTranslatables as $translatable) {
$originalString = $translatable->getOriginal();
if (!empty($originalString)) {
$matchingTranslations[] = $originalString;
}
}
return array_unique($matchingTranslations);
} | [
"private",
"function",
"getAllPossibleTranslatableStrings",
"(",
")",
"{",
"$",
"matchingTranslations",
"=",
"[",
"]",
";",
"// is it a glob?",
"if",
"(",
"$",
"this",
"->",
"node",
"->",
"getValue",
"(",
")",
"instanceof",
"\\",
"Xiag",
"\\",
"Rql",
"\\",
"... | Looks up all matching Translatables and returns them uniquified
@return array matching english strings | [
"Looks",
"up",
"all",
"matching",
"Translatables",
"and",
"returns",
"them",
"uniquified"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Listener/I18nRqlParsingListener.php#L252-L279 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/DependencyInjection/Compiler/ReadOnlyFieldsCompilerPass.php | ReadOnlyFieldsCompilerPass.process | public function process(ContainerBuilder $container)
{
$this->documentMap = $container->get('graviton.document.map');
$map = [];
foreach ($this->documentMap->getDocuments() as $document) {
$readOnlyFields = $this->documentMap->getFieldNamesFlat(
$document,
'',
'',
function ($field) {
return $field->isReadOnly();
}
);
if (!empty($readOnlyFields)) {
foreach ($readOnlyFields as $key => $readOnlyField) {
if (substr($readOnlyField, -2) == '.0') {
unset($readOnlyFields[$key]);
}
}
$map[$document->getClass()] = array_values($readOnlyFields);
}
}
$container->setParameter('graviton.document.readonly.fields', $map);
} | php | public function process(ContainerBuilder $container)
{
$this->documentMap = $container->get('graviton.document.map');
$map = [];
foreach ($this->documentMap->getDocuments() as $document) {
$readOnlyFields = $this->documentMap->getFieldNamesFlat(
$document,
'',
'',
function ($field) {
return $field->isReadOnly();
}
);
if (!empty($readOnlyFields)) {
foreach ($readOnlyFields as $key => $readOnlyField) {
if (substr($readOnlyField, -2) == '.0') {
unset($readOnlyFields[$key]);
}
}
$map[$document->getClass()] = array_values($readOnlyFields);
}
}
$container->setParameter('graviton.document.readonly.fields', $map);
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"this",
"->",
"documentMap",
"=",
"$",
"container",
"->",
"get",
"(",
"'graviton.document.map'",
")",
";",
"$",
"map",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"th... | Make readOnly fields map and set it to parameter
@param ContainerBuilder $container container builder
@return void | [
"Make",
"readOnly",
"fields",
"map",
"and",
"set",
"it",
"to",
"parameter"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/ReadOnlyFieldsCompilerPass.php#L31-L58 | train |
duncan3dc/domparser | src/Html/Element.php | Element.hasClass | public function hasClass($className)
{
if (!$class = $this->dom->getAttribute("class")) {
return false;
}
$classes = explode(" ", $class);
return in_array($className, $classes, true);
} | php | public function hasClass($className)
{
if (!$class = $this->dom->getAttribute("class")) {
return false;
}
$classes = explode(" ", $class);
return in_array($className, $classes, true);
} | [
"public",
"function",
"hasClass",
"(",
"$",
"className",
")",
"{",
"if",
"(",
"!",
"$",
"class",
"=",
"$",
"this",
"->",
"dom",
"->",
"getAttribute",
"(",
"\"class\"",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"classes",
"=",
"explode",
"(",
... | Check if this element has the specified class applied to it.
@param string $className The name of the class to check for (case-sensitive)
@return bool | [
"Check",
"if",
"this",
"element",
"has",
"the",
"specified",
"class",
"applied",
"to",
"it",
"."
] | d5523b58337cab3b9ad90e8d135f87793795f93f | https://github.com/duncan3dc/domparser/blob/d5523b58337cab3b9ad90e8d135f87793795f93f/src/Html/Element.php#L21-L30 | train |
libgraviton/graviton | src/Graviton/ExceptionBundle/Listener/RestExceptionListener.php | RestExceptionListener.getSerializedContent | public function getSerializedContent($content)
{
$serializationContext = clone $this->serializationContext;
return $this->serializer->serialize(
$content,
'json',
$serializationContext
);
} | php | public function getSerializedContent($content)
{
$serializationContext = clone $this->serializationContext;
return $this->serializer->serialize(
$content,
'json',
$serializationContext
);
} | [
"public",
"function",
"getSerializedContent",
"(",
"$",
"content",
")",
"{",
"$",
"serializationContext",
"=",
"clone",
"$",
"this",
"->",
"serializationContext",
";",
"return",
"$",
"this",
"->",
"serializer",
"->",
"serialize",
"(",
"$",
"content",
",",
"'js... | Serialize the given content
@param mixed $content Content
@return string $content Json content | [
"Serialize",
"the",
"given",
"content"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ExceptionBundle/Listener/RestExceptionListener.php#L75-L84 | train |
libgraviton/graviton | src/Graviton/RestBundle/Restriction/Manager.php | Manager.handle | public function handle(DocumentRepository $repository)
{
$className = $repository->getClassName();
if (isset($this->restrictedFieldMap[$className]) && !empty($this->restrictedFieldMap[$className])) {
$nodes = [];
foreach ($this->restrictedFieldMap[$className] as $fieldPath => $handlers) {
$nodes = array_merge(
$nodes,
$this->getHandlerValue($repository, $fieldPath, $handlers)
);
}
return new AndNode($nodes);
}
return false;
} | php | public function handle(DocumentRepository $repository)
{
$className = $repository->getClassName();
if (isset($this->restrictedFieldMap[$className]) && !empty($this->restrictedFieldMap[$className])) {
$nodes = [];
foreach ($this->restrictedFieldMap[$className] as $fieldPath => $handlers) {
$nodes = array_merge(
$nodes,
$this->getHandlerValue($repository, $fieldPath, $handlers)
);
}
return new AndNode($nodes);
}
return false;
} | [
"public",
"function",
"handle",
"(",
"DocumentRepository",
"$",
"repository",
")",
"{",
"$",
"className",
"=",
"$",
"repository",
"->",
"getClassName",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"restrictedFieldMap",
"[",
"$",
"className",
... | handle the request for a given entity
@param DocumentRepository $repository repository
@return bool|AndNode either false if no restrictions or an AndNode for filtering | [
"handle",
"the",
"request",
"for",
"a",
"given",
"entity"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Restriction/Manager.php#L60-L74 | train |
libgraviton/graviton | src/Graviton/RestBundle/Restriction/Manager.php | Manager.getHandlerValue | private function getHandlerValue(DocumentRepository $repository, $fieldPath, array $handlers)
{
$nodes = [];
foreach ($handlers as $handler) {
if (!self::$handlers[$handler] instanceof HandlerInterface) {
throw new \LogicException(
'Specified handler "'.$handler.'" is not registered with RestrictionManager!'
);
}
$value = self::$handlers[$handler]->getValue($repository, $fieldPath);
if (!$value instanceof AbstractQueryNode) {
$value = new EqNode($fieldPath, $value);
}
$nodes[] = $value;
}
return $nodes;
} | php | private function getHandlerValue(DocumentRepository $repository, $fieldPath, array $handlers)
{
$nodes = [];
foreach ($handlers as $handler) {
if (!self::$handlers[$handler] instanceof HandlerInterface) {
throw new \LogicException(
'Specified handler "'.$handler.'" is not registered with RestrictionManager!'
);
}
$value = self::$handlers[$handler]->getValue($repository, $fieldPath);
if (!$value instanceof AbstractQueryNode) {
$value = new EqNode($fieldPath, $value);
}
$nodes[] = $value;
}
return $nodes;
} | [
"private",
"function",
"getHandlerValue",
"(",
"DocumentRepository",
"$",
"repository",
",",
"$",
"fieldPath",
",",
"array",
"$",
"handlers",
")",
"{",
"$",
"nodes",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"handlers",
"as",
"$",
"handler",
")",
"{",
"if... | gets the value to restrict data. the handler can also return a AbstractQueryNode. not only a string
@param DocumentRepository $repository the repository
@param string $fieldPath path to the field (can be complex; same syntax as in rql!)
@param array $handlers the specified handlers (array with handler names)
@return array the rql nodes | [
"gets",
"the",
"value",
"to",
"restrict",
"data",
".",
"the",
"handler",
"can",
"also",
"return",
"a",
"AbstractQueryNode",
".",
"not",
"only",
"a",
"string"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Restriction/Manager.php#L85-L104 | train |
libgraviton/graviton | src/Graviton/RestBundle/Listener/LinkHeaderResponseListener.php | LinkHeaderResponseListener.onKernelResponse | public function onKernelResponse(FilterResponseEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
$response = $event->getResponse();
$request = $event->getRequest();
// extract various info from route
$routeName = $request->get('_route');
$routeParts = explode('.', $routeName);
$routeType = end($routeParts);
$this->linkHeader = LinkHeader::fromResponse($response);
// add common headers
$this->addCommonHeaders($request, $response);
// add self Link header
$selfUrl = $this->addSelfLinkHeader($routeName, $routeType, $request);
// dispatch this!
// add paging Link element when applicable
if ($routeType == 'all' && $request->attributes->get('paging')) {
$this->generatePagingLinksHeaders($routeName, $request, $response);
}
// add schema link header element
$this->generateSchemaLinkHeader($routeName, $request, $response);
// finally set link header
$response->headers->set(
'Link',
(string) $this->linkHeader
);
$event->setResponse($response);
// dispatch the "selfaware" event
$event->getRequest()->attributes->set('selfLink', $selfUrl);
$dispatcher->dispatch('graviton.rest.response.selfaware', $event);
} | php | public function onKernelResponse(FilterResponseEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
$response = $event->getResponse();
$request = $event->getRequest();
// extract various info from route
$routeName = $request->get('_route');
$routeParts = explode('.', $routeName);
$routeType = end($routeParts);
$this->linkHeader = LinkHeader::fromResponse($response);
// add common headers
$this->addCommonHeaders($request, $response);
// add self Link header
$selfUrl = $this->addSelfLinkHeader($routeName, $routeType, $request);
// dispatch this!
// add paging Link element when applicable
if ($routeType == 'all' && $request->attributes->get('paging')) {
$this->generatePagingLinksHeaders($routeName, $request, $response);
}
// add schema link header element
$this->generateSchemaLinkHeader($routeName, $request, $response);
// finally set link header
$response->headers->set(
'Link',
(string) $this->linkHeader
);
$event->setResponse($response);
// dispatch the "selfaware" event
$event->getRequest()->attributes->set('selfLink', $selfUrl);
$dispatcher->dispatch('graviton.rest.response.selfaware', $event);
} | [
"public",
"function",
"onKernelResponse",
"(",
"FilterResponseEvent",
"$",
"event",
",",
"$",
"eventName",
",",
"EventDispatcherInterface",
"$",
"dispatcher",
")",
"{",
"$",
"response",
"=",
"$",
"event",
"->",
"getResponse",
"(",
")",
";",
"$",
"request",
"="... | add our Link header items
@param FilterResponseEvent $event response listener event
@param string $eventName event name
@param EventDispatcherInterface $dispatcher dispatcher
@return void | [
"add",
"our",
"Link",
"header",
"items"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Listener/LinkHeaderResponseListener.php#L56-L94 | train |
libgraviton/graviton | src/Graviton/RestBundle/Listener/LinkHeaderResponseListener.php | LinkHeaderResponseListener.addCommonHeaders | private function addCommonHeaders(Request $request, Response $response)
{
// replace content-type if a schema was requested
if ($request->attributes->get('schemaRequest')) {
$response->headers->set('Content-Type', 'application/schema+json');
}
if ($request->attributes->has('recordCount')) {
$response->headers->set(
'X-Record-Count',
(string) $request->attributes->get('recordCount')
);
}
// search source header?
if ($request->attributes->has('X-Search-Source')) {
$response->headers->set(
'X-Search-Source',
(string) $request->attributes->get('X-Search-Source')
);
}
} | php | private function addCommonHeaders(Request $request, Response $response)
{
// replace content-type if a schema was requested
if ($request->attributes->get('schemaRequest')) {
$response->headers->set('Content-Type', 'application/schema+json');
}
if ($request->attributes->has('recordCount')) {
$response->headers->set(
'X-Record-Count',
(string) $request->attributes->get('recordCount')
);
}
// search source header?
if ($request->attributes->has('X-Search-Source')) {
$response->headers->set(
'X-Search-Source',
(string) $request->attributes->get('X-Search-Source')
);
}
} | [
"private",
"function",
"addCommonHeaders",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
"{",
"// replace content-type if a schema was requested",
"if",
"(",
"$",
"request",
"->",
"attributes",
"->",
"get",
"(",
"'schemaRequest'",
")",
")",
... | add common headers
@param Request $request request
@param Response $response response
@return void | [
"add",
"common",
"headers"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Listener/LinkHeaderResponseListener.php#L104-L125 | train |
libgraviton/graviton | src/Graviton/RestBundle/Listener/LinkHeaderResponseListener.php | LinkHeaderResponseListener.addSelfLinkHeader | private function addSelfLinkHeader($routeName, $routeType, Request $request)
{
$routeParams = $request->get('_route_params');
if (!is_array($routeParams)) {
$routeParams = [];
}
if (($routeType == 'post' || $routeType == 'postNoSlash') || $routeType != 'all') {
// handle post request by rewriting self link to newly created resource
$routeParams['id'] = $request->get('id');
}
// rewrite post routes to get
if ($routeType == 'post' || $routeType == 'postNoSlash') {
$parts = explode('.', $routeName);
array_pop($parts);
$parts[] = 'get';
$routeName = implode('.', $parts);
}
$selfLinkUrl = $this->router->generate($routeName, $routeParams, UrlGeneratorInterface::ABSOLUTE_URL);
$queryString = $request->server->get('QUERY_STRING', '');
// if no rql was set, we set our default current limits
if ($request->attributes->get('paging') === true && strpos($queryString, 'limit(') === false) {
$limit = sprintf(
'limit(%s,%s)',
$request->attributes->get('perPage'),
$request->attributes->get('startAt')
);
if (!empty($queryString)) {
$queryString .= '&';
}
$queryString .= $limit;
}
if (!empty($queryString)) {
$selfLinkUrl .= '?' . strtr($queryString, [',' => '%2C']);
}
$this->linkHeader->add(
new LinkHeaderItem(
$selfLinkUrl,
['rel' => 'self']
)
);
return $selfLinkUrl;
} | php | private function addSelfLinkHeader($routeName, $routeType, Request $request)
{
$routeParams = $request->get('_route_params');
if (!is_array($routeParams)) {
$routeParams = [];
}
if (($routeType == 'post' || $routeType == 'postNoSlash') || $routeType != 'all') {
// handle post request by rewriting self link to newly created resource
$routeParams['id'] = $request->get('id');
}
// rewrite post routes to get
if ($routeType == 'post' || $routeType == 'postNoSlash') {
$parts = explode('.', $routeName);
array_pop($parts);
$parts[] = 'get';
$routeName = implode('.', $parts);
}
$selfLinkUrl = $this->router->generate($routeName, $routeParams, UrlGeneratorInterface::ABSOLUTE_URL);
$queryString = $request->server->get('QUERY_STRING', '');
// if no rql was set, we set our default current limits
if ($request->attributes->get('paging') === true && strpos($queryString, 'limit(') === false) {
$limit = sprintf(
'limit(%s,%s)',
$request->attributes->get('perPage'),
$request->attributes->get('startAt')
);
if (!empty($queryString)) {
$queryString .= '&';
}
$queryString .= $limit;
}
if (!empty($queryString)) {
$selfLinkUrl .= '?' . strtr($queryString, [',' => '%2C']);
}
$this->linkHeader->add(
new LinkHeaderItem(
$selfLinkUrl,
['rel' => 'self']
)
);
return $selfLinkUrl;
} | [
"private",
"function",
"addSelfLinkHeader",
"(",
"$",
"routeName",
",",
"$",
"routeType",
",",
"Request",
"$",
"request",
")",
"{",
"$",
"routeParams",
"=",
"$",
"request",
"->",
"get",
"(",
"'_route_params'",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"... | Add "self" Link header item
@param string $routeName route name
@param string $routeType route type
@param Request $request request
@return string the "self" link url | [
"Add",
"self",
"Link",
"header",
"item"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Listener/LinkHeaderResponseListener.php#L136-L186 | train |
libgraviton/graviton | src/Graviton/RestBundle/Listener/LinkHeaderResponseListener.php | LinkHeaderResponseListener.generateSchemaLinkHeader | private function generateSchemaLinkHeader($routeName, Request $request, Response $response)
{
if ($request->get('_route') != 'graviton.core.static.main.all') {
try {
$schemaRoute = SchemaUtils::getSchemaRouteName($routeName);
$this->linkHeader->add(
new LinkHeaderItem(
$this->router->generate($schemaRoute, [], UrlGeneratorInterface::ABSOLUTE_URL),
['rel' => 'schema']
)
);
} catch (\Exception $e) {
// nothing to do..
}
}
} | php | private function generateSchemaLinkHeader($routeName, Request $request, Response $response)
{
if ($request->get('_route') != 'graviton.core.static.main.all') {
try {
$schemaRoute = SchemaUtils::getSchemaRouteName($routeName);
$this->linkHeader->add(
new LinkHeaderItem(
$this->router->generate($schemaRoute, [], UrlGeneratorInterface::ABSOLUTE_URL),
['rel' => 'schema']
)
);
} catch (\Exception $e) {
// nothing to do..
}
}
} | [
"private",
"function",
"generateSchemaLinkHeader",
"(",
"$",
"routeName",
",",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
"{",
"if",
"(",
"$",
"request",
"->",
"get",
"(",
"'_route'",
")",
"!=",
"'graviton.core.static.main.all'",
")",
"{... | generates the schema rel in the Link header
@param string $routeName route name
@param Request $request request
@param Response $response response
@return void | [
"generates",
"the",
"schema",
"rel",
"in",
"the",
"Link",
"header"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Listener/LinkHeaderResponseListener.php#L198-L213 | train |
libgraviton/graviton | src/Graviton/RestBundle/Listener/LinkHeaderResponseListener.php | LinkHeaderResponseListener.generatePagingLinksHeaders | private function generatePagingLinksHeaders($routeName, Request $request, Response $response)
{
$rql = '';
if ($request->attributes->get('hasRql', false)) {
$rql = $request->attributes->get('rawRql', '');
}
$this->generateLinks(
$routeName,
$request->attributes->get('page'),
$request->attributes->get('numPages'),
$request->attributes->get('perPage'),
$request,
$rql
);
$response->headers->set(
'X-Total-Count',
(string) $request->attributes->get('totalCount')
);
} | php | private function generatePagingLinksHeaders($routeName, Request $request, Response $response)
{
$rql = '';
if ($request->attributes->get('hasRql', false)) {
$rql = $request->attributes->get('rawRql', '');
}
$this->generateLinks(
$routeName,
$request->attributes->get('page'),
$request->attributes->get('numPages'),
$request->attributes->get('perPage'),
$request,
$rql
);
$response->headers->set(
'X-Total-Count',
(string) $request->attributes->get('totalCount')
);
} | [
"private",
"function",
"generatePagingLinksHeaders",
"(",
"$",
"routeName",
",",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
")",
"{",
"$",
"rql",
"=",
"''",
";",
"if",
"(",
"$",
"request",
"->",
"attributes",
"->",
"get",
"(",
"'hasRql'",... | generates the paging Link header items
@param string $routeName route name
@param Request $request request
@param Response $response response
@return void | [
"generates",
"the",
"paging",
"Link",
"header",
"items"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Listener/LinkHeaderResponseListener.php#L224-L244 | train |
libgraviton/graviton | src/Graviton/RestBundle/Listener/LinkHeaderResponseListener.php | LinkHeaderResponseListener.generateLinks | private function generateLinks($route, $page, $numPages, $perPage, Request $request, $rql)
{
if ($page > 2) {
$this->generateLink($route, 1, $perPage, 'first', $request, $rql);
}
if ($page > 1) {
$this->generateLink($route, $page - 1, $perPage, 'prev', $request, $rql);
}
if ($page < $numPages) {
$this->generateLink($route, $page + 1, $perPage, 'next', $request, $rql);
}
if ($page != $numPages) {
$this->generateLink($route, $numPages, $perPage, 'last', $request, $rql);
}
} | php | private function generateLinks($route, $page, $numPages, $perPage, Request $request, $rql)
{
if ($page > 2) {
$this->generateLink($route, 1, $perPage, 'first', $request, $rql);
}
if ($page > 1) {
$this->generateLink($route, $page - 1, $perPage, 'prev', $request, $rql);
}
if ($page < $numPages) {
$this->generateLink($route, $page + 1, $perPage, 'next', $request, $rql);
}
if ($page != $numPages) {
$this->generateLink($route, $numPages, $perPage, 'last', $request, $rql);
}
} | [
"private",
"function",
"generateLinks",
"(",
"$",
"route",
",",
"$",
"page",
",",
"$",
"numPages",
",",
"$",
"perPage",
",",
"Request",
"$",
"request",
",",
"$",
"rql",
")",
"{",
"if",
"(",
"$",
"page",
">",
"2",
")",
"{",
"$",
"this",
"->",
"gen... | generate headers for all paging links
@param string $route name of route
@param integer $page page to link to
@param integer $numPages number of all pages
@param integer $perPage number of records per page
@param Request $request request to get rawRql from
@param string $rql rql query string
@return void | [
"generate",
"headers",
"for",
"all",
"paging",
"links"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Listener/LinkHeaderResponseListener.php#L258-L272 | train |
libgraviton/graviton | src/Graviton/RestBundle/Listener/LinkHeaderResponseListener.php | LinkHeaderResponseListener.generateLink | private function generateLink($routeName, $page, $perPage, $type, Request $request, $rql)
{
$limit = '';
if ($perPage) {
$page = ($page - 1) * $perPage;
$limit = sprintf('limit(%s,%s)', $perPage, $page);
}
if (strpos($rql, 'limit') !== false) {
$rql = preg_replace('/limit\(.*\)/U', $limit, $rql);
} elseif (empty($rql)) {
$rql .= $limit;
} else {
$rql .= '&'.$limit;
}
$url = $this->getRqlUrl(
$request,
$this->router->generate($routeName, [], UrlGeneratorInterface::ABSOLUTE_URL) .
'?' . strtr($rql, [',' => '%2C'])
);
$this->linkHeader->add(new LinkHeaderItem($url, array('rel' => $type)));
} | php | private function generateLink($routeName, $page, $perPage, $type, Request $request, $rql)
{
$limit = '';
if ($perPage) {
$page = ($page - 1) * $perPage;
$limit = sprintf('limit(%s,%s)', $perPage, $page);
}
if (strpos($rql, 'limit') !== false) {
$rql = preg_replace('/limit\(.*\)/U', $limit, $rql);
} elseif (empty($rql)) {
$rql .= $limit;
} else {
$rql .= '&'.$limit;
}
$url = $this->getRqlUrl(
$request,
$this->router->generate($routeName, [], UrlGeneratorInterface::ABSOLUTE_URL) .
'?' . strtr($rql, [',' => '%2C'])
);
$this->linkHeader->add(new LinkHeaderItem($url, array('rel' => $type)));
} | [
"private",
"function",
"generateLink",
"(",
"$",
"routeName",
",",
"$",
"page",
",",
"$",
"perPage",
",",
"$",
"type",
",",
"Request",
"$",
"request",
",",
"$",
"rql",
")",
"{",
"$",
"limit",
"=",
"''",
";",
"if",
"(",
"$",
"perPage",
")",
"{",
"... | generate link header passed on params and type
@param string $routeName use with router to generate urls
@param integer $page page to link to
@param integer $perPage number of items per page
@param string $type rel type of link to generate
@param Request $request request to get rawRql from
@param string $rql rql query string
@return string | [
"generate",
"link",
"header",
"passed",
"on",
"params",
"and",
"type"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Listener/LinkHeaderResponseListener.php#L286-L308 | train |
libgraviton/graviton | src/Graviton/AnalyticsBundle/Model/AnalyticModel.php | AnalyticModel.getAggregate | public function getAggregate($params = [])
{
if ($this->getMultipipeline()) {
$pipelines = [];
foreach ($this->class as $name => $className) {
if (!class_exists($className)) {
throw new \LogicException("Analytics class '" . $className . "' does not exist!");
}
$class = new $className();
$class->setParams($params);
$pipelines[$name] = $class->get();
}
return $pipelines;
} else {
$className = $this->class;
if (!class_exists($className)) {
throw new \LogicException("Analytics class '" . $className . "' does not exist!");
}
$class = new $className();
$class->setParams($params);
return $class->get();
}
} | php | public function getAggregate($params = [])
{
if ($this->getMultipipeline()) {
$pipelines = [];
foreach ($this->class as $name => $className) {
if (!class_exists($className)) {
throw new \LogicException("Analytics class '" . $className . "' does not exist!");
}
$class = new $className();
$class->setParams($params);
$pipelines[$name] = $class->get();
}
return $pipelines;
} else {
$className = $this->class;
if (!class_exists($className)) {
throw new \LogicException("Analytics class '" . $className . "' does not exist!");
}
$class = new $className();
$class->setParams($params);
return $class->get();
}
} | [
"public",
"function",
"getAggregate",
"(",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getMultipipeline",
"(",
")",
")",
"{",
"$",
"pipelines",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"class",
"as",
"$",
... | Build a output Db Model aggregation pipeline array.
@param array $params params
@return array the pipeline | [
"Build",
"a",
"output",
"Db",
"Model",
"aggregation",
"pipeline",
"array",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/AnalyticsBundle/Model/AnalyticModel.php#L279-L301 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/DependencyInjection/Compiler/RestrictionFieldsCompilerPass.php | RestrictionFieldsCompilerPass.process | public function process(ContainerBuilder $container)
{
$this->documentMap = $container->get('graviton.document.map');
$map = [];
foreach ($this->documentMap->getDocuments() as $document) {
$restrictionFields = $this->documentMap->getFieldNamesFlat(
$document,
'',
'',
function ($field) {
return $field->getRestrictions();
},
true
);
$finalRestrictionFields = [];
foreach ($restrictionFields as $key => $field) {
// cleanup name! .0. has to be .. for rql!
$key = preg_replace('@\.([0-9]+)\.@i', '..', $key);
$finalRestrictionFields[$key] = $field->getRestrictions();
}
$map[$document->getClass()] = $finalRestrictionFields;
}
$container->setParameter('graviton.document.restriction.fields', $map);
} | php | public function process(ContainerBuilder $container)
{
$this->documentMap = $container->get('graviton.document.map');
$map = [];
foreach ($this->documentMap->getDocuments() as $document) {
$restrictionFields = $this->documentMap->getFieldNamesFlat(
$document,
'',
'',
function ($field) {
return $field->getRestrictions();
},
true
);
$finalRestrictionFields = [];
foreach ($restrictionFields as $key => $field) {
// cleanup name! .0. has to be .. for rql!
$key = preg_replace('@\.([0-9]+)\.@i', '..', $key);
$finalRestrictionFields[$key] = $field->getRestrictions();
}
$map[$document->getClass()] = $finalRestrictionFields;
}
$container->setParameter('graviton.document.restriction.fields', $map);
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"this",
"->",
"documentMap",
"=",
"$",
"container",
"->",
"get",
"(",
"'graviton.document.map'",
")",
";",
"$",
"map",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"th... | prepare a map of base data restrictions for Restriction\Manager
@param ContainerBuilder $container container builder
@return void | [
"prepare",
"a",
"map",
"of",
"base",
"data",
"restrictions",
"for",
"Restriction",
"\\",
"Manager"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/RestrictionFieldsCompilerPass.php#L31-L58 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Definition/Loader/Strategy/DirStrategy.php | DirStrategy.load | public function load($input)
{
return array_map(
function (SplFileInfo $file) {
return $file->getContents();
},
array_values(iterator_to_array($this->getFinder($input)))
);
} | php | public function load($input)
{
return array_map(
function (SplFileInfo $file) {
return $file->getContents();
},
array_values(iterator_to_array($this->getFinder($input)))
);
} | [
"public",
"function",
"load",
"(",
"$",
"input",
")",
"{",
"return",
"array_map",
"(",
"function",
"(",
"SplFileInfo",
"$",
"file",
")",
"{",
"return",
"$",
"file",
"->",
"getContents",
"(",
")",
";",
"}",
",",
"array_values",
"(",
"iterator_to_array",
"... | load raw JSON data
@param string|null $input input from command
@return string[] | [
"load",
"raw",
"JSON",
"data"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/Loader/Strategy/DirStrategy.php#L37-L45 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/DependencyInjection/Compiler/DocumentFieldNamesCompilerPass.php | DocumentFieldNamesCompilerPass.getFieldNames | private function getFieldNames(Document $document)
{
$result = [];
foreach ($document->getFields() as $field) {
$result[$field->getFieldName()] = $field->getExposedName();
}
return $result;
} | php | private function getFieldNames(Document $document)
{
$result = [];
foreach ($document->getFields() as $field) {
$result[$field->getFieldName()] = $field->getExposedName();
}
return $result;
} | [
"private",
"function",
"getFieldNames",
"(",
"Document",
"$",
"document",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"document",
"->",
"getFields",
"(",
")",
"as",
"$",
"field",
")",
"{",
"$",
"result",
"[",
"$",
"field",
"->",... | Get field names
@param Document $document Document
@return array | [
"Get",
"field",
"names"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/DocumentFieldNamesCompilerPass.php#L49-L56 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Composer/ScriptHandler.php | ScriptHandler.generateDynamicBundles | public static function generateDynamicBundles(Event $event)
{
$options = self::getOptions($event);
$consolePath = $options['symfony-app-dir'];
$cmd = escapeshellarg('graviton:generate:dynamicbundles').' --json';
self::executeCommand($event, $consolePath, $cmd);
} | php | public static function generateDynamicBundles(Event $event)
{
$options = self::getOptions($event);
$consolePath = $options['symfony-app-dir'];
$cmd = escapeshellarg('graviton:generate:dynamicbundles').' --json';
self::executeCommand($event, $consolePath, $cmd);
} | [
"public",
"static",
"function",
"generateDynamicBundles",
"(",
"Event",
"$",
"event",
")",
"{",
"$",
"options",
"=",
"self",
"::",
"getOptions",
"(",
"$",
"event",
")",
";",
"$",
"consolePath",
"=",
"$",
"options",
"[",
"'symfony-app-dir'",
"]",
";",
"$",
... | Generates dynamic bundles
@param CommandEvent $event Event
@return void | [
"Generates",
"dynamic",
"bundles"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Composer/ScriptHandler.php#L27-L34 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Definition/Utils/ConstraintNormalizer.php | ConstraintNormalizer.normalize | public static function normalize(Constraint $constraint)
{
return [
'name' => $constraint->getName(),
'options' => array_map(
function (ConstraintOption $option) {
return [
'name' => $option->getName(),
'value' => $option->getValue(),
];
},
$constraint->getOptions()
),
];
} | php | public static function normalize(Constraint $constraint)
{
return [
'name' => $constraint->getName(),
'options' => array_map(
function (ConstraintOption $option) {
return [
'name' => $option->getName(),
'value' => $option->getValue(),
];
},
$constraint->getOptions()
),
];
} | [
"public",
"static",
"function",
"normalize",
"(",
"Constraint",
"$",
"constraint",
")",
"{",
"return",
"[",
"'name'",
"=>",
"$",
"constraint",
"->",
"getName",
"(",
")",
",",
"'options'",
"=>",
"array_map",
"(",
"function",
"(",
"ConstraintOption",
"$",
"opt... | Convert constraint to array to selerialile it via json_encode
@param Constraint $constraint Constraint
@return array | [
"Convert",
"constraint",
"to",
"array",
"to",
"selerialile",
"it",
"via",
"json_encode"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/Utils/ConstraintNormalizer.php#L25-L39 | train |
libgraviton/graviton | src/Graviton/LogBundle/Monolog/Processor/RequestIdProcessor.php | RequestIdProcessor.processRecord | public function processRecord(array $record)
{
if (is_null($this->requestId)) {
$this->requestId = uniqid('');
}
$record['extra']['requestId'] = $this->requestId;
return $record;
} | php | public function processRecord(array $record)
{
if (is_null($this->requestId)) {
$this->requestId = uniqid('');
}
$record['extra']['requestId'] = $this->requestId;
return $record;
} | [
"public",
"function",
"processRecord",
"(",
"array",
"$",
"record",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"requestId",
")",
")",
"{",
"$",
"this",
"->",
"requestId",
"=",
"uniqid",
"(",
"''",
")",
";",
"}",
"$",
"record",
"[",
"'e... | processes the record and adds a random request id
@param array $record record
@return array new record | [
"processes",
"the",
"record",
"and",
"adds",
"a",
"random",
"request",
"id"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/LogBundle/Monolog/Processor/RequestIdProcessor.php#L28-L37 | train |
libgraviton/graviton | src/Graviton/SecurityBundle/Authentication/Strategies/CookieFieldStrategy.php | CookieFieldStrategy.apply | public function apply(Request $request)
{
$bagValue = $this->extractFieldInfo($request->cookies, $this->field);
// this needs to be available in a later state of the application
$this->extractAdUsername($request, $bagValue);
return $this->extractCoreId($request, $bagValue);
} | php | public function apply(Request $request)
{
$bagValue = $this->extractFieldInfo($request->cookies, $this->field);
// this needs to be available in a later state of the application
$this->extractAdUsername($request, $bagValue);
return $this->extractCoreId($request, $bagValue);
} | [
"public",
"function",
"apply",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"bagValue",
"=",
"$",
"this",
"->",
"extractFieldInfo",
"(",
"$",
"request",
"->",
"cookies",
",",
"$",
"this",
"->",
"field",
")",
";",
"// this needs to be available in a later sta... | Applies the defined strategy on the provided request.
Value may contain a coma separated string values, we use first as identifier.
@param Request $request request to handle
@return string | [
"Applies",
"the",
"defined",
"strategy",
"on",
"the",
"provided",
"request",
".",
"Value",
"may",
"contain",
"a",
"coma",
"separated",
"string",
"values",
"we",
"use",
"first",
"as",
"identifier",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SecurityBundle/Authentication/Strategies/CookieFieldStrategy.php#L52-L60 | train |
libgraviton/graviton | src/Graviton/SecurityBundle/Authentication/Strategies/CookieFieldStrategy.php | CookieFieldStrategy.extractAdUsername | protected function extractAdUsername(Request $request, $value)
{
$pattern = "/((?m)(?<=\b".self::COOKIE_FIELD_NAME."=)[^;]*)/i";
preg_match($pattern, $value, $matches);
if ($matches) {
$request->attributes->set(self::CONFIGURATION_PARAMETER_USER_ID, $matches[0]);
return $matches[0];
}
return $value;
} | php | protected function extractAdUsername(Request $request, $value)
{
$pattern = "/((?m)(?<=\b".self::COOKIE_FIELD_NAME."=)[^;]*)/i";
preg_match($pattern, $value, $matches);
if ($matches) {
$request->attributes->set(self::CONFIGURATION_PARAMETER_USER_ID, $matches[0]);
return $matches[0];
}
return $value;
} | [
"protected",
"function",
"extractAdUsername",
"(",
"Request",
"$",
"request",
",",
"$",
"value",
")",
"{",
"$",
"pattern",
"=",
"\"/((?m)(?<=\\b\"",
".",
"self",
"::",
"COOKIE_FIELD_NAME",
".",
"\"=)[^;]*)/i\"",
";",
"preg_match",
"(",
"$",
"pattern",
",",
"$"... | Finds and extracts the ad username from the cookie.
@param Request $request Request stack that controls the lifecycle of requests
@param string $value The string the value of self::COOKIE_FIELD_NAME shall be extracted from.
@return string | [
"Finds",
"and",
"extracts",
"the",
"ad",
"username",
"from",
"the",
"cookie",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SecurityBundle/Authentication/Strategies/CookieFieldStrategy.php#L80-L92 | train |
libgraviton/graviton | src/Graviton/SecurityBundle/Authentication/Strategies/CookieFieldStrategy.php | CookieFieldStrategy.extractCoreId | protected function extractCoreId(Request $request, $text)
{
$pattern = "/((?m)(?<=\b".self::COOKIE_VALUE_CORE_ID."=)[^;]*)/i";
preg_match($pattern, $text, $matches);
if ($matches) {
$request->attributes->set(self::CONFIGURATION_PARAMETER_CORE_ID, $matches[0]);
return $matches[0];
}
return $text;
} | php | protected function extractCoreId(Request $request, $text)
{
$pattern = "/((?m)(?<=\b".self::COOKIE_VALUE_CORE_ID."=)[^;]*)/i";
preg_match($pattern, $text, $matches);
if ($matches) {
$request->attributes->set(self::CONFIGURATION_PARAMETER_CORE_ID, $matches[0]);
return $matches[0];
}
return $text;
} | [
"protected",
"function",
"extractCoreId",
"(",
"Request",
"$",
"request",
",",
"$",
"text",
")",
"{",
"$",
"pattern",
"=",
"\"/((?m)(?<=\\b\"",
".",
"self",
"::",
"COOKIE_VALUE_CORE_ID",
".",
"\"=)[^;]*)/i\"",
";",
"preg_match",
"(",
"$",
"pattern",
",",
"$",
... | Finds and extracts the core system id from tha cookie.
@param Request $request Request stack that controls the lifecycle of requests
@param string $text String to be examined for the core id.
@return string | [
"Finds",
"and",
"extracts",
"the",
"core",
"system",
"id",
"from",
"tha",
"cookie",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SecurityBundle/Authentication/Strategies/CookieFieldStrategy.php#L102-L114 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/Entity/Translatable.php | Translatable.getDefaultLanguage | public static function getDefaultLanguage()
{
if (!is_null(self::$defaultLanguage)) {
return self::$defaultLanguage;
}
if (!file_exists(self::$defaultLanguageFile)) {
throw new \LogicException('Default language file '.self::$defaultLanguageFile.' does not exist');
}
self::$defaultLanguage = file_get_contents(self::$defaultLanguageFile);
return self::$defaultLanguage;
} | php | public static function getDefaultLanguage()
{
if (!is_null(self::$defaultLanguage)) {
return self::$defaultLanguage;
}
if (!file_exists(self::$defaultLanguageFile)) {
throw new \LogicException('Default language file '.self::$defaultLanguageFile.' does not exist');
}
self::$defaultLanguage = file_get_contents(self::$defaultLanguageFile);
return self::$defaultLanguage;
} | [
"public",
"static",
"function",
"getDefaultLanguage",
"(",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"self",
"::",
"$",
"defaultLanguage",
")",
")",
"{",
"return",
"self",
"::",
"$",
"defaultLanguage",
";",
"}",
"if",
"(",
"!",
"file_exists",
"(",
"self"... | returns the default language as statically generated in a file
@return string default language | [
"returns",
"the",
"default",
"language",
"as",
"statically",
"generated",
"in",
"a",
"file"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Entity/Translatable.php#L60-L72 | train |
libgraviton/graviton | src/Graviton/SecurityBundle/Authentication/Strategies/MultiStrategy.php | MultiStrategy.apply | public function apply(Request $request)
{
foreach ($this->strategies as $strategy) {
$name = $strategy->apply($request);
if ($strategy->stopPropagation()) {
$this->roles = $strategy->getRoles();
return $name;
}
}
return false;
} | php | public function apply(Request $request)
{
foreach ($this->strategies as $strategy) {
$name = $strategy->apply($request);
if ($strategy->stopPropagation()) {
$this->roles = $strategy->getRoles();
return $name;
}
}
return false;
} | [
"public",
"function",
"apply",
"(",
"Request",
"$",
"request",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"strategies",
"as",
"$",
"strategy",
")",
"{",
"$",
"name",
"=",
"$",
"strategy",
"->",
"apply",
"(",
"$",
"request",
")",
";",
"if",
"(",
"... | Applies the defined strategies on the provided request.
@param Request $request request to handle
@return string | [
"Applies",
"the",
"defined",
"strategies",
"on",
"the",
"provided",
"request",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SecurityBundle/Authentication/Strategies/MultiStrategy.php#L45-L56 | train |
libgraviton/graviton | src/Graviton/RestBundle/Restriction/Handler/Whoami.php | Whoami.getValue | public function getValue(DocumentRepository $repository, $fieldPath)
{
$user = 'anonymous';
$securityUser = $this->securityUtils->getSecurityUser();
if ($securityUser instanceof SecurityUser) {
$user = trim(strtolower($securityUser->getUsername()));
}
return $user;
} | php | public function getValue(DocumentRepository $repository, $fieldPath)
{
$user = 'anonymous';
$securityUser = $this->securityUtils->getSecurityUser();
if ($securityUser instanceof SecurityUser) {
$user = trim(strtolower($securityUser->getUsername()));
}
return $user;
} | [
"public",
"function",
"getValue",
"(",
"DocumentRepository",
"$",
"repository",
",",
"$",
"fieldPath",
")",
"{",
"$",
"user",
"=",
"'anonymous'",
";",
"$",
"securityUser",
"=",
"$",
"this",
"->",
"securityUtils",
"->",
"getSecurityUser",
"(",
")",
";",
"if",... | gets the actual value or an AbstractQueryNode that is used to filter the data.
@param DocumentRepository $repository the repository
@param string $fieldPath field path
@return string|AbstractQueryNode string for eq() filtering or a AbstractQueryNode instance | [
"gets",
"the",
"actual",
"value",
"or",
"an",
"AbstractQueryNode",
"that",
"is",
"used",
"to",
"filter",
"the",
"data",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Restriction/Handler/Whoami.php#L52-L62 | train |
libgraviton/graviton | src/Graviton/RestBundle/Serializer/ContextFactoryAbstract.php | ContextFactoryAbstract.workOnInstance | protected function workOnInstance(Context $context)
{
$context = $context->setSerializeNull($this->setSerializeNull);
// group override?
if (true === $this->overrideHeaderAllowed &&
$this->requestStack instanceof RequestStack &&
$this->requestStack->getCurrentRequest() instanceof Request
) {
$headerValue = $this->requestStack->getCurrentRequest()->headers->get($this->overrideHeaderName);
if (!is_null($headerValue)) {
$this->groups = array_map('trim', explode(',', $headerValue));
}
}
$serializerGroups = [GroupsExclusionStrategy::DEFAULT_GROUP];
if (is_array($this->groups) && !empty($this->groups)) {
$serializerGroups = array_merge($serializerGroups, $this->groups);
}
foreach ($this->exclusionStrategies as $strategy) {
$context->addExclusionStrategy($strategy);
}
return $context->setGroups($serializerGroups);
} | php | protected function workOnInstance(Context $context)
{
$context = $context->setSerializeNull($this->setSerializeNull);
// group override?
if (true === $this->overrideHeaderAllowed &&
$this->requestStack instanceof RequestStack &&
$this->requestStack->getCurrentRequest() instanceof Request
) {
$headerValue = $this->requestStack->getCurrentRequest()->headers->get($this->overrideHeaderName);
if (!is_null($headerValue)) {
$this->groups = array_map('trim', explode(',', $headerValue));
}
}
$serializerGroups = [GroupsExclusionStrategy::DEFAULT_GROUP];
if (is_array($this->groups) && !empty($this->groups)) {
$serializerGroups = array_merge($serializerGroups, $this->groups);
}
foreach ($this->exclusionStrategies as $strategy) {
$context->addExclusionStrategy($strategy);
}
return $context->setGroups($serializerGroups);
} | [
"protected",
"function",
"workOnInstance",
"(",
"Context",
"$",
"context",
")",
"{",
"$",
"context",
"=",
"$",
"context",
"->",
"setSerializeNull",
"(",
"$",
"this",
"->",
"setSerializeNull",
")",
";",
"// group override?",
"if",
"(",
"true",
"===",
"$",
"th... | sets the necessary properties on the context
@param Context $context context
@return Context context | [
"sets",
"the",
"necessary",
"properties",
"on",
"the",
"context"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Serializer/ContextFactoryAbstract.php#L131-L156 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/DependencyInjection/Compiler/GeneratorHashCompilerPass.php | GeneratorHashCompilerPass.process | public function process(ContainerBuilder $container)
{
// first type of hash: the genhash'es of all GravitonDyn bundles
$dir = $container->getParameter('graviton.generator.dynamicbundle.dir');
$dynHash = '';
if (is_dir($dir)) {
$finder = (new Finder())
->in($dir)
->files()
->sortByName()
->name('genhash');
foreach ($finder as $file) {
$dynHash .= DIRECTORY_SEPARATOR . $file->getContents();
}
}
// 2nd hash: configuration of our own graviton things (static stuff)
$staticHash = '';
if (is_dir(__DIR__.'/../../../')) {
$finder = (new Finder())
->in(__DIR__ . '/../../../')
->path('/serializer/')
->path('/doctrine/')
->path('/schema/')
->notPath('/Tests/')
->files()
->sortByName()
->name('*.xml')
->name('*.json');
foreach ($finder as $file) {
$staticHash .= DIRECTORY_SEPARATOR . sha1_file($file->getPathname());
}
}
$dynHash = sha1($dynHash);
$staticHash = sha1($staticHash);
$allHash = sha1($dynHash . DIRECTORY_SEPARATOR . $staticHash);
$container->setParameter('graviton.generator.hash.dyn', $dynHash);
$container->setParameter('graviton.generator.hash.static', $staticHash);
$container->setParameter('graviton.generator.hash.all', $allHash);
} | php | public function process(ContainerBuilder $container)
{
// first type of hash: the genhash'es of all GravitonDyn bundles
$dir = $container->getParameter('graviton.generator.dynamicbundle.dir');
$dynHash = '';
if (is_dir($dir)) {
$finder = (new Finder())
->in($dir)
->files()
->sortByName()
->name('genhash');
foreach ($finder as $file) {
$dynHash .= DIRECTORY_SEPARATOR . $file->getContents();
}
}
// 2nd hash: configuration of our own graviton things (static stuff)
$staticHash = '';
if (is_dir(__DIR__.'/../../../')) {
$finder = (new Finder())
->in(__DIR__ . '/../../../')
->path('/serializer/')
->path('/doctrine/')
->path('/schema/')
->notPath('/Tests/')
->files()
->sortByName()
->name('*.xml')
->name('*.json');
foreach ($finder as $file) {
$staticHash .= DIRECTORY_SEPARATOR . sha1_file($file->getPathname());
}
}
$dynHash = sha1($dynHash);
$staticHash = sha1($staticHash);
$allHash = sha1($dynHash . DIRECTORY_SEPARATOR . $staticHash);
$container->setParameter('graviton.generator.hash.dyn', $dynHash);
$container->setParameter('graviton.generator.hash.static', $staticHash);
$container->setParameter('graviton.generator.hash.all', $allHash);
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"// first type of hash: the genhash'es of all GravitonDyn bundles",
"$",
"dir",
"=",
"$",
"container",
"->",
"getParameter",
"(",
"'graviton.generator.dynamicbundle.dir'",
")",
";",
"$",
... | generate the hashes
@param ContainerBuilder $container container builder
@return void | [
"generate",
"the",
"hashes"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/DependencyInjection/Compiler/GeneratorHashCompilerPass.php#L27-L71 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Generator/DynamicBundleBundleGenerator.php | DynamicBundleBundleGenerator.generate | public function generate(array $bundleList, $bundleBundleNamespace, $bundleName, $targetFilename)
{
$absoluteList = [];
foreach ($bundleList as $namespace) {
$absoluteList[] = '\\' . str_replace('/', '\\', $namespace) .
'\\' . str_replace('/', '', $namespace);
}
if (is_array($this->additions)) {
$absoluteList = array_merge($absoluteList, $this->additions);
}
$absoluteList = array_unique($absoluteList);
sort($absoluteList);
$parameters = array(
'namespace' => str_replace('/', '\\', $bundleBundleNamespace),
'bundleName' => $bundleName,
'bundleClassList' => $absoluteList
);
$this->renderFile('bundle/DynamicBundleBundle.php.twig', $targetFilename, $parameters);
} | php | public function generate(array $bundleList, $bundleBundleNamespace, $bundleName, $targetFilename)
{
$absoluteList = [];
foreach ($bundleList as $namespace) {
$absoluteList[] = '\\' . str_replace('/', '\\', $namespace) .
'\\' . str_replace('/', '', $namespace);
}
if (is_array($this->additions)) {
$absoluteList = array_merge($absoluteList, $this->additions);
}
$absoluteList = array_unique($absoluteList);
sort($absoluteList);
$parameters = array(
'namespace' => str_replace('/', '\\', $bundleBundleNamespace),
'bundleName' => $bundleName,
'bundleClassList' => $absoluteList
);
$this->renderFile('bundle/DynamicBundleBundle.php.twig', $targetFilename, $parameters);
} | [
"public",
"function",
"generate",
"(",
"array",
"$",
"bundleList",
",",
"$",
"bundleBundleNamespace",
",",
"$",
"bundleName",
",",
"$",
"targetFilename",
")",
"{",
"$",
"absoluteList",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"bundleList",
"as",
"$",
"name... | Generate the BundleBundle
@param array $bundleList List of bundles
@param string $bundleBundleNamespace Namespace of our BundleBundle
@param string $bundleName Name of the bundle
@param string $targetFilename Where to write the list to
@return void | [
"Generate",
"the",
"BundleBundle"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Generator/DynamicBundleBundleGenerator.php#L47-L69 | train |
libgraviton/graviton | src/Graviton/CacheBundle/Listener/IfNoneMatchResponseListener.php | IfNoneMatchResponseListener.onKernelResponse | public function onKernelResponse(FilterResponseEvent $event)
{
$response = $event->getResponse();
$request = $event->getRequest();
$ifNoneMatch = $request->headers->get('if-none-match');
$etag = $response->headers->get('ETag', 'empty');
if ($ifNoneMatch === $etag) {
$response->setStatusCode(304);
$response->setContent(null);
}
} | php | public function onKernelResponse(FilterResponseEvent $event)
{
$response = $event->getResponse();
$request = $event->getRequest();
$ifNoneMatch = $request->headers->get('if-none-match');
$etag = $response->headers->get('ETag', 'empty');
if ($ifNoneMatch === $etag) {
$response->setStatusCode(304);
$response->setContent(null);
}
} | [
"public",
"function",
"onKernelResponse",
"(",
"FilterResponseEvent",
"$",
"event",
")",
"{",
"$",
"response",
"=",
"$",
"event",
"->",
"getResponse",
"(",
")",
";",
"$",
"request",
"=",
"$",
"event",
"->",
"getRequest",
"(",
")",
";",
"$",
"ifNoneMatch",
... | add a IfNoneMatch header to the response
@param FilterResponseEvent $event response listener event
@return void | [
"add",
"a",
"IfNoneMatch",
"header",
"to",
"the",
"response"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CacheBundle/Listener/IfNoneMatchResponseListener.php#L26-L38 | train |
libgraviton/graviton | src/Graviton/CoreBundle/Compiler/HttpClientOptionsCompilerPass.php | HttpClientOptionsCompilerPass.process | public function process(ContainerBuilder $container)
{
$baseOptions = [
'verify' => false
];
// system settings envs
if (isset($_ENV['HTTP_PROXY']) && !empty($_ENV['HTTP_PROXY'])) {
$this->setProxy($_ENV['HTTP_PROXY'], 'http');
}
if (isset($_ENV['HTTPS_PROXY']) && !empty($_ENV['HTTPS_PROXY'])) {
$this->setProxy($_ENV['HTTPS_PROXY'], 'https');
}
if (isset($_ENV['NO_PROXY']) && !empty($_ENV['NO_PROXY'])) {
$this->setNoProxyList($_ENV['NO_PROXY']);
}
// is there the old setting?
if (isset($_ENV['GRAVITON_PROXY_CURLOPTS'])) {
$yamlSettings = Yaml::parse($_ENV['GRAVITON_PROXY_CURLOPTS']);
if (is_array($yamlSettings) && isset($yamlSettings['proxy'])) {
$this->setProxy($yamlSettings['proxy']);
}
if (is_array($yamlSettings) && isset($yamlSettings['noproxy'])) {
$this->setNoProxyList($yamlSettings['noproxy']);
}
}
// new settings -> override all
if (null !== $container->getParameter('graviton.proxy')) {
$this->setProxy($container->getParameter('graviton.proxy'));
}
if (null !== $container->getParameter('graviton.noproxy')) {
$this->setNoProxyList($container->getParameter('graviton.noproxy'));
}
// any proxy?
if (!empty($this->proxySettings)) {
$baseOptions['proxy'] = $this->proxySettings;
}
$container->setParameter(
'graviton.core.http.client.options',
$baseOptions
);
} | php | public function process(ContainerBuilder $container)
{
$baseOptions = [
'verify' => false
];
// system settings envs
if (isset($_ENV['HTTP_PROXY']) && !empty($_ENV['HTTP_PROXY'])) {
$this->setProxy($_ENV['HTTP_PROXY'], 'http');
}
if (isset($_ENV['HTTPS_PROXY']) && !empty($_ENV['HTTPS_PROXY'])) {
$this->setProxy($_ENV['HTTPS_PROXY'], 'https');
}
if (isset($_ENV['NO_PROXY']) && !empty($_ENV['NO_PROXY'])) {
$this->setNoProxyList($_ENV['NO_PROXY']);
}
// is there the old setting?
if (isset($_ENV['GRAVITON_PROXY_CURLOPTS'])) {
$yamlSettings = Yaml::parse($_ENV['GRAVITON_PROXY_CURLOPTS']);
if (is_array($yamlSettings) && isset($yamlSettings['proxy'])) {
$this->setProxy($yamlSettings['proxy']);
}
if (is_array($yamlSettings) && isset($yamlSettings['noproxy'])) {
$this->setNoProxyList($yamlSettings['noproxy']);
}
}
// new settings -> override all
if (null !== $container->getParameter('graviton.proxy')) {
$this->setProxy($container->getParameter('graviton.proxy'));
}
if (null !== $container->getParameter('graviton.noproxy')) {
$this->setNoProxyList($container->getParameter('graviton.noproxy'));
}
// any proxy?
if (!empty($this->proxySettings)) {
$baseOptions['proxy'] = $this->proxySettings;
}
$container->setParameter(
'graviton.core.http.client.options',
$baseOptions
);
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"baseOptions",
"=",
"[",
"'verify'",
"=>",
"false",
"]",
";",
"// system settings envs",
"if",
"(",
"isset",
"(",
"$",
"_ENV",
"[",
"'HTTP_PROXY'",
"]",
")",
"&&",
"... | add guzzle options
@param ContainerBuilder $container Container
@return void | [
"add",
"guzzle",
"options"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Compiler/HttpClientOptionsCompilerPass.php#L32-L77 | train |
libgraviton/graviton | src/Graviton/CoreBundle/Compiler/HttpClientOptionsCompilerPass.php | HttpClientOptionsCompilerPass.setProxy | private function setProxy($proxy, $onlyProtocol = null)
{
$proxy = trim($proxy);
if (null == $onlyProtocol) {
$this->proxySettings['http'] = $proxy;
$this->proxySettings['https'] = $proxy;
} else {
$this->proxySettings[$onlyProtocol] = $proxy;
}
} | php | private function setProxy($proxy, $onlyProtocol = null)
{
$proxy = trim($proxy);
if (null == $onlyProtocol) {
$this->proxySettings['http'] = $proxy;
$this->proxySettings['https'] = $proxy;
} else {
$this->proxySettings[$onlyProtocol] = $proxy;
}
} | [
"private",
"function",
"setProxy",
"(",
"$",
"proxy",
",",
"$",
"onlyProtocol",
"=",
"null",
")",
"{",
"$",
"proxy",
"=",
"trim",
"(",
"$",
"proxy",
")",
";",
"if",
"(",
"null",
"==",
"$",
"onlyProtocol",
")",
"{",
"$",
"this",
"->",
"proxySettings",... | set the proxy
@param string $proxy the proxy
@param null|boolean $onlyProtocol only set certain protocol
@return void | [
"set",
"the",
"proxy"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Compiler/HttpClientOptionsCompilerPass.php#L87-L96 | train |
libgraviton/graviton | src/Graviton/CoreBundle/Compiler/HttpClientOptionsCompilerPass.php | HttpClientOptionsCompilerPass.setNoProxyList | private function setNoProxyList($list)
{
if (is_array($list)) {
$this->proxySettings['no'] = array_map('trim', $list);
return;
}
if (is_string($list) && strpos($list, ',') !== false) {
$this->proxySettings['no'] = explode(',', $list);
} elseif (is_string($list) && strpos($list, ' ') !== false) {
$this->proxySettings['no'] = explode(' ', $list);
}
$this->proxySettings['no'] = array_map('trim', $this->proxySettings['no']);
} | php | private function setNoProxyList($list)
{
if (is_array($list)) {
$this->proxySettings['no'] = array_map('trim', $list);
return;
}
if (is_string($list) && strpos($list, ',') !== false) {
$this->proxySettings['no'] = explode(',', $list);
} elseif (is_string($list) && strpos($list, ' ') !== false) {
$this->proxySettings['no'] = explode(' ', $list);
}
$this->proxySettings['no'] = array_map('trim', $this->proxySettings['no']);
} | [
"private",
"function",
"setNoProxyList",
"(",
"$",
"list",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"list",
")",
")",
"{",
"$",
"this",
"->",
"proxySettings",
"[",
"'no'",
"]",
"=",
"array_map",
"(",
"'trim'",
",",
"$",
"list",
")",
";",
"return",
... | set the no proxy setting
@param string $list either string or array
@return void | [
"set",
"the",
"no",
"proxy",
"setting"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Compiler/HttpClientOptionsCompilerPass.php#L105-L118 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Serializer/Handler/SchemaAdditionalPropertiesHandler.php | SchemaAdditionalPropertiesHandler.serializeSchemaAdditionalPropertiesToJson | public function serializeSchemaAdditionalPropertiesToJson(
JsonSerializationVisitor $visitor,
SchemaAdditionalProperties $additionalProperties,
array $type,
Context $context
) {
$properties = $additionalProperties->getProperties();
// case for v4 schema
if (is_bool($properties)) {
return $visitor->visitBoolean($properties, [], $context);
}
// case for schema inside additionalProperties, swagger exclusive
if ($properties instanceof Schema) {
return $visitor->getNavigator()->accept(
$properties,
['name' => 'Graviton\SchemaBundle\Document\Schema'],
$context
);
}
} | php | public function serializeSchemaAdditionalPropertiesToJson(
JsonSerializationVisitor $visitor,
SchemaAdditionalProperties $additionalProperties,
array $type,
Context $context
) {
$properties = $additionalProperties->getProperties();
// case for v4 schema
if (is_bool($properties)) {
return $visitor->visitBoolean($properties, [], $context);
}
// case for schema inside additionalProperties, swagger exclusive
if ($properties instanceof Schema) {
return $visitor->getNavigator()->accept(
$properties,
['name' => 'Graviton\SchemaBundle\Document\Schema'],
$context
);
}
} | [
"public",
"function",
"serializeSchemaAdditionalPropertiesToJson",
"(",
"JsonSerializationVisitor",
"$",
"visitor",
",",
"SchemaAdditionalProperties",
"$",
"additionalProperties",
",",
"array",
"$",
"type",
",",
"Context",
"$",
"context",
")",
"{",
"$",
"properties",
"=... | Serialize additionalProperties to JSON
@param JsonSerializationVisitor $visitor Visitor
@param SchemaAdditionalProperties $additionalProperties properties
@param array $type Type
@param Context $context Context
@return string|null | [
"Serialize",
"additionalProperties",
"to",
"JSON"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Serializer/Handler/SchemaAdditionalPropertiesHandler.php#L33-L55 | train |
libgraviton/graviton | src/Graviton/AnalyticsBundle/Manager/ServiceManager.php | ServiceManager.getServices | public function getServices()
{
$services = $this->cacheProvider->fetch(self::CACHE_KEY_SERVICES_URLS);
if (is_array($services)) {
return $services;
}
$services = [];
foreach ($this->analyticsServices as $name => $service) {
if (is_numeric($name)) {
continue;
}
$services[] = [
'$ref' => $this->router->generate(
'graviton_analytics_service',
[
'service' => $service['route']
],
false
),
'profile' => $this->router->generate(
'graviton_analytics_service_schema',
[
'service' => $service['route']
],
true
)
];
}
$this->cacheProvider->save(
self::CACHE_KEY_SERVICES_URLS,
$services,
$this->cacheTimeMetadata
);
return $services;
} | php | public function getServices()
{
$services = $this->cacheProvider->fetch(self::CACHE_KEY_SERVICES_URLS);
if (is_array($services)) {
return $services;
}
$services = [];
foreach ($this->analyticsServices as $name => $service) {
if (is_numeric($name)) {
continue;
}
$services[] = [
'$ref' => $this->router->generate(
'graviton_analytics_service',
[
'service' => $service['route']
],
false
),
'profile' => $this->router->generate(
'graviton_analytics_service_schema',
[
'service' => $service['route']
],
true
)
];
}
$this->cacheProvider->save(
self::CACHE_KEY_SERVICES_URLS,
$services,
$this->cacheTimeMetadata
);
return $services;
} | [
"public",
"function",
"getServices",
"(",
")",
"{",
"$",
"services",
"=",
"$",
"this",
"->",
"cacheProvider",
"->",
"fetch",
"(",
"self",
"::",
"CACHE_KEY_SERVICES_URLS",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"services",
")",
")",
"{",
"return",
"$"... | Return array of available services
@return array | [
"Return",
"array",
"of",
"available",
"services"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/AnalyticsBundle/Manager/ServiceManager.php#L107-L143 | train |
libgraviton/graviton | src/Graviton/AnalyticsBundle/Manager/ServiceManager.php | ServiceManager.getData | public function getData()
{
$serviceRoute = $this->requestStack->getCurrentRequest()
->get('service');
// Locate the model definition
$model = $this->getAnalyticModel($serviceRoute);
$cacheTime = $model->getCacheTime();
$cacheKey = $this->getCacheKey($model);
//Cached data if configured
if ($cacheTime &&
!$this->requestStack->getCurrentRequest()->headers->has($this->skipCacheHeaderName) &&
$cache = $this->cacheProvider->fetch($cacheKey)
) {
return $cache;
}
$data = $this->analyticsManager->getData($model, $this->getServiceParameters($model));
if ($cacheTime) {
$this->cacheProvider->save($cacheKey, $data, $cacheTime);
}
return $data;
} | php | public function getData()
{
$serviceRoute = $this->requestStack->getCurrentRequest()
->get('service');
// Locate the model definition
$model = $this->getAnalyticModel($serviceRoute);
$cacheTime = $model->getCacheTime();
$cacheKey = $this->getCacheKey($model);
//Cached data if configured
if ($cacheTime &&
!$this->requestStack->getCurrentRequest()->headers->has($this->skipCacheHeaderName) &&
$cache = $this->cacheProvider->fetch($cacheKey)
) {
return $cache;
}
$data = $this->analyticsManager->getData($model, $this->getServiceParameters($model));
if ($cacheTime) {
$this->cacheProvider->save($cacheKey, $data, $cacheTime);
}
return $data;
} | [
"public",
"function",
"getData",
"(",
")",
"{",
"$",
"serviceRoute",
"=",
"$",
"this",
"->",
"requestStack",
"->",
"getCurrentRequest",
"(",
")",
"->",
"get",
"(",
"'service'",
")",
";",
"// Locate the model definition",
"$",
"model",
"=",
"$",
"this",
"->",... | Will map and find data for defined route
@return array | [
"Will",
"map",
"and",
"find",
"data",
"for",
"defined",
"route"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/AnalyticsBundle/Manager/ServiceManager.php#L169-L195 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.