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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
libgraviton/graviton | src/Graviton/RestBundle/Listener/WriteLockListener.php | WriteLockListener.doRandomDelay | private function doRandomDelay($url)
{
return array_reduce(
$this->randomWaitUrls,
function ($carry, $value) use ($url) {
if ($carry !== true) {
return (strpos($url, $value) === 0);
} else {
return $carry;
}
}
);
} | php | private function doRandomDelay($url)
{
return array_reduce(
$this->randomWaitUrls,
function ($carry, $value) use ($url) {
if ($carry !== true) {
return (strpos($url, $value) === 0);
} else {
return $carry;
}
}
);
} | [
"private",
"function",
"doRandomDelay",
"(",
"$",
"url",
")",
"{",
"return",
"array_reduce",
"(",
"$",
"this",
"->",
"randomWaitUrls",
",",
"function",
"(",
"$",
"carry",
",",
"$",
"value",
")",
"use",
"(",
"$",
"url",
")",
"{",
"if",
"(",
"$",
"carr... | if we should randomly wait on current request
@param string $url the current url
@return boolean true if yes, false otherwise | [
"if",
"we",
"should",
"randomly",
"wait",
"on",
"current",
"request"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Listener/WriteLockListener.php#L184-L196 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Controller/ProxyController.php | ProxyController.proxyAction | public function proxyAction(Request $request)
{
$api = $this->decideApiAndEndpoint($request->getUri());
$this->registerProxySources($api['apiName']);
$this->apiLoader->addOptions($api);
$url = new Uri($this->apiLoader->getEndpoint($api['endpoint'], true));
if ($url->getScheme() === null) {
$url = $url->withScheme($request->getScheme());
}
$response = null;
try {
$newRequest = Request::create(
(string) $url,
$request->getMethod(),
[],
[],
[],
[],
$request->getContent(false)
);
$newRequest->headers->add($request->headers->all());
$newRequest->query->add($request->query->all());
$newRequest = $this->transformationHandler->transformRequest(
$api['apiName'],
$api['endpoint'],
$request,
$newRequest
);
$psrRequest = $this->psrHttpFactory->createRequest($newRequest);
$psrRequestUri = $psrRequest->getUri();
$psrRequestUriPort = $url->getPort();
if (is_numeric($psrRequestUriPort) || is_null($psrRequestUriPort)) {
$psrRequestUri = $psrRequestUri->withPort($psrRequestUriPort);
}
$psrRequest = $psrRequest->withUri($psrRequestUri);
$psrResponse = $this->proxy->forward($psrRequest)->to($this->getHostWithScheme($url));
$response = $this->httpFoundationFactory->createResponse($psrResponse);
$this->cleanResponseHeaders($response->headers);
$this->transformationHandler->transformResponse(
$api['apiName'],
$api['endpoint'],
$response,
clone $response
);
} catch (ClientException $e) {
$response = (new HttpFoundationFactory())->createResponse($e->getResponse());
} catch (ServerException $serverException) {
$response = (new HttpFoundationFactory())->createResponse($serverException->getResponse());
} catch (TransformationException $e) {
$message = json_encode(
['code' => 404, 'message' => 'HTTP 404 Not found']
);
throw new NotFoundHttpException($message, $e);
} catch (RequestException $e) {
$message = json_encode(
['code' => 404, 'message' => 'HTTP 404 Not found']
);
throw new NotFoundHttpException($message, $e);
}
return $response;
} | php | public function proxyAction(Request $request)
{
$api = $this->decideApiAndEndpoint($request->getUri());
$this->registerProxySources($api['apiName']);
$this->apiLoader->addOptions($api);
$url = new Uri($this->apiLoader->getEndpoint($api['endpoint'], true));
if ($url->getScheme() === null) {
$url = $url->withScheme($request->getScheme());
}
$response = null;
try {
$newRequest = Request::create(
(string) $url,
$request->getMethod(),
[],
[],
[],
[],
$request->getContent(false)
);
$newRequest->headers->add($request->headers->all());
$newRequest->query->add($request->query->all());
$newRequest = $this->transformationHandler->transformRequest(
$api['apiName'],
$api['endpoint'],
$request,
$newRequest
);
$psrRequest = $this->psrHttpFactory->createRequest($newRequest);
$psrRequestUri = $psrRequest->getUri();
$psrRequestUriPort = $url->getPort();
if (is_numeric($psrRequestUriPort) || is_null($psrRequestUriPort)) {
$psrRequestUri = $psrRequestUri->withPort($psrRequestUriPort);
}
$psrRequest = $psrRequest->withUri($psrRequestUri);
$psrResponse = $this->proxy->forward($psrRequest)->to($this->getHostWithScheme($url));
$response = $this->httpFoundationFactory->createResponse($psrResponse);
$this->cleanResponseHeaders($response->headers);
$this->transformationHandler->transformResponse(
$api['apiName'],
$api['endpoint'],
$response,
clone $response
);
} catch (ClientException $e) {
$response = (new HttpFoundationFactory())->createResponse($e->getResponse());
} catch (ServerException $serverException) {
$response = (new HttpFoundationFactory())->createResponse($serverException->getResponse());
} catch (TransformationException $e) {
$message = json_encode(
['code' => 404, 'message' => 'HTTP 404 Not found']
);
throw new NotFoundHttpException($message, $e);
} catch (RequestException $e) {
$message = json_encode(
['code' => 404, 'message' => 'HTTP 404 Not found']
);
throw new NotFoundHttpException($message, $e);
}
return $response;
} | [
"public",
"function",
"proxyAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"api",
"=",
"$",
"this",
"->",
"decideApiAndEndpoint",
"(",
"$",
"request",
"->",
"getUri",
"(",
")",
")",
";",
"$",
"this",
"->",
"registerProxySources",
"(",
"$",
"api"... | action for routing all requests directly to the third party API
@param Request $request request
@return \Psr\Http\Message\ResponseInterface|Response | [
"action",
"for",
"routing",
"all",
"requests",
"directly",
"to",
"the",
"third",
"party",
"API"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Controller/ProxyController.php#L107-L178 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Controller/ProxyController.php | ProxyController.cleanResponseHeaders | protected function cleanResponseHeaders(HeaderBag $headers)
{
$headers->remove('transfer-encoding'); // Chunked responses get not automatically re-chunked by graviton
$headers->remove('trailer'); // Only for chunked responses, graviton should re-set this when chunking
// Change naming to Graviton output Allow options
if ($allow = $headers->get('Allow', false)) {
$headers->set('Access-Control-Allow-Methods', $allow);
$headers->remove('Allow');
}
} | php | protected function cleanResponseHeaders(HeaderBag $headers)
{
$headers->remove('transfer-encoding'); // Chunked responses get not automatically re-chunked by graviton
$headers->remove('trailer'); // Only for chunked responses, graviton should re-set this when chunking
// Change naming to Graviton output Allow options
if ($allow = $headers->get('Allow', false)) {
$headers->set('Access-Control-Allow-Methods', $allow);
$headers->remove('Allow');
}
} | [
"protected",
"function",
"cleanResponseHeaders",
"(",
"HeaderBag",
"$",
"headers",
")",
"{",
"$",
"headers",
"->",
"remove",
"(",
"'transfer-encoding'",
")",
";",
"// Chunked responses get not automatically re-chunked by graviton",
"$",
"headers",
"->",
"remove",
"(",
"... | Removes some headers from the thirdparty API's response. These headers get always invalid by graviton's
forwarding and should therefore not be delivered to the client.
@param HeaderBag $headers The headerbag holding the thirdparty API's response headers
@return void | [
"Removes",
"some",
"headers",
"from",
"the",
"thirdparty",
"API",
"s",
"response",
".",
"These",
"headers",
"get",
"always",
"invalid",
"by",
"graviton",
"s",
"forwarding",
"and",
"should",
"therefore",
"not",
"be",
"delivered",
"to",
"the",
"client",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Controller/ProxyController.php#L188-L198 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Controller/ProxyController.php | ProxyController.schemaAction | public function schemaAction(Request $request)
{
$api = $this->decideApiAndEndpoint($request->getUri());
$this->registerProxySources($api['apiName']);
$this->apiLoader->addOptions($api);
$schema = $this->apiLoader->getEndpointSchema(urldecode($api['endpoint']));
$schema = $this->transformationHandler->transformSchema(
$api['apiName'],
$api['endpoint'],
$schema,
clone $schema
);
$response = new Response(json_encode($schema), 200);
$response->headers->set('Content-Type', 'application/json');
return $this->templating->renderResponse(
'GravitonCoreBundle:Main:index.json.twig',
array ('response' => $response->getContent()),
$response
);
} | php | public function schemaAction(Request $request)
{
$api = $this->decideApiAndEndpoint($request->getUri());
$this->registerProxySources($api['apiName']);
$this->apiLoader->addOptions($api);
$schema = $this->apiLoader->getEndpointSchema(urldecode($api['endpoint']));
$schema = $this->transformationHandler->transformSchema(
$api['apiName'],
$api['endpoint'],
$schema,
clone $schema
);
$response = new Response(json_encode($schema), 200);
$response->headers->set('Content-Type', 'application/json');
return $this->templating->renderResponse(
'GravitonCoreBundle:Main:index.json.twig',
array ('response' => $response->getContent()),
$response
);
} | [
"public",
"function",
"schemaAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"api",
"=",
"$",
"this",
"->",
"decideApiAndEndpoint",
"(",
"$",
"request",
"->",
"getUri",
"(",
")",
")",
";",
"$",
"this",
"->",
"registerProxySources",
"(",
"$",
"api... | get schema info
@param Request $request request
@return Response | [
"get",
"schema",
"info"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Controller/ProxyController.php#L207-L228 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Controller/ProxyController.php | ProxyController.registerProxySources | private function registerProxySources($apiPrefix = '')
{
foreach (array_keys($this->proxySourceConfiguration) as $source) {
foreach ($this->proxySourceConfiguration[$source] as $config) {
if ($apiPrefix == $config['prefix']) {
$this->apiLoader->setOption($config);
return;
}
}
}
$e = new NotFoundException('No such thirdparty API.');
$e->setResponse(Response::create());
throw $e;
} | php | private function registerProxySources($apiPrefix = '')
{
foreach (array_keys($this->proxySourceConfiguration) as $source) {
foreach ($this->proxySourceConfiguration[$source] as $config) {
if ($apiPrefix == $config['prefix']) {
$this->apiLoader->setOption($config);
return;
}
}
}
$e = new NotFoundException('No such thirdparty API.');
$e->setResponse(Response::create());
throw $e;
} | [
"private",
"function",
"registerProxySources",
"(",
"$",
"apiPrefix",
"=",
"''",
")",
"{",
"foreach",
"(",
"array_keys",
"(",
"$",
"this",
"->",
"proxySourceConfiguration",
")",
"as",
"$",
"source",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"proxySourceCo... | Registers configured external services to be proxied.
@param string $apiPrefix The prefix of the API
@return void | [
"Registers",
"configured",
"external",
"services",
"to",
"be",
"proxied",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Controller/ProxyController.php#L265-L279 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Controller/ProxyController.php | ProxyController.getHostWithScheme | private function getHostWithScheme(UriInterface $url)
{
$target = new Uri();
$target = $target
->withScheme($url->getScheme())
->withHost($url->getHost())
->withPort($url->getPort());
return (string) $target;
} | php | private function getHostWithScheme(UriInterface $url)
{
$target = new Uri();
$target = $target
->withScheme($url->getScheme())
->withHost($url->getHost())
->withPort($url->getPort());
return (string) $target;
} | [
"private",
"function",
"getHostWithScheme",
"(",
"UriInterface",
"$",
"url",
")",
"{",
"$",
"target",
"=",
"new",
"Uri",
"(",
")",
";",
"$",
"target",
"=",
"$",
"target",
"->",
"withScheme",
"(",
"$",
"url",
"->",
"getScheme",
"(",
")",
")",
"->",
"w... | get host, scheme and port
@param string $url the url
@return string | [
"get",
"host",
"scheme",
"and",
"port"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Controller/ProxyController.php#L288-L297 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Definition/Loader/Loader.php | Loader.load | public function load($input)
{
foreach ($this->strategies as $strategy) {
if ($strategy->supports($input)) {
return array_map([$this, 'createJsonDefinition'], $strategy->load($input));
}
}
return [];
} | php | public function load($input)
{
foreach ($this->strategies as $strategy) {
if ($strategy->supports($input)) {
return array_map([$this, 'createJsonDefinition'], $strategy->load($input));
}
}
return [];
} | [
"public",
"function",
"load",
"(",
"$",
"input",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"strategies",
"as",
"$",
"strategy",
")",
"{",
"if",
"(",
"$",
"strategy",
"->",
"supports",
"(",
"$",
"input",
")",
")",
"{",
"return",
"array_map",
"(",
... | load from input
@param string|null $input input from command
@return JsonDefinition[] | [
"load",
"from",
"input"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/Loader/Loader.php#L72-L81 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Definition/Loader/Loader.php | Loader.createJsonDefinition | protected function createJsonDefinition($json)
{
$errors = $this->validator->validateJsonDefinition($json);
if (!empty($errors)) {
throw new ValidationException($errors);
}
$definition = $this->serializer->deserialize(
$json,
'Graviton\\GeneratorBundle\\Definition\\Schema\\Definition',
'json'
);
return new JsonDefinition($definition);
} | php | protected function createJsonDefinition($json)
{
$errors = $this->validator->validateJsonDefinition($json);
if (!empty($errors)) {
throw new ValidationException($errors);
}
$definition = $this->serializer->deserialize(
$json,
'Graviton\\GeneratorBundle\\Definition\\Schema\\Definition',
'json'
);
return new JsonDefinition($definition);
} | [
"protected",
"function",
"createJsonDefinition",
"(",
"$",
"json",
")",
"{",
"$",
"errors",
"=",
"$",
"this",
"->",
"validator",
"->",
"validateJsonDefinition",
"(",
"$",
"json",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"errors",
")",
")",
"{",
"th... | Deserialize JSON definition
@param string $json JSON code
@return JsonDefinition
@throws InvalidJsonException If JSON is invalid
@throws ValidationException If definition is not valid | [
"Deserialize",
"JSON",
"definition"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/Loader/Loader.php#L91-L105 | train |
libgraviton/graviton | src/Graviton/I18nBundle/Translator/Translator.php | Translator.translate | public function translate($original)
{
$cached = $this->getFromCache($original);
if (is_array($cached)) {
return $cached;
}
$translations = $this->translationCollection->find(['original' => $original])->toArray();
$baseArray = [];
foreach ($translations as $item) {
$baseArray[$item['language']] = $item['localized'];
}
$translation = [];
foreach ($this->getLanguages() as $language) {
if (isset($baseArray[$language])) {
$translation[$language] = $baseArray[$language];
} else {
$translation[$language] = $original;
}
}
// ensure existence of default language
$translation[$this->defaultLanguage] = $original;
$this->saveToCache($original, $translation);
return $translation;
} | php | public function translate($original)
{
$cached = $this->getFromCache($original);
if (is_array($cached)) {
return $cached;
}
$translations = $this->translationCollection->find(['original' => $original])->toArray();
$baseArray = [];
foreach ($translations as $item) {
$baseArray[$item['language']] = $item['localized'];
}
$translation = [];
foreach ($this->getLanguages() as $language) {
if (isset($baseArray[$language])) {
$translation[$language] = $baseArray[$language];
} else {
$translation[$language] = $original;
}
}
// ensure existence of default language
$translation[$this->defaultLanguage] = $original;
$this->saveToCache($original, $translation);
return $translation;
} | [
"public",
"function",
"translate",
"(",
"$",
"original",
")",
"{",
"$",
"cached",
"=",
"$",
"this",
"->",
"getFromCache",
"(",
"$",
"original",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"cached",
")",
")",
"{",
"return",
"$",
"cached",
";",
"}",
"... | translate a string, returning an array with translations
@param string $original original string
@return array translation array | [
"translate",
"a",
"string",
"returning",
"an",
"array",
"with",
"translations"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Translator/Translator.php#L79-L108 | train |
libgraviton/graviton | src/Graviton/I18nBundle/Translator/Translator.php | Translator.persistTranslatable | public function persistTranslatable(Translatable $translatable)
{
$translations = $translatable->getTranslations();
if (!isset($translations[$this->defaultLanguage])) {
throw new \LogicException('Not possible to persist a Translatable without default language!');
}
$original = $translations[$this->defaultLanguage];
unset($translations[$this->defaultLanguage]);
foreach ($translations as $language => $translation) {
$this->translationCollection->upsert(
[
'original' => $original,
'language' => $language
],
[
'original' => $original,
'language' => $language,
'localized' => $translation
]
);
}
$this->removeFromCache($original);
} | php | public function persistTranslatable(Translatable $translatable)
{
$translations = $translatable->getTranslations();
if (!isset($translations[$this->defaultLanguage])) {
throw new \LogicException('Not possible to persist a Translatable without default language!');
}
$original = $translations[$this->defaultLanguage];
unset($translations[$this->defaultLanguage]);
foreach ($translations as $language => $translation) {
$this->translationCollection->upsert(
[
'original' => $original,
'language' => $language
],
[
'original' => $original,
'language' => $language,
'localized' => $translation
]
);
}
$this->removeFromCache($original);
} | [
"public",
"function",
"persistTranslatable",
"(",
"Translatable",
"$",
"translatable",
")",
"{",
"$",
"translations",
"=",
"$",
"translatable",
"->",
"getTranslations",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"translations",
"[",
"$",
"this",
"->",... | persists a translatable to database
@param Translatable $translatable the translatable
@return void | [
"persists",
"a",
"translatable",
"to",
"database"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Translator/Translator.php#L127-L152 | train |
libgraviton/graviton | src/Graviton/I18nBundle/Translator/Translator.php | Translator.getLanguages | public function getLanguages()
{
if (!empty($this->languages)) {
return $this->languages;
}
$this->languages = array_map(
function ($record) {
return $record['_id'];
},
$this->languageCollection->find([], ['_id' => 1])->toArray()
);
asort($this->languages);
$this->languages = array_values($this->languages);
return $this->languages;
} | php | public function getLanguages()
{
if (!empty($this->languages)) {
return $this->languages;
}
$this->languages = array_map(
function ($record) {
return $record['_id'];
},
$this->languageCollection->find([], ['_id' => 1])->toArray()
);
asort($this->languages);
$this->languages = array_values($this->languages);
return $this->languages;
} | [
"public",
"function",
"getLanguages",
"(",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"languages",
")",
")",
"{",
"return",
"$",
"this",
"->",
"languages",
";",
"}",
"$",
"this",
"->",
"languages",
"=",
"array_map",
"(",
"function",
"... | returns all available languages
@return array languages | [
"returns",
"all",
"available",
"languages"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Translator/Translator.php#L159-L177 | train |
libgraviton/graviton | src/Graviton/I18nBundle/Translator/Translator.php | Translator.getFromCache | private function getFromCache($original)
{
$cacheContent = $this->cache->fetch($this->getCacheKey($original));
if (is_array($cacheContent) && isset($cacheContent[$original])) {
return $cacheContent[$original];
}
return null;
} | php | private function getFromCache($original)
{
$cacheContent = $this->cache->fetch($this->getCacheKey($original));
if (is_array($cacheContent) && isset($cacheContent[$original])) {
return $cacheContent[$original];
}
return null;
} | [
"private",
"function",
"getFromCache",
"(",
"$",
"original",
")",
"{",
"$",
"cacheContent",
"=",
"$",
"this",
"->",
"cache",
"->",
"fetch",
"(",
"$",
"this",
"->",
"getCacheKey",
"(",
"$",
"original",
")",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"... | gets entry from cache
@param string $original original string
@return array|null entry | [
"gets",
"entry",
"from",
"cache"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Translator/Translator.php#L186-L194 | train |
libgraviton/graviton | src/Graviton/I18nBundle/Translator/Translator.php | Translator.saveToCache | private function saveToCache($original, $translations)
{
$cacheKey = $this->getCacheKey($original);
$cacheContent = $this->cache->fetch($cacheKey);
if (is_array($cacheContent)) {
$cacheContent[$original] = $translations;
} else {
$cacheContent = [$original => $translations];
}
$this->cache->save($cacheKey, $cacheContent);
} | php | private function saveToCache($original, $translations)
{
$cacheKey = $this->getCacheKey($original);
$cacheContent = $this->cache->fetch($cacheKey);
if (is_array($cacheContent)) {
$cacheContent[$original] = $translations;
} else {
$cacheContent = [$original => $translations];
}
$this->cache->save($cacheKey, $cacheContent);
} | [
"private",
"function",
"saveToCache",
"(",
"$",
"original",
",",
"$",
"translations",
")",
"{",
"$",
"cacheKey",
"=",
"$",
"this",
"->",
"getCacheKey",
"(",
"$",
"original",
")",
";",
"$",
"cacheContent",
"=",
"$",
"this",
"->",
"cache",
"->",
"fetch",
... | saves entry to cache
@param string $original original string
@param array $translations translations
@return void | [
"saves",
"entry",
"to",
"cache"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Translator/Translator.php#L204-L215 | train |
libgraviton/graviton | src/Graviton/I18nBundle/Translator/Translator.php | Translator.removeFromCache | private function removeFromCache($original)
{
$cacheKey = $this->getCacheKey($original);
$cacheContent = $this->cache->fetch($this->getCacheKey($original));
if (is_array($cacheContent) && isset($cacheContent[$original])) {
unset($cacheContent[$original]);
$this->cache->save($cacheKey, $cacheContent);
}
} | php | private function removeFromCache($original)
{
$cacheKey = $this->getCacheKey($original);
$cacheContent = $this->cache->fetch($this->getCacheKey($original));
if (is_array($cacheContent) && isset($cacheContent[$original])) {
unset($cacheContent[$original]);
$this->cache->save($cacheKey, $cacheContent);
}
} | [
"private",
"function",
"removeFromCache",
"(",
"$",
"original",
")",
"{",
"$",
"cacheKey",
"=",
"$",
"this",
"->",
"getCacheKey",
"(",
"$",
"original",
")",
";",
"$",
"cacheContent",
"=",
"$",
"this",
"->",
"cache",
"->",
"fetch",
"(",
"$",
"this",
"->... | removes entry from cache
@param string $original original string
@return void | [
"removes",
"entry",
"from",
"cache"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Translator/Translator.php#L224-L232 | train |
libgraviton/graviton | src/Graviton/I18nBundle/Translator/Translator.php | Translator.getCacheKey | private function getCacheKey($original)
{
return sprintf(
'translator_%s_%s',
implode('.', $this->getLanguages()),
str_pad(strtolower(substr($original, 0, $this->cacheNameDepth)), $this->cacheNameDepth, '.')
);
} | php | private function getCacheKey($original)
{
return sprintf(
'translator_%s_%s',
implode('.', $this->getLanguages()),
str_pad(strtolower(substr($original, 0, $this->cacheNameDepth)), $this->cacheNameDepth, '.')
);
} | [
"private",
"function",
"getCacheKey",
"(",
"$",
"original",
")",
"{",
"return",
"sprintf",
"(",
"'translator_%s_%s'",
",",
"implode",
"(",
"'.'",
",",
"$",
"this",
"->",
"getLanguages",
"(",
")",
")",
",",
"str_pad",
"(",
"strtolower",
"(",
"substr",
"(",
... | returns the caching key
@param string $original original string
@return string cache key | [
"returns",
"the",
"caching",
"key"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Translator/Translator.php#L241-L248 | train |
libgraviton/graviton | src/Graviton/RestBundle/HttpFoundation/LinkHeaderItem.php | LinkHeaderItem.fromString | public static function fromString($itemValue)
{
$bits = preg_split('/(".+?"|[^;]+)(?:;|$)/', $itemValue, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$value = array_shift($bits);
$attributes = [];
foreach ($bits as $bit) {
list($bitName, $bitValue) = explode('=', trim($bit));
$bitValue = self::trimEdge($bitValue, '"');
$bitValue = self::trimEdge($bitValue, '\'');
$attributes[$bitName] = $bitValue;
}
$url = self::trimEdge($value, '<');
return new self($url, $attributes);
} | php | public static function fromString($itemValue)
{
$bits = preg_split('/(".+?"|[^;]+)(?:;|$)/', $itemValue, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$value = array_shift($bits);
$attributes = [];
foreach ($bits as $bit) {
list($bitName, $bitValue) = explode('=', trim($bit));
$bitValue = self::trimEdge($bitValue, '"');
$bitValue = self::trimEdge($bitValue, '\'');
$attributes[$bitName] = $bitValue;
}
$url = self::trimEdge($value, '<');
return new self($url, $attributes);
} | [
"public",
"static",
"function",
"fromString",
"(",
"$",
"itemValue",
")",
"{",
"$",
"bits",
"=",
"preg_split",
"(",
"'/(\".+?\"|[^;]+)(?:;|$)/'",
",",
"$",
"itemValue",
",",
"0",
",",
"PREG_SPLIT_NO_EMPTY",
"|",
"PREG_SPLIT_DELIM_CAPTURE",
")",
";",
"$",
"value"... | Builds a LinkHeaderItem instance from a string.
@param string $itemValue value of a single link header
@return \Graviton\RestBundle\HttpFoundation\LinkHeaderItem | [
"Builds",
"a",
"LinkHeaderItem",
"instance",
"from",
"a",
"string",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/HttpFoundation/LinkHeaderItem.php#L51-L69 | train |
libgraviton/graviton | src/Graviton/RestBundle/HttpFoundation/LinkHeaderItem.php | LinkHeaderItem.trimEdge | private static function trimEdge($string, $char)
{
if (substr($string, 0, 1) == $char) {
$string = substr($string, 1, -1);
}
return $string;
} | php | private static function trimEdge($string, $char)
{
if (substr($string, 0, 1) == $char) {
$string = substr($string, 1, -1);
}
return $string;
} | [
"private",
"static",
"function",
"trimEdge",
"(",
"$",
"string",
",",
"$",
"char",
")",
"{",
"if",
"(",
"substr",
"(",
"$",
"string",
",",
"0",
",",
"1",
")",
"==",
"$",
"char",
")",
"{",
"$",
"string",
"=",
"substr",
"(",
"$",
"string",
",",
"... | trim edge of string if char maches
@param string $string string
@param string $char char
@return string | [
"trim",
"edge",
"of",
"string",
"if",
"char",
"maches"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/HttpFoundation/LinkHeaderItem.php#L158-L165 | train |
libgraviton/graviton | src/Graviton/SecurityBundle/Authentication/Provider/AuthenticationProviderDummy.php | AuthenticationProviderDummy.loadUserByUsername | public function loadUserByUsername($username)
{
if ($username !== 'testUsername') {
return false;
}
/** @var UserInterface $user */
$user = new \stdClass();
$user->id = 123;
$user->username = $username;
$user->firstName = 'aName';
$user->lastName = 'aSurname';
return $user;
} | php | public function loadUserByUsername($username)
{
if ($username !== 'testUsername') {
return false;
}
/** @var UserInterface $user */
$user = new \stdClass();
$user->id = 123;
$user->username = $username;
$user->firstName = 'aName';
$user->lastName = 'aSurname';
return $user;
} | [
"public",
"function",
"loadUserByUsername",
"(",
"$",
"username",
")",
"{",
"if",
"(",
"$",
"username",
"!==",
"'testUsername'",
")",
"{",
"return",
"false",
";",
"}",
"/** @var UserInterface $user */",
"$",
"user",
"=",
"new",
"\\",
"stdClass",
"(",
")",
";... | Dummy loader for test case
This method must throw UsernameNotFoundException if the user is not
found.
@param string $username the consultants username
@return false|UserInterface | [
"Dummy",
"loader",
"for",
"test",
"case"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SecurityBundle/Authentication/Provider/AuthenticationProviderDummy.php#L36-L50 | train |
libgraviton/graviton | src/Graviton/RestBundle/Service/QueryService.php | QueryService.hasSearchIndex | private function hasSearchIndex()
{
$metadata = $this->repository->getClassMetadata();
$indexes = $metadata->getIndexes();
if (empty($indexes)) {
return false;
}
$text = array_filter(
$indexes,
function ($index) {
if (isset($index['keys'])) {
$hasText = false;
foreach ($index['keys'] as $name => $direction) {
if ($direction == 'text') {
$hasText = true;
}
}
return $hasText;
}
}
);
return !empty($text);
} | php | private function hasSearchIndex()
{
$metadata = $this->repository->getClassMetadata();
$indexes = $metadata->getIndexes();
if (empty($indexes)) {
return false;
}
$text = array_filter(
$indexes,
function ($index) {
if (isset($index['keys'])) {
$hasText = false;
foreach ($index['keys'] as $name => $direction) {
if ($direction == 'text') {
$hasText = true;
}
}
return $hasText;
}
}
);
return !empty($text);
} | [
"private",
"function",
"hasSearchIndex",
"(",
")",
"{",
"$",
"metadata",
"=",
"$",
"this",
"->",
"repository",
"->",
"getClassMetadata",
"(",
")",
";",
"$",
"indexes",
"=",
"$",
"metadata",
"->",
"getIndexes",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$... | Check if collection has search indexes in DB
@return bool | [
"Check",
"if",
"collection",
"has",
"search",
"indexes",
"in",
"DB"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Service/QueryService.php#L246-L270 | train |
libgraviton/graviton | src/Graviton/RestBundle/Service/QueryService.php | QueryService.getPaginationPageSize | private function getPaginationPageSize()
{
$limitNode = $this->getPaginationLimitNode();
if ($limitNode) {
$limit = $limitNode->getLimit();
if ($limit < 1) {
throw new SyntaxErrorException('invalid limit in rql');
}
return $limit;
}
return $this->paginationDefaultLimit;
} | php | private function getPaginationPageSize()
{
$limitNode = $this->getPaginationLimitNode();
if ($limitNode) {
$limit = $limitNode->getLimit();
if ($limit < 1) {
throw new SyntaxErrorException('invalid limit in rql');
}
return $limit;
}
return $this->paginationDefaultLimit;
} | [
"private",
"function",
"getPaginationPageSize",
"(",
")",
"{",
"$",
"limitNode",
"=",
"$",
"this",
"->",
"getPaginationLimitNode",
"(",
")",
";",
"if",
"(",
"$",
"limitNode",
")",
"{",
"$",
"limit",
"=",
"$",
"limitNode",
"->",
"getLimit",
"(",
")",
";",... | get the pagination page size
@return int page size | [
"get",
"the",
"pagination",
"page",
"size"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Service/QueryService.php#L277-L292 | train |
libgraviton/graviton | src/Graviton/RestBundle/Service/QueryService.php | QueryService.getPaginationLimitNode | private function getPaginationLimitNode()
{
/** @var Query $rqlQuery */
$rqlQuery = $this->request->attributes->get('rqlQuery');
if ($rqlQuery instanceof Query && $rqlQuery->getLimit() instanceof LimitNode) {
return $rqlQuery->getLimit();
}
return false;
} | php | private function getPaginationLimitNode()
{
/** @var Query $rqlQuery */
$rqlQuery = $this->request->attributes->get('rqlQuery');
if ($rqlQuery instanceof Query && $rqlQuery->getLimit() instanceof LimitNode) {
return $rqlQuery->getLimit();
}
return false;
} | [
"private",
"function",
"getPaginationLimitNode",
"(",
")",
"{",
"/** @var Query $rqlQuery */",
"$",
"rqlQuery",
"=",
"$",
"this",
"->",
"request",
"->",
"attributes",
"->",
"get",
"(",
"'rqlQuery'",
")",
";",
"if",
"(",
"$",
"rqlQuery",
"instanceof",
"Query",
... | gets the limit node
@return bool|LimitNode the node or false | [
"gets",
"the",
"limit",
"node"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Service/QueryService.php#L315-L325 | train |
libgraviton/graviton | src/Graviton/FileBundle/Manager/FileManager.php | FileManager.buildGetContentResponse | public function buildGetContentResponse(Response $response, FileDocument $file)
{
/** @var FileMetadataBase $metadata */
$metadata = $file->getMetadata();
if (!$metadata) {
throw new InvalidArgumentException('Loaded file have no valid metadata');
}
// We use file's mimeType, just in case none we use DB's.
$mimeType = null;
if ($this->readFileSystemMimeType) {
$mimeType = $this->fileSystem->getMimetype($file->getId());
}
if (!$mimeType) {
$mimeType = $metadata->getMime();
}
if ($this->allowedMimeTypes && !in_array($mimeType, $this->allowedMimeTypes)) {
throw new InvalidArgumentException('File mime type: '.$mimeType.' is not allowed as response.');
}
// Create Response
$disposition = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_INLINE,
$metadata->getFilename()
);
$response
->setStatusCode(Response::HTTP_OK)
->setContent($this->fileSystem->read($file->getId()));
$response
->headers->set('Content-Type', $mimeType);
$response
->headers->set('Content-Disposition', $disposition);
return $response;
} | php | public function buildGetContentResponse(Response $response, FileDocument $file)
{
/** @var FileMetadataBase $metadata */
$metadata = $file->getMetadata();
if (!$metadata) {
throw new InvalidArgumentException('Loaded file have no valid metadata');
}
// We use file's mimeType, just in case none we use DB's.
$mimeType = null;
if ($this->readFileSystemMimeType) {
$mimeType = $this->fileSystem->getMimetype($file->getId());
}
if (!$mimeType) {
$mimeType = $metadata->getMime();
}
if ($this->allowedMimeTypes && !in_array($mimeType, $this->allowedMimeTypes)) {
throw new InvalidArgumentException('File mime type: '.$mimeType.' is not allowed as response.');
}
// Create Response
$disposition = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_INLINE,
$metadata->getFilename()
);
$response
->setStatusCode(Response::HTTP_OK)
->setContent($this->fileSystem->read($file->getId()));
$response
->headers->set('Content-Type', $mimeType);
$response
->headers->set('Content-Disposition', $disposition);
return $response;
} | [
"public",
"function",
"buildGetContentResponse",
"(",
"Response",
"$",
"response",
",",
"FileDocument",
"$",
"file",
")",
"{",
"/** @var FileMetadataBase $metadata */",
"$",
"metadata",
"=",
"$",
"file",
"->",
"getMetadata",
"(",
")",
";",
"if",
"(",
"!",
"$",
... | Will update the response object with provided file data
@param Response $response response
@param DocumentFile $file File document object from DB
@return Response
@throws InvalidArgumentException if invalid info fetched from fileSystem | [
"Will",
"update",
"the",
"response",
"object",
"with",
"provided",
"file",
"data"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/FileBundle/Manager/FileManager.php#L100-L135 | train |
libgraviton/graviton | src/Graviton/FileBundle/Manager/FileManager.php | FileManager.saveFile | public function saveFile($id, $filepath)
{
// will save using a stream
$fp = fopen($filepath, 'r+');
$this->fileSystem->putStream($id, $fp);
// close file
fclose($fp);
} | php | public function saveFile($id, $filepath)
{
// will save using a stream
$fp = fopen($filepath, 'r+');
$this->fileSystem->putStream($id, $fp);
// close file
fclose($fp);
} | [
"public",
"function",
"saveFile",
"(",
"$",
"id",
",",
"$",
"filepath",
")",
"{",
"// will save using a stream",
"$",
"fp",
"=",
"fopen",
"(",
"$",
"filepath",
",",
"'r+'",
")",
";",
"$",
"this",
"->",
"fileSystem",
"->",
"putStream",
"(",
"$",
"id",
"... | Save or update a file
@param string $id ID of file
@param String $filepath path to the file to save
@return void | [
"Save",
"or",
"update",
"a",
"file"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/FileBundle/Manager/FileManager.php#L146-L155 | train |
libgraviton/graviton | src/Graviton/FileBundle/Manager/FileManager.php | FileManager.buildFileDocument | private function buildFileDocument(FileDocument $document, $file, $original)
{
$now = new \DateTime();
// If only a file is posted, check if there is a original object and clone it
if ($file && $original && !$document->getMetadata()) {
$document = clone $original;
}
// Basic Metadata update
$metadata = $document->getMetadata() ?: new FileMetadataEmbedded();
// File related, if no file uploaded we keep original file info.
if ($file) {
$hash = $metadata->getHash();
if (!$hash || strlen($hash)>64) {
$hash = hash('sha256', file_get_contents($file->getRealPath()));
} else {
$hash = preg_replace('/[^a-z0-9_-]/i', '-', $hash);
}
$metadata->setHash($hash);
$metadata->setMime($file->getMimeType());
$metadata->setSize($file->getSize());
if (!$metadata->getFilename()) {
$fileName = $file->getClientOriginalName() ? $file->getClientOriginalName() : $file->getFilename();
$fileName = preg_replace("/[^a-zA-Z0-9.]/", "-", $fileName);
$metadata->setFilename($fileName);
}
} elseif ($original && ($originalMetadata = $original->getMetadata())) {
if (!$metadata->getFilename()) {
$metadata->setFilename($originalMetadata->getFilename());
}
$metadata->setHash($originalMetadata->getHash());
$metadata->setMime($originalMetadata->getMime());
$metadata->setSize($originalMetadata->getSize());
}
// Creation date. keep original if available
if ($original && $original->getMetadata() && $original->getMetadata()->getCreatedate()) {
$metadata->setCreatedate($original->getMetadata()->getCreatedate());
} else {
$metadata->setCreatedate($now);
}
$metadata->setModificationdate($now);
$document->setMetadata($metadata);
return $document;
} | php | private function buildFileDocument(FileDocument $document, $file, $original)
{
$now = new \DateTime();
// If only a file is posted, check if there is a original object and clone it
if ($file && $original && !$document->getMetadata()) {
$document = clone $original;
}
// Basic Metadata update
$metadata = $document->getMetadata() ?: new FileMetadataEmbedded();
// File related, if no file uploaded we keep original file info.
if ($file) {
$hash = $metadata->getHash();
if (!$hash || strlen($hash)>64) {
$hash = hash('sha256', file_get_contents($file->getRealPath()));
} else {
$hash = preg_replace('/[^a-z0-9_-]/i', '-', $hash);
}
$metadata->setHash($hash);
$metadata->setMime($file->getMimeType());
$metadata->setSize($file->getSize());
if (!$metadata->getFilename()) {
$fileName = $file->getClientOriginalName() ? $file->getClientOriginalName() : $file->getFilename();
$fileName = preg_replace("/[^a-zA-Z0-9.]/", "-", $fileName);
$metadata->setFilename($fileName);
}
} elseif ($original && ($originalMetadata = $original->getMetadata())) {
if (!$metadata->getFilename()) {
$metadata->setFilename($originalMetadata->getFilename());
}
$metadata->setHash($originalMetadata->getHash());
$metadata->setMime($originalMetadata->getMime());
$metadata->setSize($originalMetadata->getSize());
}
// Creation date. keep original if available
if ($original && $original->getMetadata() && $original->getMetadata()->getCreatedate()) {
$metadata->setCreatedate($original->getMetadata()->getCreatedate());
} else {
$metadata->setCreatedate($now);
}
$metadata->setModificationdate($now);
$document->setMetadata($metadata);
return $document;
} | [
"private",
"function",
"buildFileDocument",
"(",
"FileDocument",
"$",
"document",
",",
"$",
"file",
",",
"$",
"original",
")",
"{",
"$",
"now",
"=",
"new",
"\\",
"DateTime",
"(",
")",
";",
"// If only a file is posted, check if there is a original object and clone it"... | Create the basic needs for a file
@param DocumentFile $document Post or Put file document
@param UploadedFile $file To be used in set metadata
@param DocumentFile $original If there is a original document
@return DocumentFile
@throws InvalidArgumentException | [
"Create",
"the",
"basic",
"needs",
"for",
"a",
"file"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/FileBundle/Manager/FileManager.php#L237-L285 | train |
libgraviton/graviton | src/Graviton/FileBundle/Manager/FileManager.php | FileManager.remove | public function remove($id)
{
if ($this->fileSystem->has($id)) {
$this->fileSystem->delete($id);
}
} | php | public function remove($id)
{
if ($this->fileSystem->has($id)) {
$this->fileSystem->delete($id);
}
} | [
"public",
"function",
"remove",
"(",
"$",
"id",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"fileSystem",
"->",
"has",
"(",
"$",
"id",
")",
")",
"{",
"$",
"this",
"->",
"fileSystem",
"->",
"delete",
"(",
"$",
"id",
")",
";",
"}",
"}"
] | Simple delete item from file system
@param string $id ID of file to be deleted
@return void | [
"Simple",
"delete",
"item",
"from",
"file",
"system"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/FileBundle/Manager/FileManager.php#L312-L317 | train |
libgraviton/graviton | src/Graviton/FileBundle/Manager/FileManager.php | FileManager.getUploadedFileFromRequest | private function getUploadedFileFromRequest(Request $request)
{
$file = false;
if ($request->files instanceof FileBag && $request->files->count() > 0) {
if ($request->files->count() > 1) {
throw new InvalidArgumentException('Only 1 file upload per requests allowed.');
}
$files = $request->files->all();
$file = reset($files);
if ($this->allowedMimeTypes && !in_array($file->getMimeType(), $this->allowedMimeTypes)) {
throw new InvalidArgumentException('File mime type: '.$file->getMimeType().' is not allowed.');
}
}
return $file;
} | php | private function getUploadedFileFromRequest(Request $request)
{
$file = false;
if ($request->files instanceof FileBag && $request->files->count() > 0) {
if ($request->files->count() > 1) {
throw new InvalidArgumentException('Only 1 file upload per requests allowed.');
}
$files = $request->files->all();
$file = reset($files);
if ($this->allowedMimeTypes && !in_array($file->getMimeType(), $this->allowedMimeTypes)) {
throw new InvalidArgumentException('File mime type: '.$file->getMimeType().' is not allowed.');
}
}
return $file;
} | [
"private",
"function",
"getUploadedFileFromRequest",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"file",
"=",
"false",
";",
"if",
"(",
"$",
"request",
"->",
"files",
"instanceof",
"FileBag",
"&&",
"$",
"request",
"->",
"files",
"->",
"count",
"(",
")",
... | Set global uploaded file.
Only ONE file allowed per upload.
@param Request $request service request
@return UploadedFile if file was uploaded
@throws InvalidArgumentException | [
"Set",
"global",
"uploaded",
"file",
".",
"Only",
"ONE",
"file",
"allowed",
"per",
"upload",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/FileBundle/Manager/FileManager.php#L327-L343 | train |
libgraviton/graviton | src/Graviton/RestBundle/Controller/RestController.php | RestController.getAction | public function getAction(Request $request, $id)
{
$document = $this->getModel()->getSerialised($id, $request);
$response = $this->getResponse()
->setStatusCode(Response::HTTP_OK)
->setContent($document);
return $response;
} | php | public function getAction(Request $request, $id)
{
$document = $this->getModel()->getSerialised($id, $request);
$response = $this->getResponse()
->setStatusCode(Response::HTTP_OK)
->setContent($document);
return $response;
} | [
"public",
"function",
"getAction",
"(",
"Request",
"$",
"request",
",",
"$",
"id",
")",
"{",
"$",
"document",
"=",
"$",
"this",
"->",
"getModel",
"(",
")",
"->",
"getSerialised",
"(",
"$",
"id",
",",
"$",
"request",
")",
";",
"$",
"response",
"=",
... | Returns a single record
@param Request $request Current http request
@param string $id ID of record
@return \Symfony\Component\HttpFoundation\Response $response Response with result or error | [
"Returns",
"a",
"single",
"record"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Controller/RestController.php#L131-L140 | train |
libgraviton/graviton | src/Graviton/RestBundle/Controller/RestController.php | RestController.allAction | public function allAction(Request $request)
{
$model = $this->getModel();
$content = $this->restUtils->serialize($model->findAll($request));
$response = $this->getResponse()
->setStatusCode(Response::HTTP_OK)
->setContent($content);
return $response;
} | php | public function allAction(Request $request)
{
$model = $this->getModel();
$content = $this->restUtils->serialize($model->findAll($request));
$response = $this->getResponse()
->setStatusCode(Response::HTTP_OK)
->setContent($content);
return $response;
} | [
"public",
"function",
"allAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"getModel",
"(",
")",
";",
"$",
"content",
"=",
"$",
"this",
"->",
"restUtils",
"->",
"serialize",
"(",
"$",
"model",
"->",
"findAll",
... | Returns all records
@param Request $request Current http request
@return \Symfony\Component\HttpFoundation\Response $response Response with result or error | [
"Returns",
"all",
"records"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Controller/RestController.php#L189-L200 | train |
libgraviton/graviton | src/Graviton/RestBundle/Controller/RestController.php | RestController.postAction | public function postAction(Request $request)
{
// Get the response object from container
$response = $this->getResponse();
$model = $this->getModel();
$this->restUtils->checkJsonRequest($request, $response, $this->getModel());
$record = $this->restUtils->validateRequest($request->getContent(), $model);
// Insert the new record
$record = $model->insertRecord($record);
// store id of new record so we dont need to reparse body later when needed
$request->attributes->set('id', $record->getId());
// Set status code
$response->setStatusCode(Response::HTTP_CREATED);
$response->headers->set(
'Location',
$this->getRouter()->generate($this->restUtils->getRouteName($request), array('id' => $record->getId()))
);
return $response;
} | php | public function postAction(Request $request)
{
// Get the response object from container
$response = $this->getResponse();
$model = $this->getModel();
$this->restUtils->checkJsonRequest($request, $response, $this->getModel());
$record = $this->restUtils->validateRequest($request->getContent(), $model);
// Insert the new record
$record = $model->insertRecord($record);
// store id of new record so we dont need to reparse body later when needed
$request->attributes->set('id', $record->getId());
// Set status code
$response->setStatusCode(Response::HTTP_CREATED);
$response->headers->set(
'Location',
$this->getRouter()->generate($this->restUtils->getRouteName($request), array('id' => $record->getId()))
);
return $response;
} | [
"public",
"function",
"postAction",
"(",
"Request",
"$",
"request",
")",
"{",
"// Get the response object from container",
"$",
"response",
"=",
"$",
"this",
"->",
"getResponse",
"(",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"getModel",
"(",
")",
";",... | Writes a new Entry to the database
@param Request $request Current http request
@return \Symfony\Component\HttpFoundation\Response $response Result of action with data (if successful) | [
"Writes",
"a",
"new",
"Entry",
"to",
"the",
"database"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Controller/RestController.php#L209-L234 | train |
libgraviton/graviton | src/Graviton/RestBundle/Controller/RestController.php | RestController.patchAction | public function patchAction($id, Request $request)
{
$response = $this->getResponse();
$model = $this->getModel();
// Validate received data. On failure release the lock.
try {
// Check JSON Patch request
$this->restUtils->checkJsonRequest($request, $response, $model);
$this->restUtils->checkJsonPatchRequest(json_decode($request->getContent(), 1));
// Find record && apply $ref converter
$jsonDocument = $model->getSerialised($id, null);
try {
// Check if valid
$this->jsonPatchValidator->validate($jsonDocument, $request->getContent());
// Apply JSON patches
$patch = new Patch($jsonDocument, $request->getContent());
$patchedDocument = $patch->apply();
} catch (\Exception $e) {
throw new InvalidJsonPatchException($e->getMessage());
}
} catch (\Exception $e) {
throw $e;
}
// if document hasn't changed, pass HTTP_NOT_MODIFIED and exit
if ($jsonDocument == $patchedDocument) {
$response->setStatusCode(Response::HTTP_NOT_MODIFIED);
return $response;
}
// Validate result object
$record = $this->restUtils->validateRequest($patchedDocument, $model);
// Update object
$this->getModel()->updateRecord($id, $record);
// Set status response code
$response->setStatusCode(Response::HTTP_OK);
$response->headers->set(
'Content-Location',
$this->getRouter()->generate($this->restUtils->getRouteName($request), array('id' => $record->getId()))
);
return $response;
} | php | public function patchAction($id, Request $request)
{
$response = $this->getResponse();
$model = $this->getModel();
// Validate received data. On failure release the lock.
try {
// Check JSON Patch request
$this->restUtils->checkJsonRequest($request, $response, $model);
$this->restUtils->checkJsonPatchRequest(json_decode($request->getContent(), 1));
// Find record && apply $ref converter
$jsonDocument = $model->getSerialised($id, null);
try {
// Check if valid
$this->jsonPatchValidator->validate($jsonDocument, $request->getContent());
// Apply JSON patches
$patch = new Patch($jsonDocument, $request->getContent());
$patchedDocument = $patch->apply();
} catch (\Exception $e) {
throw new InvalidJsonPatchException($e->getMessage());
}
} catch (\Exception $e) {
throw $e;
}
// if document hasn't changed, pass HTTP_NOT_MODIFIED and exit
if ($jsonDocument == $patchedDocument) {
$response->setStatusCode(Response::HTTP_NOT_MODIFIED);
return $response;
}
// Validate result object
$record = $this->restUtils->validateRequest($patchedDocument, $model);
// Update object
$this->getModel()->updateRecord($id, $record);
// Set status response code
$response->setStatusCode(Response::HTTP_OK);
$response->headers->set(
'Content-Location',
$this->getRouter()->generate($this->restUtils->getRouteName($request), array('id' => $record->getId()))
);
return $response;
} | [
"public",
"function",
"patchAction",
"(",
"$",
"id",
",",
"Request",
"$",
"request",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"getResponse",
"(",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"getModel",
"(",
")",
";",
"// Validate received... | Patch a record
@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"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Controller/RestController.php#L301-L348 | train |
libgraviton/graviton | src/Graviton/RestBundle/Controller/RestController.php | RestController.schemaAction | public function schemaAction(Request $request, $id = null)
{
$request->attributes->set('schemaRequest', true);
list($app, $module, , $modelName, $schemaType) = explode('.', $request->attributes->get('_route'));
$response = $this->response;
$response->setStatusCode(Response::HTTP_OK);
$response->setVary(['Origin', 'Accept-Encoding']);
$response->setPublic();
if (!$id && $schemaType != 'canonicalIdSchema') {
$schema = $this->schemaUtils->getCollectionSchema($modelName, $this->getModel());
} else {
$schema = $this->schemaUtils->getModelSchema($modelName, $this->getModel());
}
// enabled methods for CorsListener
$corsMethods = 'GET, POST, PUT, PATCH, DELETE, OPTIONS';
try {
$router = $this->getRouter();
// if post route is available we assume everything is readable
$router->generate(implode('.', array($app, $module, 'rest', $modelName, 'post')));
} catch (RouteNotFoundException $exception) {
// only allow read methods
$corsMethods = 'GET, OPTIONS';
}
$request->attributes->set('corsMethods', $corsMethods);
$response->setContent($this->restUtils->serialize($schema));
return $response;
} | php | public function schemaAction(Request $request, $id = null)
{
$request->attributes->set('schemaRequest', true);
list($app, $module, , $modelName, $schemaType) = explode('.', $request->attributes->get('_route'));
$response = $this->response;
$response->setStatusCode(Response::HTTP_OK);
$response->setVary(['Origin', 'Accept-Encoding']);
$response->setPublic();
if (!$id && $schemaType != 'canonicalIdSchema') {
$schema = $this->schemaUtils->getCollectionSchema($modelName, $this->getModel());
} else {
$schema = $this->schemaUtils->getModelSchema($modelName, $this->getModel());
}
// enabled methods for CorsListener
$corsMethods = 'GET, POST, PUT, PATCH, DELETE, OPTIONS';
try {
$router = $this->getRouter();
// if post route is available we assume everything is readable
$router->generate(implode('.', array($app, $module, 'rest', $modelName, 'post')));
} catch (RouteNotFoundException $exception) {
// only allow read methods
$corsMethods = 'GET, OPTIONS';
}
$request->attributes->set('corsMethods', $corsMethods);
$response->setContent($this->restUtils->serialize($schema));
return $response;
} | [
"public",
"function",
"schemaAction",
"(",
"Request",
"$",
"request",
",",
"$",
"id",
"=",
"null",
")",
"{",
"$",
"request",
"->",
"attributes",
"->",
"set",
"(",
"'schemaRequest'",
",",
"true",
")",
";",
"list",
"(",
"$",
"app",
",",
"$",
"module",
... | Return schema GET results.
@param Request $request Current http request
@param string $id ID of record
@throws SerializationException
@return \Symfony\Component\HttpFoundation\Response $response Result of the action | [
"Return",
"schema",
"GET",
"results",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Controller/RestController.php#L406-L438 | train |
libgraviton/graviton | src/Graviton/RestBundle/DependencyInjection/Compiler/RqlQueryRoutesCompilerPass.php | RqlQueryRoutesCompilerPass.process | public function process(ContainerBuilder $container)
{
$routes = [];
foreach ($container->getParameter('graviton.rest.services') as $service => $params) {
list($app, $bundle, , $entity) = explode('.', $service);
$routes[] = implode('.', [$app, $bundle, 'rest', $entity, 'all']);
$routes[] = implode('.', [$app, $bundle, 'rest', $entity, 'get']);
}
$container->setParameter('graviton.rest.listener.rqlqueryrequestlistener.allowedroutes', $routes);
} | php | public function process(ContainerBuilder $container)
{
$routes = [];
foreach ($container->getParameter('graviton.rest.services') as $service => $params) {
list($app, $bundle, , $entity) = explode('.', $service);
$routes[] = implode('.', [$app, $bundle, 'rest', $entity, 'all']);
$routes[] = implode('.', [$app, $bundle, 'rest', $entity, 'get']);
}
$container->setParameter('graviton.rest.listener.rqlqueryrequestlistener.allowedroutes', $routes);
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"routes",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"container",
"->",
"getParameter",
"(",
"'graviton.rest.services'",
")",
"as",
"$",
"service",
"=>",
"$",
"params",
... | Find "allAction" routes and set it to allowed routes for RQL parsing
@param ContainerBuilder $container Container builder
@return void | [
"Find",
"allAction",
"routes",
"and",
"set",
"it",
"to",
"allowed",
"routes",
"for",
"RQL",
"parsing"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/DependencyInjection/Compiler/RqlQueryRoutesCompilerPass.php#L24-L34 | train |
libgraviton/graviton | src/Graviton/AnalyticsBundle/Listener/HomepageRenderListener.php | HomepageRenderListener.onRender | public function onRender(HomepageRenderEvent $event)
{
$services = $this->serviceManager->getServices();
foreach ($services as $service) {
$event->addRoute($service['$ref'], $service['profile']);
}
} | php | public function onRender(HomepageRenderEvent $event)
{
$services = $this->serviceManager->getServices();
foreach ($services as $service) {
$event->addRoute($service['$ref'], $service['profile']);
}
} | [
"public",
"function",
"onRender",
"(",
"HomepageRenderEvent",
"$",
"event",
")",
"{",
"$",
"services",
"=",
"$",
"this",
"->",
"serviceManager",
"->",
"getServices",
"(",
")",
";",
"foreach",
"(",
"$",
"services",
"as",
"$",
"service",
")",
"{",
"$",
"ev... | Add our links to the homepage
@param HomepageRenderEvent $event event
@return void | [
"Add",
"our",
"links",
"to",
"the",
"homepage"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/AnalyticsBundle/Listener/HomepageRenderListener.php#L42-L48 | train |
libgraviton/graviton | src/Graviton/CoreBundle/Controller/FaviconController.php | FaviconController.iconAction | public function iconAction()
{
header('Content-Type: image/x-icon');
// open our file
$fp = fopen(__DIR__.'/../Resources/assets/favicon.ico', 'r');
fpassthru($fp);
fclose($fp);
exit;
} | php | public function iconAction()
{
header('Content-Type: image/x-icon');
// open our file
$fp = fopen(__DIR__.'/../Resources/assets/favicon.ico', 'r');
fpassthru($fp);
fclose($fp);
exit;
} | [
"public",
"function",
"iconAction",
"(",
")",
"{",
"header",
"(",
"'Content-Type: image/x-icon'",
")",
";",
"// open our file",
"$",
"fp",
"=",
"fopen",
"(",
"__DIR__",
".",
"'/../Resources/assets/favicon.ico'",
",",
"'r'",
")",
";",
"fpassthru",
"(",
"$",
"fp",... | renders a favicon
@return \Symfony\Component\HttpFoundation\Response $response Response with result or error | [
"renders",
"a",
"favicon"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Controller/FaviconController.php#L21-L29 | train |
libgraviton/graviton | src/Graviton/RestBundle/Listener/XVersionResponseListener.php | XVersionResponseListener.onKernelResponse | public function onKernelResponse(FilterResponseEvent $event)
{
if (!$event->isMasterRequest()) {
// don't do anything if it's not the master request
return;
}
$event->getResponse()->headers->set(
'X-Version',
$this->versionHeader
);
} | php | public function onKernelResponse(FilterResponseEvent $event)
{
if (!$event->isMasterRequest()) {
// don't do anything if it's not the master request
return;
}
$event->getResponse()->headers->set(
'X-Version',
$this->versionHeader
);
} | [
"public",
"function",
"onKernelResponse",
"(",
"FilterResponseEvent",
"$",
"event",
")",
"{",
"if",
"(",
"!",
"$",
"event",
"->",
"isMasterRequest",
"(",
")",
")",
"{",
"// don't do anything if it's not the master request",
"return",
";",
"}",
"$",
"event",
"->",
... | Adds a X-Version header to the response.
@param FilterResponseEvent $event Current emitted event.
@return void | [
"Adds",
"a",
"X",
"-",
"Version",
"header",
"to",
"the",
"response",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Listener/XVersionResponseListener.php#L40-L51 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/ArrayField.php | ArrayField.getItemType | public function getItemType()
{
if (!preg_match('/array\<(.+)\>/i', $this->serializerType, $matches)) {
return $this->serializerType;
}
$map = [
'DateTime' => 'date',
'integer' => 'int',
'float' => 'float',
'double' => 'float',
'boolean' => 'boolean',
'extref' => 'extref',
];
return isset($map[$matches[1]]) ? $map[$matches[1]] : $matches[1];
} | php | public function getItemType()
{
if (!preg_match('/array\<(.+)\>/i', $this->serializerType, $matches)) {
return $this->serializerType;
}
$map = [
'DateTime' => 'date',
'integer' => 'int',
'float' => 'float',
'double' => 'float',
'boolean' => 'boolean',
'extref' => 'extref',
];
return isset($map[$matches[1]]) ? $map[$matches[1]] : $matches[1];
} | [
"public",
"function",
"getItemType",
"(",
")",
"{",
"if",
"(",
"!",
"preg_match",
"(",
"'/array\\<(.+)\\>/i'",
",",
"$",
"this",
"->",
"serializerType",
",",
"$",
"matches",
")",
")",
"{",
"return",
"$",
"this",
"->",
"serializerType",
";",
"}",
"$",
"ma... | Get item type
@return string | [
"Get",
"item",
"type"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/ArrayField.php#L59-L74 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Constraint/VersionServiceConstraint.php | VersionServiceConstraint.isVersioningService | public function isVersioningService()
{
$schema = $this->utils->getCurrentSchema();
if (isset($schema->{'x-versioning'}) && $schema->{'x-versioning'} === true) {
return true;
}
return false;
} | php | public function isVersioningService()
{
$schema = $this->utils->getCurrentSchema();
if (isset($schema->{'x-versioning'}) && $schema->{'x-versioning'} === true) {
return true;
}
return false;
} | [
"public",
"function",
"isVersioningService",
"(",
")",
"{",
"$",
"schema",
"=",
"$",
"this",
"->",
"utils",
"->",
"getCurrentSchema",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"schema",
"->",
"{",
"'x-versioning'",
"}",
")",
"&&",
"$",
"schema",
"->... | tells whether the current service has versioning activated or not
@return bool true if yes, false otherwise | [
"tells",
"whether",
"the",
"current",
"service",
"has",
"versioning",
"activated",
"or",
"not"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/VersionServiceConstraint.php#L85-L92 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Constraint/VersionServiceConstraint.php | VersionServiceConstraint.getVersionFromObject | private function getVersionFromObject($object)
{
$version = null;
if ($this->accessor->isReadable($object, self::FIELD_NAME)) {
$version = $this->accessor->getValue($object, self::FIELD_NAME);
}
return $version;
} | php | private function getVersionFromObject($object)
{
$version = null;
if ($this->accessor->isReadable($object, self::FIELD_NAME)) {
$version = $this->accessor->getValue($object, self::FIELD_NAME);
}
return $version;
} | [
"private",
"function",
"getVersionFromObject",
"(",
"$",
"object",
")",
"{",
"$",
"version",
"=",
"null",
";",
"if",
"(",
"$",
"this",
"->",
"accessor",
"->",
"isReadable",
"(",
"$",
"object",
",",
"self",
"::",
"FIELD_NAME",
")",
")",
"{",
"$",
"versi... | returns the version from a given object
@param object $object object
@return int|null null or the specified version | [
"returns",
"the",
"version",
"from",
"a",
"given",
"object"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/VersionServiceConstraint.php#L101-L109 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Constraint/VersionServiceConstraint.php | VersionServiceConstraint.getUserVersion | private function getUserVersion($object)
{
if ($this->utils->getCurrentRequestMethod() == 'PATCH') {
$content = json_decode($this->utils->getCurrentRequestContent(), true);
$hasVersion = array_filter(
$content,
function ($val) {
if ($val['path'] == '/'.self::FIELD_NAME) {
return true;
}
return false;
}
);
if (empty($hasVersion)) {
return -1;
}
}
return $this->getVersionFromObject($object);
} | php | private function getUserVersion($object)
{
if ($this->utils->getCurrentRequestMethod() == 'PATCH') {
$content = json_decode($this->utils->getCurrentRequestContent(), true);
$hasVersion = array_filter(
$content,
function ($val) {
if ($val['path'] == '/'.self::FIELD_NAME) {
return true;
}
return false;
}
);
if (empty($hasVersion)) {
return -1;
}
}
return $this->getVersionFromObject($object);
} | [
"private",
"function",
"getUserVersion",
"(",
"$",
"object",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"utils",
"->",
"getCurrentRequestMethod",
"(",
")",
"==",
"'PATCH'",
")",
"{",
"$",
"content",
"=",
"json_decode",
"(",
"$",
"this",
"->",
"utils",
"->",... | Gets the user provided version, handling different scenarios
@param object $object object
@return int|null null or the specified version | [
"Gets",
"the",
"user",
"provided",
"version",
"handling",
"different",
"scenarios"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/VersionServiceConstraint.php#L118-L139 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Constraint/VersionServiceConstraint.php | VersionServiceConstraint.setCurrentVersionHeader | public function setCurrentVersionHeader(FilterResponseEvent $event)
{
if ($this->version) {
$event->getResponse()->headers->set(self::HEADER_NAME, $this->version);
}
} | php | public function setCurrentVersionHeader(FilterResponseEvent $event)
{
if ($this->version) {
$event->getResponse()->headers->set(self::HEADER_NAME, $this->version);
}
} | [
"public",
"function",
"setCurrentVersionHeader",
"(",
"FilterResponseEvent",
"$",
"event",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"version",
")",
"{",
"$",
"event",
"->",
"getResponse",
"(",
")",
"->",
"headers",
"->",
"set",
"(",
"self",
"::",
"HEADER_NA... | Setting if needed the headers to let user know what was the new version.
@param FilterResponseEvent $event SF response event
@return void | [
"Setting",
"if",
"needed",
"the",
"headers",
"to",
"let",
"user",
"know",
"what",
"was",
"the",
"new",
"version",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/VersionServiceConstraint.php#L147-L152 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Constraint/ConstraintBuilder.php | ConstraintBuilder.addConstraints | public function addConstraints($fieldName, Schema $property, DocumentModel $model)
{
$constraints = $model->getConstraints($fieldName);
if (!is_array($constraints)) {
return $property;
}
foreach ($constraints as $constraint) {
$isSupported = false;
foreach ($this->builders as $builder) {
if ($builder->supportsConstraint($constraint->name, $constraint->options)) {
$property = $builder->buildConstraint($fieldName, $property, $model, $constraint->options);
$isSupported = true;
}
}
if (!$isSupported) {
/**
* unknown/not supported constraints will be added to the 'x-constraints' schema property.
* this allows others (possibly schema constraints) to pick it up and implement more advanced logic.
*/
$property->addConstraint($constraint->name);
}
}
return $property;
} | php | public function addConstraints($fieldName, Schema $property, DocumentModel $model)
{
$constraints = $model->getConstraints($fieldName);
if (!is_array($constraints)) {
return $property;
}
foreach ($constraints as $constraint) {
$isSupported = false;
foreach ($this->builders as $builder) {
if ($builder->supportsConstraint($constraint->name, $constraint->options)) {
$property = $builder->buildConstraint($fieldName, $property, $model, $constraint->options);
$isSupported = true;
}
}
if (!$isSupported) {
/**
* unknown/not supported constraints will be added to the 'x-constraints' schema property.
* this allows others (possibly schema constraints) to pick it up and implement more advanced logic.
*/
$property->addConstraint($constraint->name);
}
}
return $property;
} | [
"public",
"function",
"addConstraints",
"(",
"$",
"fieldName",
",",
"Schema",
"$",
"property",
",",
"DocumentModel",
"$",
"model",
")",
"{",
"$",
"constraints",
"=",
"$",
"model",
"->",
"getConstraints",
"(",
"$",
"fieldName",
")",
";",
"if",
"(",
"!",
"... | Go through the constraints and call the builders to do their job
@param string $fieldName field name
@param Schema $property the property
@param DocumentModel $model the parent model
@return Schema | [
"Go",
"through",
"the",
"constraints",
"and",
"call",
"the",
"builders",
"to",
"do",
"their",
"job"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/ConstraintBuilder.php#L45-L72 | train |
konduto/php-sdk | src/Models/Payment.php | Payment.build | public static function build(array $array) {
if (array_key_exists("type", $array) && in_array($array["type"], self::$availableTypes)) {
switch ($array["type"]) {
case Payment::TYPE_CREDIT:
return new CreditCard($array);
break;
case Payment::TYPE_BOLETO:
return new Boleto($array);
break;
case Payment::TYPE_DEBIT:
case Payment::TYPE_TRANSFER:
case Payment::TYPE_VOUCHER:
return new Payment($array);
break;
default: // Exception
}
}
throw new \InvalidArgumentException("Array must contain a valid 'type' field");
} | php | public static function build(array $array) {
if (array_key_exists("type", $array) && in_array($array["type"], self::$availableTypes)) {
switch ($array["type"]) {
case Payment::TYPE_CREDIT:
return new CreditCard($array);
break;
case Payment::TYPE_BOLETO:
return new Boleto($array);
break;
case Payment::TYPE_DEBIT:
case Payment::TYPE_TRANSFER:
case Payment::TYPE_VOUCHER:
return new Payment($array);
break;
default: // Exception
}
}
throw new \InvalidArgumentException("Array must contain a valid 'type' field");
} | [
"public",
"static",
"function",
"build",
"(",
"array",
"$",
"array",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"\"type\"",
",",
"$",
"array",
")",
"&&",
"in_array",
"(",
"$",
"array",
"[",
"\"type\"",
"]",
",",
"self",
"::",
"$",
"availableTypes",
... | Given an array, instantiates a payment among the possible
types of payments. The decision of what Model to use is made
by field 'type'
@param $array: array containing fields of the Payment
@return Payment CreditCard or Boleto object | [
"Given",
"an",
"array",
"instantiates",
"a",
"payment",
"among",
"the",
"possible",
"types",
"of",
"payments",
".",
"The",
"decision",
"of",
"what",
"Model",
"to",
"use",
"is",
"made",
"by",
"field",
"type"
] | ff095590c30307897c557f980845f613ff351585 | https://github.com/konduto/php-sdk/blob/ff095590c30307897c557f980845f613ff351585/src/Models/Payment.php#L32-L53 | train |
libgraviton/graviton | src/Graviton/RabbitMqBundle/Service/DumpConsumer.php | DumpConsumer.execute | public function execute(AMQPMessage $msg)
{
echo str_repeat('-', 60).PHP_EOL;
echo '[RECV ' . date('c') . ']' . PHP_EOL .'<content>' .
PHP_EOL . $msg->body . PHP_EOL . '</content>'.PHP_EOL.PHP_EOL;
echo "*" . ' INFO ' . PHP_EOL;
foreach ($msg->{'delivery_info'} as $key => $value) {
if (is_scalar($value)) {
echo "** " . $key . ' = ' . $value . PHP_EOL;
}
}
echo "*" . ' PROPERTIES ' . PHP_EOL;
foreach ($msg->get_properties() as $property => $value) {
if (is_scalar($value)) {
echo "** " . $property . ' = ' . $value . PHP_EOL;
}
}
} | php | public function execute(AMQPMessage $msg)
{
echo str_repeat('-', 60).PHP_EOL;
echo '[RECV ' . date('c') . ']' . PHP_EOL .'<content>' .
PHP_EOL . $msg->body . PHP_EOL . '</content>'.PHP_EOL.PHP_EOL;
echo "*" . ' INFO ' . PHP_EOL;
foreach ($msg->{'delivery_info'} as $key => $value) {
if (is_scalar($value)) {
echo "** " . $key . ' = ' . $value . PHP_EOL;
}
}
echo "*" . ' PROPERTIES ' . PHP_EOL;
foreach ($msg->get_properties() as $property => $value) {
if (is_scalar($value)) {
echo "** " . $property . ' = ' . $value . PHP_EOL;
}
}
} | [
"public",
"function",
"execute",
"(",
"AMQPMessage",
"$",
"msg",
")",
"{",
"echo",
"str_repeat",
"(",
"'-'",
",",
"60",
")",
".",
"PHP_EOL",
";",
"echo",
"'[RECV '",
".",
"date",
"(",
"'c'",
")",
".",
"']'",
".",
"PHP_EOL",
".",
"'<content>'",
".",
"... | Callback executed when a message is received. Dumps the message body, delivery_info and properties.
@param AMQPMessage $msg The received message.
@return void | [
"Callback",
"executed",
"when",
"a",
"message",
"is",
"received",
".",
"Dumps",
"the",
"message",
"body",
"delivery_info",
"and",
"properties",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RabbitMqBundle/Service/DumpConsumer.php#L29-L48 | train |
konduto/php-sdk | src/Models/Travel.php | Travel.build | public static function build(array $args) {
if (is_array($args) && array_key_exists("type", $args)) {
switch ($args["type"]) {
case Travel::TYPE_BUS:
return new BusTravel($args);
case Travel::TYPE_FLIGHT:
return new Flight($args);
}
}
throw new \InvalidArgumentException("Array must contain a valid 'type' field");
} | php | public static function build(array $args) {
if (is_array($args) && array_key_exists("type", $args)) {
switch ($args["type"]) {
case Travel::TYPE_BUS:
return new BusTravel($args);
case Travel::TYPE_FLIGHT:
return new Flight($args);
}
}
throw new \InvalidArgumentException("Array must contain a valid 'type' field");
} | [
"public",
"static",
"function",
"build",
"(",
"array",
"$",
"args",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"args",
")",
"&&",
"array_key_exists",
"(",
"\"type\"",
",",
"$",
"args",
")",
")",
"{",
"switch",
"(",
"$",
"args",
"[",
"\"type\"",
"]",
... | Given an array, instantiates a travel among the possible
types of travel. The decision of what Model to use is made
by the field 'type'
@param array $args: array containing fields of the Travel
@return Travel BusTravel or Flight object | [
"Given",
"an",
"array",
"instantiates",
"a",
"travel",
"among",
"the",
"possible",
"types",
"of",
"travel",
".",
"The",
"decision",
"of",
"what",
"Model",
"to",
"use",
"is",
"made",
"by",
"the",
"field",
"type"
] | ff095590c30307897c557f980845f613ff351585 | https://github.com/konduto/php-sdk/blob/ff095590c30307897c557f980845f613ff351585/src/Models/Travel.php#L35-L45 | train |
libgraviton/graviton | src/Graviton/SecurityBundle/Controller/WhoAmIController.php | WhoAmIController.whoAmIAction | public function whoAmIAction()
{
/** @var SecurityUser $securityUser */
$securityUser = $this->getSecurityUser();
/** @var Response $response */
$response = $this->getResponse();
$response->headers->set('Content-Type', 'application/json');
if (!$securityUser) {
$response->setContent(json_encode(['Security is not enabled']));
$response->setStatusCode(Response::HTTP_METHOD_NOT_ALLOWED);
return $response;
}
$response->setContent($this->restUtils->serialize($securityUser->getUser()));
$response->setStatusCode(Response::HTTP_OK);
return $response;
} | php | public function whoAmIAction()
{
/** @var SecurityUser $securityUser */
$securityUser = $this->getSecurityUser();
/** @var Response $response */
$response = $this->getResponse();
$response->headers->set('Content-Type', 'application/json');
if (!$securityUser) {
$response->setContent(json_encode(['Security is not enabled']));
$response->setStatusCode(Response::HTTP_METHOD_NOT_ALLOWED);
return $response;
}
$response->setContent($this->restUtils->serialize($securityUser->getUser()));
$response->setStatusCode(Response::HTTP_OK);
return $response;
} | [
"public",
"function",
"whoAmIAction",
"(",
")",
"{",
"/** @var SecurityUser $securityUser */",
"$",
"securityUser",
"=",
"$",
"this",
"->",
"getSecurityUser",
"(",
")",
";",
"/** @var Response $response */",
"$",
"response",
"=",
"$",
"this",
"->",
"getResponse",
"(... | Currently authenticated user information.
If security is not enabled then header will be Not Allowed.
If User not found using correct header Anonymous user
Serialised Object transformer
@return Response $response Response with result or error | [
"Currently",
"authenticated",
"user",
"information",
".",
"If",
"security",
"is",
"not",
"enabled",
"then",
"header",
"will",
"be",
"Not",
"Allowed",
".",
"If",
"User",
"not",
"found",
"using",
"correct",
"header",
"Anonymous",
"user",
"Serialised",
"Object",
... | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SecurityBundle/Controller/WhoAmIController.php#L28-L47 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php | GenerateDynamicBundleCommand.getExistingBundleHashes | private function getExistingBundleHashes($baseDir)
{
$existingBundles = [];
$fs = new Filesystem();
$bundleBaseDir = $baseDir.self::BUNDLE_NAMESPACE;
if (!$fs->exists($bundleBaseDir)) {
return $existingBundles;
}
$bundleFinder = $this->getBundleFinder($baseDir);
foreach ($bundleFinder as $bundleDir) {
$genHash = '';
$hashFileFinder = new Finder();
$hashFileIterator = $hashFileFinder
->files()
->in($bundleDir->getPathname())
->name(self::GENERATION_HASHFILE_FILENAME)
->depth('== 0')
->getIterator();
$hashFileIterator->rewind();
$hashFile = $hashFileIterator->current();
if ($hashFile instanceof SplFileInfo) {
$genHash = $hashFile->getContents();
}
$existingBundles[$bundleDir->getPathname()] = $genHash;
}
return $existingBundles;
} | php | private function getExistingBundleHashes($baseDir)
{
$existingBundles = [];
$fs = new Filesystem();
$bundleBaseDir = $baseDir.self::BUNDLE_NAMESPACE;
if (!$fs->exists($bundleBaseDir)) {
return $existingBundles;
}
$bundleFinder = $this->getBundleFinder($baseDir);
foreach ($bundleFinder as $bundleDir) {
$genHash = '';
$hashFileFinder = new Finder();
$hashFileIterator = $hashFileFinder
->files()
->in($bundleDir->getPathname())
->name(self::GENERATION_HASHFILE_FILENAME)
->depth('== 0')
->getIterator();
$hashFileIterator->rewind();
$hashFile = $hashFileIterator->current();
if ($hashFile instanceof SplFileInfo) {
$genHash = $hashFile->getContents();
}
$existingBundles[$bundleDir->getPathname()] = $genHash;
}
return $existingBundles;
} | [
"private",
"function",
"getExistingBundleHashes",
"(",
"$",
"baseDir",
")",
"{",
"$",
"existingBundles",
"=",
"[",
"]",
";",
"$",
"fs",
"=",
"new",
"Filesystem",
"(",
")",
";",
"$",
"bundleBaseDir",
"=",
"$",
"baseDir",
".",
"self",
"::",
"BUNDLE_NAMESPACE... | scans through all existing dynamic bundles, checks if there is a generation hash and collect that
all in an array that can be used for fast checking.
@param string $baseDir base directory of dynamic bundles
@return array key is bundlepath, value is the current hash | [
"scans",
"through",
"all",
"existing",
"dynamic",
"bundles",
"checks",
"if",
"there",
"is",
"a",
"generation",
"hash",
"and",
"collect",
"that",
"all",
"in",
"an",
"array",
"that",
"can",
"be",
"used",
"for",
"fast",
"checking",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L290-L323 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php | GenerateDynamicBundleCommand.getBundleClassnameFromFolder | private function getBundleClassnameFromFolder($folderName)
{
if (substr($folderName, -6) == 'Bundle') {
$folderName = substr($folderName, 0, -6);
}
return sprintf(self::BUNDLE_NAME_MASK, $folderName);
} | php | private function getBundleClassnameFromFolder($folderName)
{
if (substr($folderName, -6) == 'Bundle') {
$folderName = substr($folderName, 0, -6);
}
return sprintf(self::BUNDLE_NAME_MASK, $folderName);
} | [
"private",
"function",
"getBundleClassnameFromFolder",
"(",
"$",
"folderName",
")",
"{",
"if",
"(",
"substr",
"(",
"$",
"folderName",
",",
"-",
"6",
")",
"==",
"'Bundle'",
")",
"{",
"$",
"folderName",
"=",
"substr",
"(",
"$",
"folderName",
",",
"0",
",",... | from a name of a folder of a bundle, this function returns the corresponding class name
@param string $folderName folder name
@return string | [
"from",
"a",
"name",
"of",
"a",
"folder",
"of",
"a",
"bundle",
"this",
"function",
"returns",
"the",
"corresponding",
"class",
"name"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L332-L339 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php | GenerateDynamicBundleCommand.getBundleFinder | private function getBundleFinder($baseDir)
{
$bundleBaseDir = $baseDir.self::BUNDLE_NAMESPACE;
if (!(new Filesystem())->exists($bundleBaseDir)) {
return null;
}
$bundleFinder = new Finder();
$bundleFinder->directories()->in($bundleBaseDir)->depth('== 0')->notName('BundleBundle');
return $bundleFinder;
} | php | private function getBundleFinder($baseDir)
{
$bundleBaseDir = $baseDir.self::BUNDLE_NAMESPACE;
if (!(new Filesystem())->exists($bundleBaseDir)) {
return null;
}
$bundleFinder = new Finder();
$bundleFinder->directories()->in($bundleBaseDir)->depth('== 0')->notName('BundleBundle');
return $bundleFinder;
} | [
"private",
"function",
"getBundleFinder",
"(",
"$",
"baseDir",
")",
"{",
"$",
"bundleBaseDir",
"=",
"$",
"baseDir",
".",
"self",
"::",
"BUNDLE_NAMESPACE",
";",
"if",
"(",
"!",
"(",
"new",
"Filesystem",
"(",
")",
")",
"->",
"exists",
"(",
"$",
"bundleBase... | returns a finder that iterates all bundle directories
@param string $baseDir the base dir to search
@return Finder|null finder or null if basedir does not exist | [
"returns",
"a",
"finder",
"that",
"iterates",
"all",
"bundle",
"directories"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L348-L360 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php | GenerateDynamicBundleCommand.getTemplateHash | private function getTemplateHash()
{
$templateDir = __DIR__ . '/../Resources/skeleton';
$resourceFinder = new Finder();
$resourceFinder->in($templateDir)->files()->sortByName();
$templateTimes = '';
foreach ($resourceFinder as $file) {
$templateTimes .= PATH_SEPARATOR . sha1_file($file->getPathname());
}
return sha1($templateTimes);
} | php | private function getTemplateHash()
{
$templateDir = __DIR__ . '/../Resources/skeleton';
$resourceFinder = new Finder();
$resourceFinder->in($templateDir)->files()->sortByName();
$templateTimes = '';
foreach ($resourceFinder as $file) {
$templateTimes .= PATH_SEPARATOR . sha1_file($file->getPathname());
}
return sha1($templateTimes);
} | [
"private",
"function",
"getTemplateHash",
"(",
")",
"{",
"$",
"templateDir",
"=",
"__DIR__",
".",
"'/../Resources/skeleton'",
";",
"$",
"resourceFinder",
"=",
"new",
"Finder",
"(",
")",
";",
"$",
"resourceFinder",
"->",
"in",
"(",
"$",
"templateDir",
")",
"-... | Calculates a hash of all templates that generator uses to output it's file.
That way a regeneration will be triggered when one of them changes..
@return string hash | [
"Calculates",
"a",
"hash",
"of",
"all",
"templates",
"that",
"generator",
"uses",
"to",
"output",
"it",
"s",
"file",
".",
"That",
"way",
"a",
"regeneration",
"will",
"be",
"triggered",
"when",
"one",
"of",
"them",
"changes",
".."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L368-L378 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php | GenerateDynamicBundleCommand.generateSubResources | protected function generateSubResources(
OutputInterface $output,
JsonDefinition $jsonDef,
$bundleName,
$bundleClassName
) {
foreach ($this->getSubResources($jsonDef) as $subRecource) {
$arguments = [
'graviton:generate:resource',
'--no-debug' => null,
'--entity' => $bundleName . ':' . $subRecource->getId(),
'--bundleClassName' => $bundleClassName,
'--json' => $this->serializer->serialize($subRecource->getDef(), 'json'),
'--no-controller' => 'true',
];
$this->generateResource($arguments, $output, $jsonDef);
}
} | php | protected function generateSubResources(
OutputInterface $output,
JsonDefinition $jsonDef,
$bundleName,
$bundleClassName
) {
foreach ($this->getSubResources($jsonDef) as $subRecource) {
$arguments = [
'graviton:generate:resource',
'--no-debug' => null,
'--entity' => $bundleName . ':' . $subRecource->getId(),
'--bundleClassName' => $bundleClassName,
'--json' => $this->serializer->serialize($subRecource->getDef(), 'json'),
'--no-controller' => 'true',
];
$this->generateResource($arguments, $output, $jsonDef);
}
} | [
"protected",
"function",
"generateSubResources",
"(",
"OutputInterface",
"$",
"output",
",",
"JsonDefinition",
"$",
"jsonDef",
",",
"$",
"bundleName",
",",
"$",
"bundleClassName",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getSubResources",
"(",
"$",
"jsonDef... | Generate Bundle entities
@param OutputInterface $output Instance to sent text to be displayed on stout.
@param JsonDefinition $jsonDef Configuration to be generated the entity from.
@param string $bundleName Name of the bundle the entity shall be generated for.
@param string $bundleClassName class name
@return void
@throws \Exception | [
"Generate",
"Bundle",
"entities"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L391-L408 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php | GenerateDynamicBundleCommand.generateResources | protected function generateResources(
JsonDefinition $jsonDef,
$bundleName,
$bundleDir,
$bundleNamespace
) {
/** @var ResourceGenerator $generator */
$generator = $this->resourceGenerator;
$generator->setGenerateController(false);
foreach ($this->getSubResources($jsonDef) as $subRecource) {
$generator->setJson(new JsonDefinition($subRecource->getDef()->setIsSubDocument(true)));
$generator->generate(
$bundleDir,
$bundleNamespace,
$bundleName,
$subRecource->getId()
);
}
// main resources
if (!empty($jsonDef->getFields())) {
$generator->setGenerateController(true);
$routerBase = $jsonDef->getRouterBase();
if ($routerBase === false || $this->isNotWhitelistedController($routerBase)) {
$generator->setGenerateController(false);
}
$generator->setJson(new JsonDefinition($jsonDef->getDef()));
$generator->generate(
$bundleDir,
$bundleNamespace,
$bundleName,
$jsonDef->getId()
);
}
} | php | protected function generateResources(
JsonDefinition $jsonDef,
$bundleName,
$bundleDir,
$bundleNamespace
) {
/** @var ResourceGenerator $generator */
$generator = $this->resourceGenerator;
$generator->setGenerateController(false);
foreach ($this->getSubResources($jsonDef) as $subRecource) {
$generator->setJson(new JsonDefinition($subRecource->getDef()->setIsSubDocument(true)));
$generator->generate(
$bundleDir,
$bundleNamespace,
$bundleName,
$subRecource->getId()
);
}
// main resources
if (!empty($jsonDef->getFields())) {
$generator->setGenerateController(true);
$routerBase = $jsonDef->getRouterBase();
if ($routerBase === false || $this->isNotWhitelistedController($routerBase)) {
$generator->setGenerateController(false);
}
$generator->setJson(new JsonDefinition($jsonDef->getDef()));
$generator->generate(
$bundleDir,
$bundleNamespace,
$bundleName,
$jsonDef->getId()
);
}
} | [
"protected",
"function",
"generateResources",
"(",
"JsonDefinition",
"$",
"jsonDef",
",",
"$",
"bundleName",
",",
"$",
"bundleDir",
",",
"$",
"bundleNamespace",
")",
"{",
"/** @var ResourceGenerator $generator */",
"$",
"generator",
"=",
"$",
"this",
"->",
"resource... | generates the resources of a bundle
@param JsonDefinition $jsonDef definition
@param string $bundleName name
@param string $bundleDir dir
@param string $bundleNamespace namespace
@return void | [
"generates",
"the",
"resources",
"of",
"a",
"bundle"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L420-L458 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php | GenerateDynamicBundleCommand.getSubResources | protected function getSubResources(JsonDefinition $definition)
{
$resources = [];
foreach ($definition->getFields() as $field) {
while ($field instanceof JsonDefinitionArray) {
$field = $field->getElement();
}
if (!$field instanceof JsonDefinitionHash) {
continue;
}
$subDefiniton = $field->getJsonDefinition();
$resources = array_merge($this->getSubResources($subDefiniton), $resources);
$resources[] = $subDefiniton;
}
return $resources;
} | php | protected function getSubResources(JsonDefinition $definition)
{
$resources = [];
foreach ($definition->getFields() as $field) {
while ($field instanceof JsonDefinitionArray) {
$field = $field->getElement();
}
if (!$field instanceof JsonDefinitionHash) {
continue;
}
$subDefiniton = $field->getJsonDefinition();
$resources = array_merge($this->getSubResources($subDefiniton), $resources);
$resources[] = $subDefiniton;
}
return $resources;
} | [
"protected",
"function",
"getSubResources",
"(",
"JsonDefinition",
"$",
"definition",
")",
"{",
"$",
"resources",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"definition",
"->",
"getFields",
"(",
")",
"as",
"$",
"field",
")",
"{",
"while",
"(",
"$",
"field"... | Get all sub hashes
@param JsonDefinition $definition Main JSON definition
@return JsonDefinition[] | [
"Get",
"all",
"sub",
"hashes"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L466-L484 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php | GenerateDynamicBundleCommand.generateResource | private function generateResource(array $arguments, OutputInterface $output, JsonDefinition $jsonDef)
{
// controller?
$routerBase = $jsonDef->getRouterBase();
if ($routerBase === false || $this->isNotWhitelistedController($routerBase)) {
$arguments['--no-controller'] = 'true';
}
$this->runner->executeCommand($arguments, $output, 'Create resource call failed, see above. Exiting.');
} | php | private function generateResource(array $arguments, OutputInterface $output, JsonDefinition $jsonDef)
{
// controller?
$routerBase = $jsonDef->getRouterBase();
if ($routerBase === false || $this->isNotWhitelistedController($routerBase)) {
$arguments['--no-controller'] = 'true';
}
$this->runner->executeCommand($arguments, $output, 'Create resource call failed, see above. Exiting.');
} | [
"private",
"function",
"generateResource",
"(",
"array",
"$",
"arguments",
",",
"OutputInterface",
"$",
"output",
",",
"JsonDefinition",
"$",
"jsonDef",
")",
"{",
"// controller?",
"$",
"routerBase",
"=",
"$",
"jsonDef",
"->",
"getRouterBase",
"(",
")",
";",
"... | Gathers data for the command to run.
@param array $arguments Set of cli arguments passed to the command
@param OutputInterface $output Output channel to send messages to.
@param JsonDefinition $jsonDef Configuration of the service
@return void
@throws \LogicException | [
"Gathers",
"data",
"for",
"the",
"command",
"to",
"run",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L496-L505 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php | GenerateDynamicBundleCommand.generateBundleBundleClass | private function generateBundleBundleClass()
{
// add optional bundles if defined by parameter.
if ($this->bundleAdditions !== null) {
$this->bundleBundleGenerator->setAdditions($this->bundleAdditions);
} else {
$this->bundleBundleGenerator->setAdditions([]);
}
$this->bundleBundleGenerator->generate(
$this->bundleBundleList,
$this->bundleBundleNamespace,
$this->bundleBundleClassname,
$this->bundleBundleClassfile
);
} | php | private function generateBundleBundleClass()
{
// add optional bundles if defined by parameter.
if ($this->bundleAdditions !== null) {
$this->bundleBundleGenerator->setAdditions($this->bundleAdditions);
} else {
$this->bundleBundleGenerator->setAdditions([]);
}
$this->bundleBundleGenerator->generate(
$this->bundleBundleList,
$this->bundleBundleNamespace,
$this->bundleBundleClassname,
$this->bundleBundleClassfile
);
} | [
"private",
"function",
"generateBundleBundleClass",
"(",
")",
"{",
"// add optional bundles if defined by parameter.",
"if",
"(",
"$",
"this",
"->",
"bundleAdditions",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"bundleBundleGenerator",
"->",
"setAdditions",
"(",
"$",... | Generates our BundleBundle for dynamic bundles.
It basically replaces the Bundle main class that got generated
by the Sensio bundle task and it includes all of our bundles there.
@return void | [
"Generates",
"our",
"BundleBundle",
"for",
"dynamic",
"bundles",
".",
"It",
"basically",
"replaces",
"the",
"Bundle",
"main",
"class",
"that",
"got",
"generated",
"by",
"the",
"Sensio",
"bundle",
"task",
"and",
"it",
"includes",
"all",
"of",
"our",
"bundles",
... | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L538-L553 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php | GenerateDynamicBundleCommand.generateGenerationHashFile | private function generateGenerationHashFile($bundleDir, $hash)
{
$fs = new Filesystem();
if ($fs->exists($bundleDir)) {
$fs->dumpFile($bundleDir.DIRECTORY_SEPARATOR.self::GENERATION_HASHFILE_FILENAME, $hash);
}
} | php | private function generateGenerationHashFile($bundleDir, $hash)
{
$fs = new Filesystem();
if ($fs->exists($bundleDir)) {
$fs->dumpFile($bundleDir.DIRECTORY_SEPARATOR.self::GENERATION_HASHFILE_FILENAME, $hash);
}
} | [
"private",
"function",
"generateGenerationHashFile",
"(",
"$",
"bundleDir",
",",
"$",
"hash",
")",
"{",
"$",
"fs",
"=",
"new",
"Filesystem",
"(",
")",
";",
"if",
"(",
"$",
"fs",
"->",
"exists",
"(",
"$",
"bundleDir",
")",
")",
"{",
"$",
"fs",
"->",
... | Generates the file containing the hash to determine if this bundle needs regeneration
@param string $bundleDir directory of the bundle
@param string $hash the hash to save
@return void | [
"Generates",
"the",
"file",
"containing",
"the",
"hash",
"to",
"determine",
"if",
"this",
"bundle",
"needs",
"regeneration"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L582-L588 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/DependencyInjection/Compiler/ExtRefFieldsCompilerPass.php | ExtRefFieldsCompilerPass.process | public function process(ContainerBuilder $container)
{
$this->documentMap = $container->get('graviton.document.map');
$map = [];
$services = array_keys($container->findTaggedServiceIds('graviton.rest'));
foreach ($services as $id) {
list($ns, $bundle, , $doc) = explode('.', $id);
if (empty($bundle) || empty($doc)) {
continue;
}
if ($bundle === 'core' && $doc === 'main') {
continue;
}
$className = $this->getServiceDocument(
$container->getDefinition($id),
$ns,
$bundle,
$doc
);
$extRefFields = $this->processDocument($this->documentMap->getDocument($className));
$routePrefix = strtolower($ns.'.'.$bundle.'.'.'rest'.'.'.$doc);
$map[$routePrefix.'.get'] = $extRefFields;
$map[$routePrefix.'.all'] = $extRefFields;
}
$container->setParameter('graviton.document.extref.fields', $map);
} | php | public function process(ContainerBuilder $container)
{
$this->documentMap = $container->get('graviton.document.map');
$map = [];
$services = array_keys($container->findTaggedServiceIds('graviton.rest'));
foreach ($services as $id) {
list($ns, $bundle, , $doc) = explode('.', $id);
if (empty($bundle) || empty($doc)) {
continue;
}
if ($bundle === 'core' && $doc === 'main') {
continue;
}
$className = $this->getServiceDocument(
$container->getDefinition($id),
$ns,
$bundle,
$doc
);
$extRefFields = $this->processDocument($this->documentMap->getDocument($className));
$routePrefix = strtolower($ns.'.'.$bundle.'.'.'rest'.'.'.$doc);
$map[$routePrefix.'.get'] = $extRefFields;
$map[$routePrefix.'.all'] = $extRefFields;
}
$container->setParameter('graviton.document.extref.fields', $map);
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"this",
"->",
"documentMap",
"=",
"$",
"container",
"->",
"get",
"(",
"'graviton.document.map'",
")",
";",
"$",
"map",
"=",
"[",
"]",
";",
"$",
"services",
"=",
"a... | Make extref fields map and set it to parameter
@param ContainerBuilder $container container builder
@return void | [
"Make",
"extref",
"fields",
"map",
"and",
"set",
"it",
"to",
"parameter"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/ExtRefFieldsCompilerPass.php#L41-L71 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/DependencyInjection/Compiler/ExtRefFieldsCompilerPass.php | ExtRefFieldsCompilerPass.getServiceDocument | private function getServiceDocument(Definition $service, $ns, $bundle, $doc)
{
$tags = $service->getTag('graviton.rest');
if (!empty($tags[0]['collection'])) {
$doc = $tags[0]['collection'];
$bundle = $tags[0]['collection'];
}
if (strtolower($ns) === 'gravitondyn') {
$ns = 'GravitonDyn';
}
return sprintf(
'%s\\%s\\Document\\%s',
ucfirst($ns),
ucfirst($bundle).'Bundle',
ucfirst($doc)
);
} | php | private function getServiceDocument(Definition $service, $ns, $bundle, $doc)
{
$tags = $service->getTag('graviton.rest');
if (!empty($tags[0]['collection'])) {
$doc = $tags[0]['collection'];
$bundle = $tags[0]['collection'];
}
if (strtolower($ns) === 'gravitondyn') {
$ns = 'GravitonDyn';
}
return sprintf(
'%s\\%s\\Document\\%s',
ucfirst($ns),
ucfirst($bundle).'Bundle',
ucfirst($doc)
);
} | [
"private",
"function",
"getServiceDocument",
"(",
"Definition",
"$",
"service",
",",
"$",
"ns",
",",
"$",
"bundle",
",",
"$",
"doc",
")",
"{",
"$",
"tags",
"=",
"$",
"service",
"->",
"getTag",
"(",
"'graviton.rest'",
")",
";",
"if",
"(",
"!",
"empty",
... | Get document class name from service
@param Definition $service Service definition
@param string $ns Bundle namespace
@param string $bundle Bundle name
@param string $doc Document name
@return string | [
"Get",
"document",
"class",
"name",
"from",
"service"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/ExtRefFieldsCompilerPass.php#L83-L101 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/DependencyInjection/Compiler/ExtRefFieldsCompilerPass.php | ExtRefFieldsCompilerPass.processDocument | private function processDocument(Document $document, $exposedPrefix = '')
{
$result = [];
foreach ($document->getFields() as $field) {
if ($field instanceof Field) {
if ($field->getType() === 'extref') {
$result[] = $exposedPrefix.$field->getExposedName();
}
} elseif ($field instanceof ArrayField) {
if ($field->getItemType() === 'extref') {
$result[] = $exposedPrefix.$field->getExposedName().'.0';
}
} elseif ($field instanceof EmbedOne) {
$result = array_merge(
$result,
$this->processDocument(
$field->getDocument(),
$exposedPrefix.$field->getExposedName().'.'
)
);
} elseif ($field instanceof EmbedMany) {
$result = array_merge(
$result,
$this->processDocument(
$field->getDocument(),
$exposedPrefix.$field->getExposedName().'.0.'
)
);
}
}
return $result;
} | php | private function processDocument(Document $document, $exposedPrefix = '')
{
$result = [];
foreach ($document->getFields() as $field) {
if ($field instanceof Field) {
if ($field->getType() === 'extref') {
$result[] = $exposedPrefix.$field->getExposedName();
}
} elseif ($field instanceof ArrayField) {
if ($field->getItemType() === 'extref') {
$result[] = $exposedPrefix.$field->getExposedName().'.0';
}
} elseif ($field instanceof EmbedOne) {
$result = array_merge(
$result,
$this->processDocument(
$field->getDocument(),
$exposedPrefix.$field->getExposedName().'.'
)
);
} elseif ($field instanceof EmbedMany) {
$result = array_merge(
$result,
$this->processDocument(
$field->getDocument(),
$exposedPrefix.$field->getExposedName().'.0.'
)
);
}
}
return $result;
} | [
"private",
"function",
"processDocument",
"(",
"Document",
"$",
"document",
",",
"$",
"exposedPrefix",
"=",
"''",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"document",
"->",
"getFields",
"(",
")",
"as",
"$",
"field",
")",
"{",
... | Recursive doctrine document processing
@param Document $document Document
@param string $exposedPrefix Exposed field prefix
@return array | [
"Recursive",
"doctrine",
"document",
"processing"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/ExtRefFieldsCompilerPass.php#L110-L142 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Definition/Loader/HttpLoader.php | HttpLoader.supports | public function supports($url)
{
$error = $this->validator->validate($url, [new Url()]);
return 0 === count($error);
} | php | public function supports($url)
{
$error = $this->validator->validate($url, [new Url()]);
return 0 === count($error);
} | [
"public",
"function",
"supports",
"(",
"$",
"url",
")",
"{",
"$",
"error",
"=",
"$",
"this",
"->",
"validator",
"->",
"validate",
"(",
"$",
"url",
",",
"[",
"new",
"Url",
"(",
")",
"]",
")",
";",
"return",
"0",
"===",
"count",
"(",
"$",
"error",
... | check if the url is valid
@param string $url url
@return boolean | [
"check",
"if",
"the",
"url",
"is",
"valid"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Definition/Loader/HttpLoader.php#L136-L141 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Definition/Loader/HttpLoader.php | HttpLoader.fetchFile | private function fetchFile(RequestInterface $request)
{
$content = "{}";
try {
$response = $this->client->send($request);
$content = (string) $response->getBody();
if (isset($this->cache)) {
$this->cache->save($this->options['storeKey'], $content, $this->cacheLifetime);
}
} catch (RequestException $e) {
$this->logger->info(
"Unable to fetch File!",
[
"message" => $e->getMessage(),
"url" => $request->getRequestTarget(),
"code" => (!empty($e->getResponse())? $e->getResponse()->getStatusCode() : 500)
]
);
}
return $content;
} | php | private function fetchFile(RequestInterface $request)
{
$content = "{}";
try {
$response = $this->client->send($request);
$content = (string) $response->getBody();
if (isset($this->cache)) {
$this->cache->save($this->options['storeKey'], $content, $this->cacheLifetime);
}
} catch (RequestException $e) {
$this->logger->info(
"Unable to fetch File!",
[
"message" => $e->getMessage(),
"url" => $request->getRequestTarget(),
"code" => (!empty($e->getResponse())? $e->getResponse()->getStatusCode() : 500)
]
);
}
return $content;
} | [
"private",
"function",
"fetchFile",
"(",
"RequestInterface",
"$",
"request",
")",
"{",
"$",
"content",
"=",
"\"{}\"",
";",
"try",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"$",
"request",
")",
";",
"$",
"content",
"=",
... | fetch file from remote destination
@param RequestInterface $request request
@return string | [
"fetch",
"file",
"from",
"remote",
"destination"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Definition/Loader/HttpLoader.php#L196-L217 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Service/TransformationHandler.php | TransformationHandler.transformRequest | public function transformRequest($api, $endpoint, Request $requestIn, Request $requestOut)
{
$transformations = $this->getRequestTransformations($api, $endpoint);
if (!empty($transformations)) {
foreach ($transformations as $transformation) {
$transformedRequest = $transformation->transformRequest($requestIn, $requestOut);
$requestOut = $transformedRequest instanceof Request ? $transformedRequest : $requestOut;
}
return $requestOut;
}
// TODO [taafeba2]: add logging
return $requestOut;
} | php | public function transformRequest($api, $endpoint, Request $requestIn, Request $requestOut)
{
$transformations = $this->getRequestTransformations($api, $endpoint);
if (!empty($transformations)) {
foreach ($transformations as $transformation) {
$transformedRequest = $transformation->transformRequest($requestIn, $requestOut);
$requestOut = $transformedRequest instanceof Request ? $transformedRequest : $requestOut;
}
return $requestOut;
}
// TODO [taafeba2]: add logging
return $requestOut;
} | [
"public",
"function",
"transformRequest",
"(",
"$",
"api",
",",
"$",
"endpoint",
",",
"Request",
"$",
"requestIn",
",",
"Request",
"$",
"requestOut",
")",
"{",
"$",
"transformations",
"=",
"$",
"this",
"->",
"getRequestTransformations",
"(",
"$",
"api",
",",... | Applies all transformations defined for the given API and endpoint on a request.
@param string $api The API name
@param string $endpoint The endpoint
@param Request $requestIn The original request object.
@param Request $requestOut The request object to use for transformations
@return Request The transformed request
@throws TransformationException | [
"Applies",
"all",
"transformations",
"defined",
"for",
"the",
"given",
"API",
"and",
"endpoint",
"on",
"a",
"request",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Service/TransformationHandler.php#L48-L63 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Service/TransformationHandler.php | TransformationHandler.transformResponse | public function transformResponse($api, $endpoint, Response $responseIn, Response $responseOut)
{
$transformations = $this->getResponseTransformations($api, $endpoint);
foreach ($transformations as $transformation) {
$transformedRequest = $transformation->transformResponse($responseIn, $responseOut);
$responseOut = $transformedRequest instanceof Response ? $transformedRequest : $responseOut;
}
return $responseOut;
} | php | public function transformResponse($api, $endpoint, Response $responseIn, Response $responseOut)
{
$transformations = $this->getResponseTransformations($api, $endpoint);
foreach ($transformations as $transformation) {
$transformedRequest = $transformation->transformResponse($responseIn, $responseOut);
$responseOut = $transformedRequest instanceof Response ? $transformedRequest : $responseOut;
}
return $responseOut;
} | [
"public",
"function",
"transformResponse",
"(",
"$",
"api",
",",
"$",
"endpoint",
",",
"Response",
"$",
"responseIn",
",",
"Response",
"$",
"responseOut",
")",
"{",
"$",
"transformations",
"=",
"$",
"this",
"->",
"getResponseTransformations",
"(",
"$",
"api",
... | Applies all transformations defined for the given API and endpoint on a response.
@param string $api The API name
@param string $endpoint The endpoint
@param Response $responseIn The original response object
@param Response $responseOut The response object to use for transformations
@return Response The transformed response | [
"Applies",
"all",
"transformations",
"defined",
"for",
"the",
"given",
"API",
"and",
"endpoint",
"on",
"a",
"response",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Service/TransformationHandler.php#L74-L82 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Service/TransformationHandler.php | TransformationHandler.transformSchema | public function transformSchema($api, $endpoint, \stdClass $schemaIn, \stdClass $schemaOut)
{
$transformations = $this->getSchemaTransformations($api, $endpoint);
foreach ($transformations as $transformation) {
$transformedSchema = $transformation->transformSchema($schemaIn, $schemaOut);
$schemaOut = $transformedSchema instanceof \stdClass ? $transformedSchema : $schemaOut;
}
return $schemaOut;
} | php | public function transformSchema($api, $endpoint, \stdClass $schemaIn, \stdClass $schemaOut)
{
$transformations = $this->getSchemaTransformations($api, $endpoint);
foreach ($transformations as $transformation) {
$transformedSchema = $transformation->transformSchema($schemaIn, $schemaOut);
$schemaOut = $transformedSchema instanceof \stdClass ? $transformedSchema : $schemaOut;
}
return $schemaOut;
} | [
"public",
"function",
"transformSchema",
"(",
"$",
"api",
",",
"$",
"endpoint",
",",
"\\",
"stdClass",
"$",
"schemaIn",
",",
"\\",
"stdClass",
"$",
"schemaOut",
")",
"{",
"$",
"transformations",
"=",
"$",
"this",
"->",
"getSchemaTransformations",
"(",
"$",
... | Applies all transformations defined for the given API and endpoint on a schema.
@param string $api The API name
@param string $endpoint The endpoint
@param \stdClass $schemaIn The original schema object
@param \stdClass $schemaOut The schema object to use for transformations
@return \stdClass The transformed schema | [
"Applies",
"all",
"transformations",
"defined",
"for",
"the",
"given",
"API",
"and",
"endpoint",
"on",
"a",
"schema",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Service/TransformationHandler.php#L93-L101 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Service/TransformationHandler.php | TransformationHandler.getRequestTransformations | public function getRequestTransformations($api, $endpoint)
{
if (isset($this->requestTransformations[$api])) {
$patterns = array_keys($this->requestTransformations[$api]);
foreach ($patterns as $pattern) {
preg_match($pattern, $endpoint, $matches);
if (!empty($matches[1])) {
return $this->requestTransformations[$api][$pattern];
}
}
}
return [];
} | php | public function getRequestTransformations($api, $endpoint)
{
if (isset($this->requestTransformations[$api])) {
$patterns = array_keys($this->requestTransformations[$api]);
foreach ($patterns as $pattern) {
preg_match($pattern, $endpoint, $matches);
if (!empty($matches[1])) {
return $this->requestTransformations[$api][$pattern];
}
}
}
return [];
} | [
"public",
"function",
"getRequestTransformations",
"(",
"$",
"api",
",",
"$",
"endpoint",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"requestTransformations",
"[",
"$",
"api",
"]",
")",
")",
"{",
"$",
"patterns",
"=",
"array_keys",
"(",
"$",
... | Returns the request transformations registered for a given API and endpoint.
@param string $api The API name
@param string $endpoint The endpoint
@return array The transformations | [
"Returns",
"the",
"request",
"transformations",
"registered",
"for",
"a",
"given",
"API",
"and",
"endpoint",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Service/TransformationHandler.php#L110-L125 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Service/TransformationHandler.php | TransformationHandler.addRequestTransformation | public function addRequestTransformation($api, $endpoint, RequestTransformationInterface $transformation)
{
$this->requestTransformations[$api][$endpoint][] = $transformation;
return count($this->requestTransformations[$api][$endpoint]) - 1;
} | php | public function addRequestTransformation($api, $endpoint, RequestTransformationInterface $transformation)
{
$this->requestTransformations[$api][$endpoint][] = $transformation;
return count($this->requestTransformations[$api][$endpoint]) - 1;
} | [
"public",
"function",
"addRequestTransformation",
"(",
"$",
"api",
",",
"$",
"endpoint",
",",
"RequestTransformationInterface",
"$",
"transformation",
")",
"{",
"$",
"this",
"->",
"requestTransformations",
"[",
"$",
"api",
"]",
"[",
"$",
"endpoint",
"]",
"[",
... | Adds a transformation to a given API and endpoint.
@param string $api The API name
@param string $endpoint The API endpoint
@param RequestTransformationInterface $transformation The transformation
@return int The position of the added transformation within the transformation array. | [
"Adds",
"a",
"transformation",
"to",
"a",
"given",
"API",
"and",
"endpoint",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Service/TransformationHandler.php#L161-L165 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Service/TransformationHandler.php | TransformationHandler.addResponseTransformation | public function addResponseTransformation($api, $endpoint, ResponseTransformationInterface $transformation)
{
$this->responseTransformations[$api][$endpoint][] = $transformation;
return count($this->responseTransformations[$api][$endpoint]) - 1;
} | php | public function addResponseTransformation($api, $endpoint, ResponseTransformationInterface $transformation)
{
$this->responseTransformations[$api][$endpoint][] = $transformation;
return count($this->responseTransformations[$api][$endpoint]) - 1;
} | [
"public",
"function",
"addResponseTransformation",
"(",
"$",
"api",
",",
"$",
"endpoint",
",",
"ResponseTransformationInterface",
"$",
"transformation",
")",
"{",
"$",
"this",
"->",
"responseTransformations",
"[",
"$",
"api",
"]",
"[",
"$",
"endpoint",
"]",
"[",... | Adds a response transformation to a given API and endpoint.
@param string $api The API name
@param string $endpoint The API endpoint
@param ResponseTransformationInterface $transformation The transformation
@return int The position of the added transformation within the transformation array. | [
"Adds",
"a",
"response",
"transformation",
"to",
"a",
"given",
"API",
"and",
"endpoint",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Service/TransformationHandler.php#L175-L179 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Service/TransformationHandler.php | TransformationHandler.addSchemaTransformation | public function addSchemaTransformation($api, $endpoint, SchemaTransformationInterface $transformation)
{
$this->schemaTransformations[$api][$endpoint][] = $transformation;
return count($this->schemaTransformations[$api][$endpoint]) - 1;
} | php | public function addSchemaTransformation($api, $endpoint, SchemaTransformationInterface $transformation)
{
$this->schemaTransformations[$api][$endpoint][] = $transformation;
return count($this->schemaTransformations[$api][$endpoint]) - 1;
} | [
"public",
"function",
"addSchemaTransformation",
"(",
"$",
"api",
",",
"$",
"endpoint",
",",
"SchemaTransformationInterface",
"$",
"transformation",
")",
"{",
"$",
"this",
"->",
"schemaTransformations",
"[",
"$",
"api",
"]",
"[",
"$",
"endpoint",
"]",
"[",
"]"... | Adds a schema transformation to a given API and endpoint.
@param string $api The API name
@param string $endpoint The API endpoint
@param SchemaTransformationInterface $transformation The transformation
@return int The position of the added transformation within the transformation array. | [
"Adds",
"a",
"schema",
"transformation",
"to",
"a",
"given",
"API",
"and",
"endpoint",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Service/TransformationHandler.php#L189-L193 | train |
libgraviton/graviton | src/Graviton/AnalyticsBundle/Helper/JsonMapper.php | JsonMapper.map | public function map($json, $object)
{
foreach ($json as $key => $jvalue) {
$key = $this->getSafeName($key);
$setter = 'set' . $this->getCamelCaseName($key);
if (method_exists($object, $setter)) {
$object->{$setter}($jvalue);
}
}
return $object;
} | php | public function map($json, $object)
{
foreach ($json as $key => $jvalue) {
$key = $this->getSafeName($key);
$setter = 'set' . $this->getCamelCaseName($key);
if (method_exists($object, $setter)) {
$object->{$setter}($jvalue);
}
}
return $object;
} | [
"public",
"function",
"map",
"(",
"$",
"json",
",",
"$",
"object",
")",
"{",
"foreach",
"(",
"$",
"json",
"as",
"$",
"key",
"=>",
"$",
"jvalue",
")",
"{",
"$",
"key",
"=",
"$",
"this",
"->",
"getSafeName",
"(",
"$",
"key",
")",
";",
"$",
"sette... | Maps data into object class
@param object $json to be casted
@param object $object Class to receive data
@throws InvalidArgumentException
@return object | [
"Maps",
"data",
"into",
"object",
"class"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/AnalyticsBundle/Helper/JsonMapper.php#L26-L38 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Model/SchemaModel.php | SchemaModel.manyPropertyModelForTarget | public function manyPropertyModelForTarget($mapping)
{
// @todo refactor to get rid of container dependency (maybe remove from here)
list($app, $bundle, , $document) = explode('\\', $mapping);
$app = strtolower($app);
$bundle = strtolower(substr($bundle, 0, -6));
$document = strtolower($document);
$propertyService = implode('.', array($app, $bundle, 'model', $document));
$propertyModel = $this->container->get($propertyService);
return $propertyModel;
} | php | public function manyPropertyModelForTarget($mapping)
{
// @todo refactor to get rid of container dependency (maybe remove from here)
list($app, $bundle, , $document) = explode('\\', $mapping);
$app = strtolower($app);
$bundle = strtolower(substr($bundle, 0, -6));
$document = strtolower($document);
$propertyService = implode('.', array($app, $bundle, 'model', $document));
$propertyModel = $this->container->get($propertyService);
return $propertyModel;
} | [
"public",
"function",
"manyPropertyModelForTarget",
"(",
"$",
"mapping",
")",
"{",
"// @todo refactor to get rid of container dependency (maybe remove from here)",
"list",
"(",
"$",
"app",
",",
"$",
"bundle",
",",
",",
"$",
"document",
")",
"=",
"explode",
"(",
"'\\\\... | get property model for embedded field
@param string $mapping name of mapping class
@return $this | [
"get",
"property",
"model",
"for",
"embedded",
"field"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Model/SchemaModel.php#L176-L187 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Model/SchemaModel.php | SchemaModel.getRequiredFields | public function getRequiredFields($variationName = null)
{
if (is_null($variationName)) {
return $this->schema->required;
}
/* compose required fields based on variation */
$requiredFields = $this->getRequiredFields();
foreach ($this->schema->properties as $fieldName => $fieldAttributes) {
$onVariation = $this->getOnVariaton($fieldName);
if (is_object($onVariation) && isset($onVariation->{$variationName}->required)) {
$thisRequired = $onVariation->{$variationName}->required;
if ($thisRequired === true) {
$requiredFields[] = $fieldName;
}
if ($thisRequired === false) {
// see if its set
$fieldIndex = array_search($fieldName, $requiredFields);
if ($fieldName !== false) {
unset($requiredFields[$fieldIndex]);
}
}
}
}
return array_values(
array_unique(
$requiredFields
)
);
} | php | public function getRequiredFields($variationName = null)
{
if (is_null($variationName)) {
return $this->schema->required;
}
/* compose required fields based on variation */
$requiredFields = $this->getRequiredFields();
foreach ($this->schema->properties as $fieldName => $fieldAttributes) {
$onVariation = $this->getOnVariaton($fieldName);
if (is_object($onVariation) && isset($onVariation->{$variationName}->required)) {
$thisRequired = $onVariation->{$variationName}->required;
if ($thisRequired === true) {
$requiredFields[] = $fieldName;
}
if ($thisRequired === false) {
// see if its set
$fieldIndex = array_search($fieldName, $requiredFields);
if ($fieldName !== false) {
unset($requiredFields[$fieldIndex]);
}
}
}
}
return array_values(
array_unique(
$requiredFields
)
);
} | [
"public",
"function",
"getRequiredFields",
"(",
"$",
"variationName",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"variationName",
")",
")",
"{",
"return",
"$",
"this",
"->",
"schema",
"->",
"required",
";",
"}",
"/* compose required fields based on... | get required fields for this object
@param string $variationName a variation that can alter which fields are required
@return string[] | [
"get",
"required",
"fields",
"for",
"this",
"object"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Model/SchemaModel.php#L196-L229 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Model/SchemaModel.php | SchemaModel.getDocumentClass | public function getDocumentClass()
{
$documentClass = false;
if (isset($this->schema->{'x-documentClass'})) {
$documentClass = $this->schema->{'x-documentClass'};
}
return $documentClass;
} | php | public function getDocumentClass()
{
$documentClass = false;
if (isset($this->schema->{'x-documentClass'})) {
$documentClass = $this->schema->{'x-documentClass'};
}
return $documentClass;
} | [
"public",
"function",
"getDocumentClass",
"(",
")",
"{",
"$",
"documentClass",
"=",
"false",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"schema",
"->",
"{",
"'x-documentClass'",
"}",
")",
")",
"{",
"$",
"documentClass",
"=",
"$",
"this",
"->",
"s... | Gets the defined document class in shortform from schema
@return string|false either the document class or false it not given | [
"Gets",
"the",
"defined",
"document",
"class",
"in",
"shortform",
"from",
"schema"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Model/SchemaModel.php#L308-L315 | train |
libgraviton/graviton | src/Graviton/SchemaBundle/Model/SchemaModel.php | SchemaModel.getSchemaField | private function getSchemaField($field, $property, $fallbackValue = '')
{
if (isset($this->schema->properties->$field->$property)) {
$fallbackValue = $this->schema->properties->$field->$property;
}
return $fallbackValue;
} | php | private function getSchemaField($field, $property, $fallbackValue = '')
{
if (isset($this->schema->properties->$field->$property)) {
$fallbackValue = $this->schema->properties->$field->$property;
}
return $fallbackValue;
} | [
"private",
"function",
"getSchemaField",
"(",
"$",
"field",
",",
"$",
"property",
",",
"$",
"fallbackValue",
"=",
"''",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"schema",
"->",
"properties",
"->",
"$",
"field",
"->",
"$",
"property",
")",
... | get schema field value
@param string $field field name
@param string $property property name
@param mixed $fallbackValue fallback value if property isn't set
@return mixed | [
"get",
"schema",
"field",
"value"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Model/SchemaModel.php#L378-L385 | train |
duncan3dc/domparser | src/ParserTrait.php | ParserTrait.getData | protected function getData($data)
{
$method = "load" . strtoupper($this->mode);
libxml_use_internal_errors(true);
$this->dom->$method($data);
$this->errors = libxml_get_errors();
libxml_clear_errors();
return $data;
} | php | protected function getData($data)
{
$method = "load" . strtoupper($this->mode);
libxml_use_internal_errors(true);
$this->dom->$method($data);
$this->errors = libxml_get_errors();
libxml_clear_errors();
return $data;
} | [
"protected",
"function",
"getData",
"(",
"$",
"data",
")",
"{",
"$",
"method",
"=",
"\"load\"",
".",
"strtoupper",
"(",
"$",
"this",
"->",
"mode",
")",
";",
"libxml_use_internal_errors",
"(",
"true",
")",
";",
"$",
"this",
"->",
"dom",
"->",
"$",
"meth... | Get the content for parsing.
Creates an internal dom instance.
@param string $data The xml/html
@return string The xml/html | [
"Get",
"the",
"content",
"for",
"parsing",
"."
] | d5523b58337cab3b9ad90e8d135f87793795f93f | https://github.com/duncan3dc/domparser/blob/d5523b58337cab3b9ad90e8d135f87793795f93f/src/ParserTrait.php#L24-L34 | train |
duncan3dc/domparser | src/ParserTrait.php | ParserTrait.xpath | public function xpath($path)
{
$xpath = new \DOMXPath($this->dom);
$list = $xpath->query($path);
$return = [];
foreach ($list as $node) {
$return[] = $this->newElement($node);
}
return $return;
} | php | public function xpath($path)
{
$xpath = new \DOMXPath($this->dom);
$list = $xpath->query($path);
$return = [];
foreach ($list as $node) {
$return[] = $this->newElement($node);
}
return $return;
} | [
"public",
"function",
"xpath",
"(",
"$",
"path",
")",
"{",
"$",
"xpath",
"=",
"new",
"\\",
"DOMXPath",
"(",
"$",
"this",
"->",
"dom",
")",
";",
"$",
"list",
"=",
"$",
"xpath",
"->",
"query",
"(",
"$",
"path",
")",
";",
"$",
"return",
"=",
"[",
... | Get elements using an xpath selector.
@param string $path The xpath selector
@return Element[] | [
"Get",
"elements",
"using",
"an",
"xpath",
"selector",
"."
] | d5523b58337cab3b9ad90e8d135f87793795f93f | https://github.com/duncan3dc/domparser/blob/d5523b58337cab3b9ad90e8d135f87793795f93f/src/ParserTrait.php#L44-L56 | train |
libgraviton/graviton | src/Graviton/MigrationBundle/Command/MongodbMigrateCommand.php | MongodbMigrateCommand.execute | public function execute(InputInterface $input, OutputInterface $output)
{
// graviton root
$baseDir = __DIR__.'/../../../';
// vendorized? - go back some more..
if (strpos($baseDir, '/vendor/') !== false) {
$baseDir .= '../../../';
}
$this->finder
->in($baseDir)
->path('Resources/config')
->name('/migrations.(xml|yml)/')
->files();
foreach ($this->finder as $file) {
if (!$file->isFile()) {
continue;
}
$output->writeln('Found '.$file->getRelativePathname());
$command = $this->getApplication()->find('mongodb:migrations:migrate');
$helperSet = $command->getHelperSet();
$helperSet->set($this->documentManager, 'dm');
$command->setHelperSet($helperSet);
$configuration = $this->getConfiguration($file->getPathname(), $output);
self::injectContainerToMigrations($this->container, $configuration->getMigrations());
$command->setMigrationConfiguration($configuration);
$arguments = $input->getArguments();
$arguments['command'] = 'mongodb:migrations:migrate';
$arguments['--configuration'] = $file->getPathname();
$migrateInput = new ArrayInput($arguments);
$migrateInput->setInteractive($input->isInteractive());
$returnCode = $command->run($migrateInput, $output);
if ($returnCode !== 0) {
$this->errors[] = sprintf(
'Calling mongodb:migrations:migrate failed for %s',
$file->getRelativePathname()
);
}
}
if (!empty($this->errors)) {
$output->writeln(
sprintf('<error>%s</error>', implode(PHP_EOL, $this->errors))
);
return -1;
}
return 0;
} | php | public function execute(InputInterface $input, OutputInterface $output)
{
// graviton root
$baseDir = __DIR__.'/../../../';
// vendorized? - go back some more..
if (strpos($baseDir, '/vendor/') !== false) {
$baseDir .= '../../../';
}
$this->finder
->in($baseDir)
->path('Resources/config')
->name('/migrations.(xml|yml)/')
->files();
foreach ($this->finder as $file) {
if (!$file->isFile()) {
continue;
}
$output->writeln('Found '.$file->getRelativePathname());
$command = $this->getApplication()->find('mongodb:migrations:migrate');
$helperSet = $command->getHelperSet();
$helperSet->set($this->documentManager, 'dm');
$command->setHelperSet($helperSet);
$configuration = $this->getConfiguration($file->getPathname(), $output);
self::injectContainerToMigrations($this->container, $configuration->getMigrations());
$command->setMigrationConfiguration($configuration);
$arguments = $input->getArguments();
$arguments['command'] = 'mongodb:migrations:migrate';
$arguments['--configuration'] = $file->getPathname();
$migrateInput = new ArrayInput($arguments);
$migrateInput->setInteractive($input->isInteractive());
$returnCode = $command->run($migrateInput, $output);
if ($returnCode !== 0) {
$this->errors[] = sprintf(
'Calling mongodb:migrations:migrate failed for %s',
$file->getRelativePathname()
);
}
}
if (!empty($this->errors)) {
$output->writeln(
sprintf('<error>%s</error>', implode(PHP_EOL, $this->errors))
);
return -1;
}
return 0;
} | [
"public",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"// graviton root",
"$",
"baseDir",
"=",
"__DIR__",
".",
"'/../../../'",
";",
"// vendorized? - go back some more..",
"if",
"(",
"strpos",
"(",
"... | call execute on found commands
@param InputInterface $input user input
@param OutputInterface $output command output
@return void | [
"call",
"execute",
"on",
"found",
"commands"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/MigrationBundle/Command/MongodbMigrateCommand.php#L90-L147 | train |
libgraviton/graviton | src/Graviton/MigrationBundle/Command/MongodbMigrateCommand.php | MongodbMigrateCommand.getConfiguration | private function getConfiguration($filepath, $output)
{
$outputWriter = new OutputWriter(
function ($message) use ($output) {
return $output->writeln($message);
}
);
$info = pathinfo($filepath);
$namespace = 'AntiMattr\MongoDB\Migrations\Configuration';
$class = $info['extension'] === 'xml' ? 'XmlConfiguration' : 'YamlConfiguration';
$class = sprintf('%s\%s', $namespace, $class);
$configuration = new $class($this->documentManager->getDocumentManager()->getConnection(), $outputWriter);
// register databsae name before loading to ensure that loading does not fail
$configuration->setMigrationsDatabaseName($this->databaseName);
// load additional config from migrations.(yml|xml)
$configuration->load($filepath);
return $configuration;
} | php | private function getConfiguration($filepath, $output)
{
$outputWriter = new OutputWriter(
function ($message) use ($output) {
return $output->writeln($message);
}
);
$info = pathinfo($filepath);
$namespace = 'AntiMattr\MongoDB\Migrations\Configuration';
$class = $info['extension'] === 'xml' ? 'XmlConfiguration' : 'YamlConfiguration';
$class = sprintf('%s\%s', $namespace, $class);
$configuration = new $class($this->documentManager->getDocumentManager()->getConnection(), $outputWriter);
// register databsae name before loading to ensure that loading does not fail
$configuration->setMigrationsDatabaseName($this->databaseName);
// load additional config from migrations.(yml|xml)
$configuration->load($filepath);
return $configuration;
} | [
"private",
"function",
"getConfiguration",
"(",
"$",
"filepath",
",",
"$",
"output",
")",
"{",
"$",
"outputWriter",
"=",
"new",
"OutputWriter",
"(",
"function",
"(",
"$",
"message",
")",
"use",
"(",
"$",
"output",
")",
"{",
"return",
"$",
"output",
"->",... | get configration object for migration script
This is based on antromattr/mongodb-migartion code but extends it so we can inject
non local stuff centrally.
@param string $filepath path to configuration file
@param Output $output ouput interface need by config parser to do stuff
@return AntiMattr\MongoDB\Migrations\Configuration\Configuration | [
"get",
"configration",
"object",
"for",
"migration",
"script"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/MigrationBundle/Command/MongodbMigrateCommand.php#L160-L181 | train |
libgraviton/graviton | src/Graviton/FileBundle/Manager/RequestManager.php | RequestManager.updateFileRequest | public function updateFileRequest(Request $request)
{
$original = $this->requestStack->getMasterRequest();
$input = $original ? $original->getContent() : false;
if (!$input) {
return $request;
}
$part = new Part((string) $request);
if ($part->isMultiPart()) {
// do we have metadata? for a multipart form
$metadata = $part->getPartsByName('metadata');
if (is_array($metadata) && !empty($metadata)) {
$request->request->set('metadata', $metadata[0]->getBody());
}
// the file itself
$upload = $part->getPartsByName('upload');
if (is_array($upload) && !empty($upload)) {
$uploadPart = $upload[0];
$file = $this->extractFileFromString(
$uploadPart->getBody(),
$uploadPart->getFileName()
);
$request->files->add([$file]);
}
} elseif ((strpos($request->headers->get('Content-Type'), 'application/json') !== false)
&& $json = json_decode($part->getBody(), true)
) {
// Type json and can be parsed
$request->request->set('metadata', json_encode($json));
} else {
// Anything else should be saved as file
$file = $this->extractFileFromString($part->getBody());
if ($file) {
$request->files->add([$file]);
}
}
return $request;
} | php | public function updateFileRequest(Request $request)
{
$original = $this->requestStack->getMasterRequest();
$input = $original ? $original->getContent() : false;
if (!$input) {
return $request;
}
$part = new Part((string) $request);
if ($part->isMultiPart()) {
// do we have metadata? for a multipart form
$metadata = $part->getPartsByName('metadata');
if (is_array($metadata) && !empty($metadata)) {
$request->request->set('metadata', $metadata[0]->getBody());
}
// the file itself
$upload = $part->getPartsByName('upload');
if (is_array($upload) && !empty($upload)) {
$uploadPart = $upload[0];
$file = $this->extractFileFromString(
$uploadPart->getBody(),
$uploadPart->getFileName()
);
$request->files->add([$file]);
}
} elseif ((strpos($request->headers->get('Content-Type'), 'application/json') !== false)
&& $json = json_decode($part->getBody(), true)
) {
// Type json and can be parsed
$request->request->set('metadata', json_encode($json));
} else {
// Anything else should be saved as file
$file = $this->extractFileFromString($part->getBody());
if ($file) {
$request->files->add([$file]);
}
}
return $request;
} | [
"public",
"function",
"updateFileRequest",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"original",
"=",
"$",
"this",
"->",
"requestStack",
"->",
"getMasterRequest",
"(",
")",
";",
"$",
"input",
"=",
"$",
"original",
"?",
"$",
"original",
"->",
"getConte... | Simple RAW http request parser.
Ideal for PUT requests where PUT is streamed but you still need the data.
@param Request $request Sf data request
@return Request | [
"Simple",
"RAW",
"http",
"request",
"parser",
".",
"Ideal",
"for",
"PUT",
"requests",
"where",
"PUT",
"is",
"streamed",
"but",
"you",
"still",
"need",
"the",
"data",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/FileBundle/Manager/RequestManager.php#L44-L88 | train |
libgraviton/graviton | src/Graviton/FileBundle/Manager/RequestManager.php | RequestManager.extractFileFromString | private function extractFileFromString($fileContent, $originalFileName = null)
{
$tmpName = $fileName = uniqid(true);
if (!is_null($originalFileName)) {
$fileName = $originalFileName;
}
$dir = ini_get('upload_tmp_dir');
$dir = (empty($dir)) ? sys_get_temp_dir() : $dir;
$tmpFile = $dir . DIRECTORY_SEPARATOR . $tmpName;
// create temporary file;
(new Filesystem())->dumpFile($tmpFile, $fileContent);
$file = new File($tmpFile);
return new UploadedFile(
$file->getRealPath(),
$fileName,
$file->getMimeType(),
$file->getSize()
);
} | php | private function extractFileFromString($fileContent, $originalFileName = null)
{
$tmpName = $fileName = uniqid(true);
if (!is_null($originalFileName)) {
$fileName = $originalFileName;
}
$dir = ini_get('upload_tmp_dir');
$dir = (empty($dir)) ? sys_get_temp_dir() : $dir;
$tmpFile = $dir . DIRECTORY_SEPARATOR . $tmpName;
// create temporary file;
(new Filesystem())->dumpFile($tmpFile, $fileContent);
$file = new File($tmpFile);
return new UploadedFile(
$file->getRealPath(),
$fileName,
$file->getMimeType(),
$file->getSize()
);
} | [
"private",
"function",
"extractFileFromString",
"(",
"$",
"fileContent",
",",
"$",
"originalFileName",
"=",
"null",
")",
"{",
"$",
"tmpName",
"=",
"$",
"fileName",
"=",
"uniqid",
"(",
"true",
")",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"originalFileName... | Extracts file data from request content
@param string $fileContent the file content
@param string $originalFileName an overriding original file name
@return false|UploadedFile | [
"Extracts",
"file",
"data",
"from",
"request",
"content"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/FileBundle/Manager/RequestManager.php#L98-L120 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/GravitonDocumentBundle.php | GravitonDocumentBundle.boot | public function boot()
{
$extRefConverter = $this->container->get('graviton.document.service.extrefconverter');
$customType = Type::getType('hash');
$customType->setExtRefConverter($extRefConverter);
} | php | public function boot()
{
$extRefConverter = $this->container->get('graviton.document.service.extrefconverter');
$customType = Type::getType('hash');
$customType->setExtRefConverter($extRefConverter);
} | [
"public",
"function",
"boot",
"(",
")",
"{",
"$",
"extRefConverter",
"=",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'graviton.document.service.extrefconverter'",
")",
";",
"$",
"customType",
"=",
"Type",
"::",
"getType",
"(",
"'hash'",
")",
";",
"$"... | boot bundle function
@return void | [
"boot",
"bundle",
"function"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/GravitonDocumentBundle.php#L126-L131 | train |
libgraviton/graviton | src/Graviton/CoreBundle/Compiler/VersionCompilerPass.php | VersionCompilerPass.process | public function process(ContainerBuilder $container)
{
$rootDir = $container->getParameter('kernel.root_dir');
if (strpos($rootDir, 'vendor') !== false) {
$configurationFile = $rootDir.'/../../../../app';
} else {
$configurationFile = $rootDir;
}
$configurationFile .= '/config/version_service.yml';
if (!file_exists($configurationFile)) {
throw new \LogicException(
'Could not read version configuration file "'.$configurationFile.'"'
);
}
$config = Yaml::parseFile($configurationFile);
$versionInformation = [
'self' => 'unknown'
];
if (isset($config['selfName'])) {
$versionInformation['self'] = $this->getPackageVersion($config['selfName']);
}
if (isset($config['desiredVersions']) && is_array($config['desiredVersions'])) {
foreach ($config['desiredVersions'] as $name) {
$versionInformation[$name] = $this->getPackageVersion($name);
}
}
// for version header
$versionHeader = '';
foreach ($versionInformation as $name => $version) {
$versionHeader .= $name . ': ' . $version . '; ';
}
$container->setParameter(
'graviton.core.version.data',
$versionInformation
);
$container->setParameter(
'graviton.core.version.header',
trim($versionHeader)
);
} | php | public function process(ContainerBuilder $container)
{
$rootDir = $container->getParameter('kernel.root_dir');
if (strpos($rootDir, 'vendor') !== false) {
$configurationFile = $rootDir.'/../../../../app';
} else {
$configurationFile = $rootDir;
}
$configurationFile .= '/config/version_service.yml';
if (!file_exists($configurationFile)) {
throw new \LogicException(
'Could not read version configuration file "'.$configurationFile.'"'
);
}
$config = Yaml::parseFile($configurationFile);
$versionInformation = [
'self' => 'unknown'
];
if (isset($config['selfName'])) {
$versionInformation['self'] = $this->getPackageVersion($config['selfName']);
}
if (isset($config['desiredVersions']) && is_array($config['desiredVersions'])) {
foreach ($config['desiredVersions'] as $name) {
$versionInformation[$name] = $this->getPackageVersion($name);
}
}
// for version header
$versionHeader = '';
foreach ($versionInformation as $name => $version) {
$versionHeader .= $name . ': ' . $version . '; ';
}
$container->setParameter(
'graviton.core.version.data',
$versionInformation
);
$container->setParameter(
'graviton.core.version.header',
trim($versionHeader)
);
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"rootDir",
"=",
"$",
"container",
"->",
"getParameter",
"(",
"'kernel.root_dir'",
")",
";",
"if",
"(",
"strpos",
"(",
"$",
"rootDir",
",",
"'vendor'",
")",
"!==",
"f... | add version information of packages to the container
@param ContainerBuilder $container Container
@return void | [
"add",
"version",
"information",
"of",
"packages",
"to",
"the",
"container"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Compiler/VersionCompilerPass.php#L41-L88 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/Listener/DocumentVersionListener.php | DocumentVersionListener.updateCounter | private function updateCounter(ModelEvent $event, $action)
{
if (!$this->constraint->isVersioningService()) {
return;
}
$qb = $this->documentManager->createQueryBuilder($event->getCollectionClass());
if ('update' == $action) {
$qb->findAndUpdate()
->field('id')->equals($event->getCollectionId())
->field(VersionServiceConstraint::FIELD_NAME)->inc(1)
->getQuery()->execute();
} else {
$qb->findAndUpdate()
->field('id')->equals($event->getCollectionId())
->field(VersionServiceConstraint::FIELD_NAME)->set(1)
->getQuery()->execute();
}
} | php | private function updateCounter(ModelEvent $event, $action)
{
if (!$this->constraint->isVersioningService()) {
return;
}
$qb = $this->documentManager->createQueryBuilder($event->getCollectionClass());
if ('update' == $action) {
$qb->findAndUpdate()
->field('id')->equals($event->getCollectionId())
->field(VersionServiceConstraint::FIELD_NAME)->inc(1)
->getQuery()->execute();
} else {
$qb->findAndUpdate()
->field('id')->equals($event->getCollectionId())
->field(VersionServiceConstraint::FIELD_NAME)->set(1)
->getQuery()->execute();
}
} | [
"private",
"function",
"updateCounter",
"(",
"ModelEvent",
"$",
"event",
",",
"$",
"action",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"constraint",
"->",
"isVersioningService",
"(",
")",
")",
"{",
"return",
";",
"}",
"$",
"qb",
"=",
"$",
"this",
... | Update Counter for all new saved items
@param ModelEvent $event Object event
@param string $action What is to be done
@return void | [
"Update",
"Counter",
"for",
"all",
"new",
"saved",
"items"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Listener/DocumentVersionListener.php#L68-L86 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/Service/SolrQuery.php | SolrQuery.isConfigured | public function isConfigured()
{
if (!empty($this->urlParts) && isset($this->solrMap[$this->className])) {
return true;
}
return false;
} | php | public function isConfigured()
{
if (!empty($this->urlParts) && isset($this->solrMap[$this->className])) {
return true;
}
return false;
} | [
"public",
"function",
"isConfigured",
"(",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"urlParts",
")",
"&&",
"isset",
"(",
"$",
"this",
"->",
"solrMap",
"[",
"$",
"this",
"->",
"className",
"]",
")",
")",
"{",
"return",
"true",
";",... | returns true if solr is configured currently, false otherwise
@return bool if solr is configured | [
"returns",
"true",
"if",
"solr",
"is",
"configured",
"currently",
"false",
"otherwise"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Service/SolrQuery.php#L148-L154 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/Service/SolrQuery.php | SolrQuery.query | public function query(SearchNode $node, LimitNode $limitNode = null)
{
$client = $this->getClient();
$query = $client->createQuery($client::QUERY_SELECT);
// set the weights
$query->getEDisMax()->setQueryFields($this->solrMap[$this->className]);
$query->setQuery($this->getSearchTerm($node));
if ($limitNode instanceof LimitNode) {
$query->setStart($limitNode->getOffset())->setRows($limitNode->getLimit());
} else {
$query->setStart(0)->setRows($this->paginationDefaultLimit);
}
$query->setFields(['id']);
$result = $client->select($query);
if ($this->requestStack->getCurrentRequest() instanceof Request) {
$this->requestStack->getCurrentRequest()->attributes->set('totalCount', $result->getNumFound());
$this->requestStack->getCurrentRequest()->attributes->set('X-Search-Source', 'solr');
}
$idList = [];
foreach ($result as $document) {
if (isset($document->id)) {
$idList[] = (string) $document->id;
} elseif (isset($document->_id)) {
$idList[] = (string) $document->_id;
}
}
return $idList;
} | php | public function query(SearchNode $node, LimitNode $limitNode = null)
{
$client = $this->getClient();
$query = $client->createQuery($client::QUERY_SELECT);
// set the weights
$query->getEDisMax()->setQueryFields($this->solrMap[$this->className]);
$query->setQuery($this->getSearchTerm($node));
if ($limitNode instanceof LimitNode) {
$query->setStart($limitNode->getOffset())->setRows($limitNode->getLimit());
} else {
$query->setStart(0)->setRows($this->paginationDefaultLimit);
}
$query->setFields(['id']);
$result = $client->select($query);
if ($this->requestStack->getCurrentRequest() instanceof Request) {
$this->requestStack->getCurrentRequest()->attributes->set('totalCount', $result->getNumFound());
$this->requestStack->getCurrentRequest()->attributes->set('X-Search-Source', 'solr');
}
$idList = [];
foreach ($result as $document) {
if (isset($document->id)) {
$idList[] = (string) $document->id;
} elseif (isset($document->_id)) {
$idList[] = (string) $document->_id;
}
}
return $idList;
} | [
"public",
"function",
"query",
"(",
"SearchNode",
"$",
"node",
",",
"LimitNode",
"$",
"limitNode",
"=",
"null",
")",
"{",
"$",
"client",
"=",
"$",
"this",
"->",
"getClient",
"(",
")",
";",
"$",
"query",
"=",
"$",
"client",
"->",
"createQuery",
"(",
"... | executes the search on solr using the rql parsing nodes.
@param SearchNode $node search node
@param LimitNode|null $limitNode limit node
@return array an array of just record ids (the ids of the matching documents in solr) | [
"executes",
"the",
"search",
"on",
"solr",
"using",
"the",
"rql",
"parsing",
"nodes",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Service/SolrQuery.php#L164-L200 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/Service/SolrQuery.php | SolrQuery.getSearchTerm | private function getSearchTerm(SearchNode $node)
{
$fullTerm = $node->getSearchQuery();
foreach ($this->fullTermPatterns as $pattern) {
if (preg_match($pattern, $fullTerm, $matches) === 1) {
return '"'.$fullTerm.'"';
}
}
if ($this->andifyTerms) {
$glue = 'AND';
} else {
$glue = '';
}
$i = 0;
$hasPreviousOperator = false;
$fullSearchElements = [];
foreach (explode(' ', $node->getSearchQuery()) as $term) {
$i++;
// is this an operator?
if (array_search($term, $this->queryOperators) !== false) {
$fullSearchElements[] = $term;
$hasPreviousOperator = true;
continue;
}
$singleTerm = $this->getSingleTerm($term);
if ($i > 1 && $hasPreviousOperator == false && !empty($glue)) {
$fullSearchElements[] = $glue;
} else {
$hasPreviousOperator = false;
}
$fullSearchElements[] = $singleTerm;
}
return implode(' ', $fullSearchElements);
} | php | private function getSearchTerm(SearchNode $node)
{
$fullTerm = $node->getSearchQuery();
foreach ($this->fullTermPatterns as $pattern) {
if (preg_match($pattern, $fullTerm, $matches) === 1) {
return '"'.$fullTerm.'"';
}
}
if ($this->andifyTerms) {
$glue = 'AND';
} else {
$glue = '';
}
$i = 0;
$hasPreviousOperator = false;
$fullSearchElements = [];
foreach (explode(' ', $node->getSearchQuery()) as $term) {
$i++;
// is this an operator?
if (array_search($term, $this->queryOperators) !== false) {
$fullSearchElements[] = $term;
$hasPreviousOperator = true;
continue;
}
$singleTerm = $this->getSingleTerm($term);
if ($i > 1 && $hasPreviousOperator == false && !empty($glue)) {
$fullSearchElements[] = $glue;
} else {
$hasPreviousOperator = false;
}
$fullSearchElements[] = $singleTerm;
}
return implode(' ', $fullSearchElements);
} | [
"private",
"function",
"getSearchTerm",
"(",
"SearchNode",
"$",
"node",
")",
"{",
"$",
"fullTerm",
"=",
"$",
"node",
"->",
"getSearchQuery",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"fullTermPatterns",
"as",
"$",
"pattern",
")",
"{",
"if",
"(",
... | returns the string search term to be used in the solr query
@param SearchNode $node the search node
@return string the composed search query | [
"returns",
"the",
"string",
"search",
"term",
"to",
"be",
"used",
"in",
"the",
"solr",
"query"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Service/SolrQuery.php#L209-L252 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/Service/SolrQuery.php | SolrQuery.getSingleTerm | private function getSingleTerm($term)
{
// we don't modify numbers
if (ctype_digit($term)) {
return '"'.$term.'"';
}
// formatted number?
$formatted = str_replace(
[
'-',
'.'
],
'',
$term
);
if (ctype_digit($formatted)) {
return '"'.$term.'"';
}
// everything that is only numbers *and* characters and at least 3 long, we don't fuzzy/wildcard
// thanks to https://stackoverflow.com/a/7684859/3762521
$pattern = '/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/';
if (strlen($term) > 3 && preg_match($pattern, $term, $matches) === 1) {
return '"'.$term.'"';
}
// is it a solr field query (like id:333)?
if (preg_match($this->fieldQueryPattern, $term) === 1) {
return $this->parseSolrFieldQuery($term);
}
// strings shorter then 5 chars (like hans) we wildcard, all others we make fuzzy
if (strlen($term) >= $this->solrFuzzyBridge) {
return $this->doAndNotPrefixSingleTerm($term, '~');
}
if (strlen($term) >= $this->solrWildcardBridge) {
return $this->doAndNotPrefixSingleTerm($term, '*');
}
return $term;
} | php | private function getSingleTerm($term)
{
// we don't modify numbers
if (ctype_digit($term)) {
return '"'.$term.'"';
}
// formatted number?
$formatted = str_replace(
[
'-',
'.'
],
'',
$term
);
if (ctype_digit($formatted)) {
return '"'.$term.'"';
}
// everything that is only numbers *and* characters and at least 3 long, we don't fuzzy/wildcard
// thanks to https://stackoverflow.com/a/7684859/3762521
$pattern = '/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/';
if (strlen($term) > 3 && preg_match($pattern, $term, $matches) === 1) {
return '"'.$term.'"';
}
// is it a solr field query (like id:333)?
if (preg_match($this->fieldQueryPattern, $term) === 1) {
return $this->parseSolrFieldQuery($term);
}
// strings shorter then 5 chars (like hans) we wildcard, all others we make fuzzy
if (strlen($term) >= $this->solrFuzzyBridge) {
return $this->doAndNotPrefixSingleTerm($term, '~');
}
if (strlen($term) >= $this->solrWildcardBridge) {
return $this->doAndNotPrefixSingleTerm($term, '*');
}
return $term;
} | [
"private",
"function",
"getSingleTerm",
"(",
"$",
"term",
")",
"{",
"// we don't modify numbers",
"if",
"(",
"ctype_digit",
"(",
"$",
"term",
")",
")",
"{",
"return",
"'\"'",
".",
"$",
"term",
".",
"'\"'",
";",
"}",
"// formatted number?",
"$",
"formatted",
... | returns a single term how to search. here we can apply custom logic to the user input string
@param string $term single search term
@return string modified search term | [
"returns",
"a",
"single",
"term",
"how",
"to",
"search",
".",
"here",
"we",
"can",
"apply",
"custom",
"logic",
"to",
"the",
"user",
"input",
"string"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Service/SolrQuery.php#L261-L303 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/Service/SolrQuery.php | SolrQuery.doAndNotPrefixSingleTerm | private function doAndNotPrefixSingleTerm($term, $modifier)
{
// already modifier there?
$last = substr($term, -1);
if ($last == '~' || $last == '*') {
// clean from term, override modifier from client
$modifier = $last;
$term = substr($term, 0, -1);
}
return sprintf(
'(%s OR %s%s)',
$term,
$term,
$modifier
);
} | php | private function doAndNotPrefixSingleTerm($term, $modifier)
{
// already modifier there?
$last = substr($term, -1);
if ($last == '~' || $last == '*') {
// clean from term, override modifier from client
$modifier = $last;
$term = substr($term, 0, -1);
}
return sprintf(
'(%s OR %s%s)',
$term,
$term,
$modifier
);
} | [
"private",
"function",
"doAndNotPrefixSingleTerm",
"(",
"$",
"term",
",",
"$",
"modifier",
")",
"{",
"// already modifier there?",
"$",
"last",
"=",
"substr",
"(",
"$",
"term",
",",
"-",
"1",
")",
";",
"if",
"(",
"$",
"last",
"==",
"'~'",
"||",
"$",
"l... | ORify a single term
@param string $term search term
@param string $modifier modified
@return string ORified query | [
"ORify",
"a",
"single",
"term"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Service/SolrQuery.php#L339-L355 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/Service/SolrQuery.php | SolrQuery.getClient | private function getClient()
{
$endpointConfig = $this->urlParts;
if (!isset($endpointConfig['path'])) {
$endpointConfig['path'] = '/';
}
if (substr($endpointConfig['path'], -1) != '/') {
$endpointConfig['path'] .= '/';
}
// find core name
$classnameParts = explode('\\', $this->className);
$endpointConfig['core'] = array_pop($classnameParts);
$endpointConfig['timeout'] = 10000;
$endpointConfig['key'] = 'local';
$this->solrClient->addEndpoint($endpointConfig);
$this->solrClient->setDefaultEndpoint($endpointConfig['key']);
return $this->solrClient;
} | php | private function getClient()
{
$endpointConfig = $this->urlParts;
if (!isset($endpointConfig['path'])) {
$endpointConfig['path'] = '/';
}
if (substr($endpointConfig['path'], -1) != '/') {
$endpointConfig['path'] .= '/';
}
// find core name
$classnameParts = explode('\\', $this->className);
$endpointConfig['core'] = array_pop($classnameParts);
$endpointConfig['timeout'] = 10000;
$endpointConfig['key'] = 'local';
$this->solrClient->addEndpoint($endpointConfig);
$this->solrClient->setDefaultEndpoint($endpointConfig['key']);
return $this->solrClient;
} | [
"private",
"function",
"getClient",
"(",
")",
"{",
"$",
"endpointConfig",
"=",
"$",
"this",
"->",
"urlParts",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"endpointConfig",
"[",
"'path'",
"]",
")",
")",
"{",
"$",
"endpointConfig",
"[",
"'path'",
"]",
"=",
... | returns the client to use for the current query
@return Client client | [
"returns",
"the",
"client",
"to",
"use",
"for",
"the",
"current",
"query"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Service/SolrQuery.php#L362-L384 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Transformation/BodyMapping.php | BodyMapping.transformResponse | public function transformResponse(Response $responseIn, Response $responseOut)
{
$responseOut->setContent(
json_encode($this->transformer->transform($responseIn->getContent(), $this->mapping))
);
} | php | public function transformResponse(Response $responseIn, Response $responseOut)
{
$responseOut->setContent(
json_encode($this->transformer->transform($responseIn->getContent(), $this->mapping))
);
} | [
"public",
"function",
"transformResponse",
"(",
"Response",
"$",
"responseIn",
",",
"Response",
"$",
"responseOut",
")",
"{",
"$",
"responseOut",
"->",
"setContent",
"(",
"json_encode",
"(",
"$",
"this",
"->",
"transformer",
"->",
"transform",
"(",
"$",
"respo... | Transforms a response
@param Response $responseIn The original response object
@param Response $responseOut The response object to transform
@return void | [
"Transforms",
"a",
"response"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Transformation/BodyMapping.php#L50-L55 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/Transformation/BodyMapping.php | BodyMapping.transformRequest | public function transformRequest(Request $requestIn, Request $requestOut)
{
$requestOut = Request::create(
$requestOut->getUri(),
$requestOut->getMethod(),
[],
[],
[],
[],
json_encode(
$this->transformer->transform(json_decode($requestIn->getContent()), $this->mapping)
)
);
return $requestOut;
} | php | public function transformRequest(Request $requestIn, Request $requestOut)
{
$requestOut = Request::create(
$requestOut->getUri(),
$requestOut->getMethod(),
[],
[],
[],
[],
json_encode(
$this->transformer->transform(json_decode($requestIn->getContent()), $this->mapping)
)
);
return $requestOut;
} | [
"public",
"function",
"transformRequest",
"(",
"Request",
"$",
"requestIn",
",",
"Request",
"$",
"requestOut",
")",
"{",
"$",
"requestOut",
"=",
"Request",
"::",
"create",
"(",
"$",
"requestOut",
"->",
"getUri",
"(",
")",
",",
"$",
"requestOut",
"->",
"get... | Transforms a request
@param Request $requestIn The original request object
@param Request $requestOut The request object to transform
@return Request The transformed request | [
"Transforms",
"a",
"request"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Transformation/BodyMapping.php#L64-L78 | train |
libgraviton/graviton | src/Graviton/RestBundle/Routing/Loader/ActionUtils.php | ActionUtils.getBaseFromService | private static function getBaseFromService($service, $serviceConfig)
{
if (isset($serviceConfig[0]['router-base']) && strlen($serviceConfig[0]['router-base']) > 0) {
$base = $serviceConfig[0]['router-base'] . '/';
} else {
$parts = explode('.', $service);
$entity = array_pop($parts);
$module = $parts[1];
$base = '/' . $module . '/' . $entity . '/';
}
return $base;
} | php | private static function getBaseFromService($service, $serviceConfig)
{
if (isset($serviceConfig[0]['router-base']) && strlen($serviceConfig[0]['router-base']) > 0) {
$base = $serviceConfig[0]['router-base'] . '/';
} else {
$parts = explode('.', $service);
$entity = array_pop($parts);
$module = $parts[1];
$base = '/' . $module . '/' . $entity . '/';
}
return $base;
} | [
"private",
"static",
"function",
"getBaseFromService",
"(",
"$",
"service",
",",
"$",
"serviceConfig",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"serviceConfig",
"[",
"0",
"]",
"[",
"'router-base'",
"]",
")",
"&&",
"strlen",
"(",
"$",
"serviceConfig",
"[",
... | Get entity name from service strings.
By convention the last part of the service string so far
makes up the entities name.
@param string $service (partial) service id
@param array $serviceConfig service configuration
@return string | [
"Get",
"entity",
"name",
"from",
"service",
"strings",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Routing/Loader/ActionUtils.php#L77-L91 | train |
libgraviton/graviton | src/Graviton/RestBundle/Routing/Loader/ActionUtils.php | ActionUtils.getRouteOptions | public static function getRouteOptions($service, $serviceConfig, array $parameters = [], $useIdPattern = false)
{
if ($useIdPattern) {
$parameters['id'] = self::ID_PATTERN;
}
return self::getRoute($service, 'OPTIONS', 'optionsAction', $serviceConfig, $parameters);
} | php | public static function getRouteOptions($service, $serviceConfig, array $parameters = [], $useIdPattern = false)
{
if ($useIdPattern) {
$parameters['id'] = self::ID_PATTERN;
}
return self::getRoute($service, 'OPTIONS', 'optionsAction', $serviceConfig, $parameters);
} | [
"public",
"static",
"function",
"getRouteOptions",
"(",
"$",
"service",
",",
"$",
"serviceConfig",
",",
"array",
"$",
"parameters",
"=",
"[",
"]",
",",
"$",
"useIdPattern",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"useIdPattern",
")",
"{",
"$",
"parameter... | Get route for OPTIONS requests
@param string $service service id
@param array $serviceConfig service configuration
@param array $parameters service params
@param boolean $useIdPattern generate route with id param
@return Route | [
"Get",
"route",
"for",
"OPTIONS",
"requests"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Routing/Loader/ActionUtils.php#L168-L174 | train |
libgraviton/graviton | src/Graviton/RestBundle/Routing/Loader/ActionUtils.php | ActionUtils.getCanonicalSchemaRoute | public static function getCanonicalSchemaRoute($service, $serviceConfig, $type = 'item', $option = false)
{
$pattern = self::getBaseFromService($service, $serviceConfig);
$pattern = '/schema' . $pattern . $type;
$action = 'schemaAction';
$method = 'GET';
if ($option !== false) {
$action = 'optionsAction';
$method = 'OPTIONS';
}
$defaults = array(
'_controller' => $service . ':' . $action,
'_format' => '~',
);
$route = new Route($pattern, $defaults, []);
$route->setMethods($method);
return $route;
} | php | public static function getCanonicalSchemaRoute($service, $serviceConfig, $type = 'item', $option = false)
{
$pattern = self::getBaseFromService($service, $serviceConfig);
$pattern = '/schema' . $pattern . $type;
$action = 'schemaAction';
$method = 'GET';
if ($option !== false) {
$action = 'optionsAction';
$method = 'OPTIONS';
}
$defaults = array(
'_controller' => $service . ':' . $action,
'_format' => '~',
);
$route = new Route($pattern, $defaults, []);
$route->setMethods($method);
return $route;
} | [
"public",
"static",
"function",
"getCanonicalSchemaRoute",
"(",
"$",
"service",
",",
"$",
"serviceConfig",
",",
"$",
"type",
"=",
"'item'",
",",
"$",
"option",
"=",
"false",
")",
"{",
"$",
"pattern",
"=",
"self",
"::",
"getBaseFromService",
"(",
"$",
"serv... | Get canonical route for schema requests
@param string $service service id
@param array $serviceConfig service configuration
@param string $type service type (item or collection)
@param boolean $option render a options route
@return Route | [
"Get",
"canonical",
"route",
"for",
"schema",
"requests"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Routing/Loader/ActionUtils.php#L204-L225 | train |
libgraviton/graviton | src/Graviton/I18nBundle/Service/I18nUtils.php | I18nUtils.findMatchingTranslatables | public function findMatchingTranslatables($value, $sourceLocale, $useWildCard = false)
{
// i need to use a queryBuilder as the repository doesn't let me do regex queries (i guess so..)
$builder = $this->manager->createQueryBuilder(Translation::class);
$builder
->field('language')->equals($sourceLocale);
if ($useWildCard === true) {
$value = new \MongoRegex($value);
}
/*
* we have 2 cases to match
* - 'translated' is set and matches
* - 'translated' is not present, so 'original' can match (as this is inserted 'virtually')
*/
$builder->addAnd(
$builder->expr()
->addOr(
$builder->expr()->field('localized')->equals($value)
)
->addOr(
$builder->expr()
->field('localized')->equals(null)
->field('original')->equals($value)
)
);
$query = $builder->getQuery();
return $query->execute()->toArray();
} | php | public function findMatchingTranslatables($value, $sourceLocale, $useWildCard = false)
{
// i need to use a queryBuilder as the repository doesn't let me do regex queries (i guess so..)
$builder = $this->manager->createQueryBuilder(Translation::class);
$builder
->field('language')->equals($sourceLocale);
if ($useWildCard === true) {
$value = new \MongoRegex($value);
}
/*
* we have 2 cases to match
* - 'translated' is set and matches
* - 'translated' is not present, so 'original' can match (as this is inserted 'virtually')
*/
$builder->addAnd(
$builder->expr()
->addOr(
$builder->expr()->field('localized')->equals($value)
)
->addOr(
$builder->expr()
->field('localized')->equals(null)
->field('original')->equals($value)
)
);
$query = $builder->getQuery();
return $query->execute()->toArray();
} | [
"public",
"function",
"findMatchingTranslatables",
"(",
"$",
"value",
",",
"$",
"sourceLocale",
",",
"$",
"useWildCard",
"=",
"false",
")",
"{",
"// i need to use a queryBuilder as the repository doesn't let me do regex queries (i guess so..)",
"$",
"builder",
"=",
"$",
"th... | This function allows to search for existing translations from a source
language, probably using a wildcard
@param string $value the translated string
@param string $sourceLocale a source locale
@param boolean $useWildCard if we should search wildcard or not
@return array matching Translatables | [
"This",
"function",
"allows",
"to",
"search",
"for",
"existing",
"translations",
"from",
"a",
"source",
"language",
"probably",
"using",
"a",
"wildcard"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Service/I18nUtils.php#L102-L133 | train |
libgraviton/graviton | src/Graviton/SecurityBundle/Authentication/SecurityAuthenticator.php | SecurityAuthenticator.authenticateToken | public function authenticateToken(
TokenInterface $token,
UserProviderInterface $userProvider,
$providerKey
) {
$username = $token->getCredentials();
$roles = array_map(array($this, 'objectRolesToArray'), $token->getRoles());
$user = false;
// If no username in Strategy, check if required.
if ($this->securityRequired && !$username) {
$this->logger->warning('Authentication key is required.');
throw new AuthenticationException('Authentication key is required.');
}
if ($username) {
if (in_array(SecurityUser::ROLE_SUBNET, $roles)) {
$this->logger->info('Authentication, subnet user IP address: ' . $token->getAttribute('ipAddress'));
$user = new SubnetUser($username);
} elseif ($user = $this->userProvider->loadUserByUsername($username)) {
$roles[] = SecurityUser::ROLE_CONSULTANT;
}
}
// If no user, try to fetch the test user, else check if anonymous is enabled
if (!$user) {
if ($this->testUsername && $user = $this->userProvider->loadUserByUsername($this->testUsername)) {
$this->logger->info('Authentication, test user: ' . $this->testUsername);
$roles[] = SecurityUser::ROLE_TEST;
} elseif ($this->allowAnonymous) {
$this->logger->info('Authentication, loading anonymous user.');
$user = new AnonymousUser();
$roles[] = SecurityUser::ROLE_ANONYMOUS;
}
}
/** @var SecurityUser $securityUser */
if ($user) {
$securityUser = new SecurityUser($user, $roles);
} else {
$this->logger->warning(sprintf('Authentication key "%s" could not be resolved.', $username));
throw new AuthenticationException(
sprintf('Authentication key "%s" could not be resolved.', $username)
);
}
return new PreAuthenticatedToken(
$securityUser,
$username,
$providerKey,
$securityUser->getRoles()
);
} | php | public function authenticateToken(
TokenInterface $token,
UserProviderInterface $userProvider,
$providerKey
) {
$username = $token->getCredentials();
$roles = array_map(array($this, 'objectRolesToArray'), $token->getRoles());
$user = false;
// If no username in Strategy, check if required.
if ($this->securityRequired && !$username) {
$this->logger->warning('Authentication key is required.');
throw new AuthenticationException('Authentication key is required.');
}
if ($username) {
if (in_array(SecurityUser::ROLE_SUBNET, $roles)) {
$this->logger->info('Authentication, subnet user IP address: ' . $token->getAttribute('ipAddress'));
$user = new SubnetUser($username);
} elseif ($user = $this->userProvider->loadUserByUsername($username)) {
$roles[] = SecurityUser::ROLE_CONSULTANT;
}
}
// If no user, try to fetch the test user, else check if anonymous is enabled
if (!$user) {
if ($this->testUsername && $user = $this->userProvider->loadUserByUsername($this->testUsername)) {
$this->logger->info('Authentication, test user: ' . $this->testUsername);
$roles[] = SecurityUser::ROLE_TEST;
} elseif ($this->allowAnonymous) {
$this->logger->info('Authentication, loading anonymous user.');
$user = new AnonymousUser();
$roles[] = SecurityUser::ROLE_ANONYMOUS;
}
}
/** @var SecurityUser $securityUser */
if ($user) {
$securityUser = new SecurityUser($user, $roles);
} else {
$this->logger->warning(sprintf('Authentication key "%s" could not be resolved.', $username));
throw new AuthenticationException(
sprintf('Authentication key "%s" could not be resolved.', $username)
);
}
return new PreAuthenticatedToken(
$securityUser,
$username,
$providerKey,
$securityUser->getRoles()
);
} | [
"public",
"function",
"authenticateToken",
"(",
"TokenInterface",
"$",
"token",
",",
"UserProviderInterface",
"$",
"userProvider",
",",
"$",
"providerKey",
")",
"{",
"$",
"username",
"=",
"$",
"token",
"->",
"getCredentials",
"(",
")",
";",
"$",
"roles",
"=",
... | Tries to authenticate the provided token
@param TokenInterface $token token to authenticate
@param UserProviderInterface $userProvider provider to auth against
@param string $providerKey key to auth with
@return PreAuthenticatedToken | [
"Tries",
"to",
"authenticate",
"the",
"provided",
"token"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SecurityBundle/Authentication/SecurityAuthenticator.php#L126-L178 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Generator/ResourceGenerator/XDynamicKey.php | XDynamicKey.prepareFunctionNames | private static function prepareFunctionNames($refMethods)
{
$fieldNames = explode('.', $refMethods);
$getters = [];
foreach ($fieldNames as $field) {
array_push($getters, 'get'.ucfirst($field));
}
return $getters;
} | php | private static function prepareFunctionNames($refMethods)
{
$fieldNames = explode('.', $refMethods);
$getters = [];
foreach ($fieldNames as $field) {
array_push($getters, 'get'.ucfirst($field));
}
return $getters;
} | [
"private",
"static",
"function",
"prepareFunctionNames",
"(",
"$",
"refMethods",
")",
"{",
"$",
"fieldNames",
"=",
"explode",
"(",
"'.'",
",",
"$",
"refMethods",
")",
";",
"$",
"getters",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"fieldNames",
"as",
"$",
... | prepares getter methods for every given field name
@param string $refMethods string containing "path" to the ref field
@return array | [
"prepares",
"getter",
"methods",
"for",
"every",
"given",
"field",
"name"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Generator/ResourceGenerator/XDynamicKey.php#L55-L65 | train |
libgraviton/graviton | src/Graviton/RestBundle/Routing/Loader/BasicLoader.php | BasicLoader.loadService | private function loadService($service, $serviceConfig)
{
list($app, $bundle, , $entity) = explode('.', $service);
$resource = implode('.', array($app, $bundle, 'rest', $entity));
$this->loadReadOnlyRoutes($service, $resource, $serviceConfig);
if (!($serviceConfig[0] && array_key_exists('read-only', $serviceConfig[0]))) {
$this->loadWriteRoutes($service, $resource, $serviceConfig);
}
} | php | private function loadService($service, $serviceConfig)
{
list($app, $bundle, , $entity) = explode('.', $service);
$resource = implode('.', array($app, $bundle, 'rest', $entity));
$this->loadReadOnlyRoutes($service, $resource, $serviceConfig);
if (!($serviceConfig[0] && array_key_exists('read-only', $serviceConfig[0]))) {
$this->loadWriteRoutes($service, $resource, $serviceConfig);
}
} | [
"private",
"function",
"loadService",
"(",
"$",
"service",
",",
"$",
"serviceConfig",
")",
"{",
"list",
"(",
"$",
"app",
",",
"$",
"bundle",
",",
",",
"$",
"entity",
")",
"=",
"explode",
"(",
"'.'",
",",
"$",
"service",
")",
";",
"$",
"resource",
"... | load routes for a single service
@param string $service service name
@param array $serviceConfig service configuration
@return void | [
"load",
"routes",
"for",
"a",
"single",
"service"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Routing/Loader/BasicLoader.php#L88-L97 | train |
libgraviton/graviton | src/Graviton/RestBundle/Routing/Loader/BasicLoader.php | BasicLoader.loadReadOnlyRoutes | public function loadReadOnlyRoutes($service, $resource, $serviceConfig)
{
$actionOptions = ActionUtils::getRouteOptions($service, $serviceConfig);
$this->routes->add($resource . '.options', $actionOptions);
$actionOptionsNoSlash = ActionUtils::getRouteOptions($service, $serviceConfig);
$actionOptionsNoSlash->setPath(substr($actionOptionsNoSlash->getPath(), 0, -1));
$this->routes->add($resource . '.optionsNoSlash', $actionOptionsNoSlash);
$actionHead = ActionUtils::getRouteHead($service, $serviceConfig);
$this->routes->add($resource . '.head', $actionHead);
$actionHead = ActionUtils::getRouteHead($service, $serviceConfig, [], true);
$this->routes->add($resource . '.idHead', $actionHead);
$actionGet = ActionUtils::getRouteGet($service, $serviceConfig);
$this->routes->add($resource . '.get', $actionGet);
$actionAll = ActionUtils::getRouteAll($service, $serviceConfig);
$this->routes->add($resource . '.all', $actionAll);
$actionOptions = ActionUtils::getCanonicalSchemaRoute($service, $serviceConfig, 'collection');
$this->routes->add($resource . '.canonicalSchema', $actionOptions);
$actionOptions = ActionUtils::getCanonicalSchemaRoute($service, $serviceConfig, 'collection', true);
$this->routes->add($resource . '.canonicalSchemaOptions', $actionOptions);
$actionOptions = ActionUtils::getCanonicalSchemaRoute($service, $serviceConfig);
$this->routes->add($resource . '.canonicalIdSchema', $actionOptions);
$actionOptions = ActionUtils::getCanonicalSchemaRoute($service, $serviceConfig, 'item', true);
$this->routes->add($resource . '.canonicalIdSchemaOptions', $actionOptions);
$actionOptions = ActionUtils::getRouteOptions($service, $serviceConfig, [], true);
$this->routes->add($resource . '.idOptions', $actionOptions);
} | php | public function loadReadOnlyRoutes($service, $resource, $serviceConfig)
{
$actionOptions = ActionUtils::getRouteOptions($service, $serviceConfig);
$this->routes->add($resource . '.options', $actionOptions);
$actionOptionsNoSlash = ActionUtils::getRouteOptions($service, $serviceConfig);
$actionOptionsNoSlash->setPath(substr($actionOptionsNoSlash->getPath(), 0, -1));
$this->routes->add($resource . '.optionsNoSlash', $actionOptionsNoSlash);
$actionHead = ActionUtils::getRouteHead($service, $serviceConfig);
$this->routes->add($resource . '.head', $actionHead);
$actionHead = ActionUtils::getRouteHead($service, $serviceConfig, [], true);
$this->routes->add($resource . '.idHead', $actionHead);
$actionGet = ActionUtils::getRouteGet($service, $serviceConfig);
$this->routes->add($resource . '.get', $actionGet);
$actionAll = ActionUtils::getRouteAll($service, $serviceConfig);
$this->routes->add($resource . '.all', $actionAll);
$actionOptions = ActionUtils::getCanonicalSchemaRoute($service, $serviceConfig, 'collection');
$this->routes->add($resource . '.canonicalSchema', $actionOptions);
$actionOptions = ActionUtils::getCanonicalSchemaRoute($service, $serviceConfig, 'collection', true);
$this->routes->add($resource . '.canonicalSchemaOptions', $actionOptions);
$actionOptions = ActionUtils::getCanonicalSchemaRoute($service, $serviceConfig);
$this->routes->add($resource . '.canonicalIdSchema', $actionOptions);
$actionOptions = ActionUtils::getCanonicalSchemaRoute($service, $serviceConfig, 'item', true);
$this->routes->add($resource . '.canonicalIdSchemaOptions', $actionOptions);
$actionOptions = ActionUtils::getRouteOptions($service, $serviceConfig, [], true);
$this->routes->add($resource . '.idOptions', $actionOptions);
} | [
"public",
"function",
"loadReadOnlyRoutes",
"(",
"$",
"service",
",",
"$",
"resource",
",",
"$",
"serviceConfig",
")",
"{",
"$",
"actionOptions",
"=",
"ActionUtils",
"::",
"getRouteOptions",
"(",
"$",
"service",
",",
"$",
"serviceConfig",
")",
";",
"$",
"thi... | generate ro routes
@param string $service service name
@param string $resource resource name
@param array $serviceConfig service configuration
@return void | [
"generate",
"ro",
"routes"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Routing/Loader/BasicLoader.php#L108-L144 | train |
libgraviton/graviton | src/Graviton/RestBundle/Routing/Loader/BasicLoader.php | BasicLoader.loadWriteRoutes | public function loadWriteRoutes($service, $resource, $serviceConfig)
{
$actionPost = ActionUtils::getRoutePost($service, $serviceConfig);
$this->routes->add($resource . '.post', $actionPost);
$actionPut = ActionUtils::getRoutePut($service, $serviceConfig);
$this->routes->add($resource . '.put', $actionPut);
$actionPostNoSlash = ActionUtils::getRoutePost($service, $serviceConfig);
$actionPostNoSlash->setPath(substr($actionPostNoSlash->getPath(), 0, -1));
$this->routes->add($resource . '.postNoSlash', $actionPostNoSlash);
$actionPatch = ActionUtils::getRoutePatch($service, $serviceConfig);
$this->routes->add($resource . '.patch', $actionPatch);
$actionDelete = ActionUtils::getRouteDelete($service, $serviceConfig);
$this->routes->add($resource . '.delete', $actionDelete);
} | php | public function loadWriteRoutes($service, $resource, $serviceConfig)
{
$actionPost = ActionUtils::getRoutePost($service, $serviceConfig);
$this->routes->add($resource . '.post', $actionPost);
$actionPut = ActionUtils::getRoutePut($service, $serviceConfig);
$this->routes->add($resource . '.put', $actionPut);
$actionPostNoSlash = ActionUtils::getRoutePost($service, $serviceConfig);
$actionPostNoSlash->setPath(substr($actionPostNoSlash->getPath(), 0, -1));
$this->routes->add($resource . '.postNoSlash', $actionPostNoSlash);
$actionPatch = ActionUtils::getRoutePatch($service, $serviceConfig);
$this->routes->add($resource . '.patch', $actionPatch);
$actionDelete = ActionUtils::getRouteDelete($service, $serviceConfig);
$this->routes->add($resource . '.delete', $actionDelete);
} | [
"public",
"function",
"loadWriteRoutes",
"(",
"$",
"service",
",",
"$",
"resource",
",",
"$",
"serviceConfig",
")",
"{",
"$",
"actionPost",
"=",
"ActionUtils",
"::",
"getRoutePost",
"(",
"$",
"service",
",",
"$",
"serviceConfig",
")",
";",
"$",
"this",
"->... | generate write routes
@param string $service service name
@param string $resource resource name
@param array $serviceConfig service configuration
@return void | [
"generate",
"write",
"routes"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Routing/Loader/BasicLoader.php#L155-L172 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Definition/JsonDefinitionField.php | JsonDefinitionField.getTypeDoctrine | public function getTypeDoctrine()
{
if (isset(self::$doctrineTypeMap[$this->getType()])) {
return self::$doctrineTypeMap[$this->getType()];
}
// our fallback default
return self::$doctrineTypeMap[self::TYPE_STRING];
} | php | public function getTypeDoctrine()
{
if (isset(self::$doctrineTypeMap[$this->getType()])) {
return self::$doctrineTypeMap[$this->getType()];
}
// our fallback default
return self::$doctrineTypeMap[self::TYPE_STRING];
} | [
"public",
"function",
"getTypeDoctrine",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"doctrineTypeMap",
"[",
"$",
"this",
"->",
"getType",
"(",
")",
"]",
")",
")",
"{",
"return",
"self",
"::",
"$",
"doctrineTypeMap",
"[",
"$",
"this",
... | Returns the field type in a doctrine-understandable way..
@return string Type | [
"Returns",
"the",
"field",
"type",
"in",
"a",
"doctrine",
"-",
"understandable",
"way",
".."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinitionField.php#L138-L146 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Definition/JsonDefinitionField.php | JsonDefinitionField.getType | public function getType()
{
if ($this->definition->getTranslatable()) {
return self::TYPE_TRANSLATABLE;
}
return strtolower($this->definition->getType());
} | php | public function getType()
{
if ($this->definition->getTranslatable()) {
return self::TYPE_TRANSLATABLE;
}
return strtolower($this->definition->getType());
} | [
"public",
"function",
"getType",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"definition",
"->",
"getTranslatable",
"(",
")",
")",
"{",
"return",
"self",
"::",
"TYPE_TRANSLATABLE",
";",
"}",
"return",
"strtolower",
"(",
"$",
"this",
"->",
"definition",
... | Returns the field type
@return string Type | [
"Returns",
"the",
"field",
"type"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinitionField.php#L153-L159 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.