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/AnalyticsBundle/Manager/ServiceManager.php
ServiceManager.getCacheKey
private function getCacheKey($schema) { return self::CACHE_KEY_SERVICES_PREFIX . $schema->getRoute() . sha1(serialize($this->requestStack->getCurrentRequest()->query->all())); }
php
private function getCacheKey($schema) { return self::CACHE_KEY_SERVICES_PREFIX . $schema->getRoute() . sha1(serialize($this->requestStack->getCurrentRequest()->query->all())); }
[ "private", "function", "getCacheKey", "(", "$", "schema", ")", "{", "return", "self", "::", "CACHE_KEY_SERVICES_PREFIX", ".", "$", "schema", "->", "getRoute", "(", ")", ".", "sha1", "(", "serialize", "(", "$", "this", "->", "requestStack", "->", "getCurrentR...
generate a cache key also based on query @param AnalyticModel $schema schema @return string cache key
[ "generate", "a", "cache", "key", "also", "based", "on", "query" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/AnalyticsBundle/Manager/ServiceManager.php#L204-L209
train
libgraviton/graviton
src/Graviton/AnalyticsBundle/Manager/ServiceManager.php
ServiceManager.getSchema
public function getSchema() { $serviceRoute = $this->requestStack->getCurrentRequest() ->get('service'); // Locate the schema definition $model = $this->getAnalyticModel($serviceRoute); return $model->getSchema(); }
php
public function getSchema() { $serviceRoute = $this->requestStack->getCurrentRequest() ->get('service'); // Locate the schema definition $model = $this->getAnalyticModel($serviceRoute); return $model->getSchema(); }
[ "public", "function", "getSchema", "(", ")", "{", "$", "serviceRoute", "=", "$", "this", "->", "requestStack", "->", "getCurrentRequest", "(", ")", "->", "get", "(", "'service'", ")", ";", "// Locate the schema definition", "$", "model", "=", "$", "this", "-...
Locate and display service definition schema @return mixed
[ "Locate", "and", "display", "service", "definition", "schema" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/AnalyticsBundle/Manager/ServiceManager.php#L216-L225
train
libgraviton/graviton
src/Graviton/AnalyticsBundle/Manager/ServiceManager.php
ServiceManager.getServiceParameters
private function getServiceParameters(AnalyticModel $model) { $params = []; if (!is_array($model->getParams())) { return $params; } foreach ($model->getParams() as $param) { if (!isset($param['name'])) { throw new \LogicException("Incorrect spec (no name) of param in analytics route " . $model->getRoute()); } $paramValue = $this->requestStack->getCurrentRequest()->query->get($param['name'], null); // default set? if (is_null($paramValue) && isset($param['default'])) { $paramValue = $param['default']; } // required missing? if (is_null($paramValue) && (isset($param['required']) && $param['required'] === true)) { throw new AnalyticUsageException( sprintf( "Missing parameter '%s' in analytics route '%s'", $param['name'], $model->getRoute() ) ); } if (!is_null($param['type']) && !is_null($paramValue)) { switch ($param['type']) { case "integer": $paramValue = intval($paramValue); // more than max? limit to max.. if (isset($param['max']) && is_numeric($param['max']) && intval($param['max']) < $paramValue) { $paramValue = intval($param['max']); } break; case "boolean": $paramValue = boolval($paramValue); break; case "array": $paramValue = explode(',', $paramValue); break; case "date": $paramValue = new UTCDateTime($this->dateConverter->getDateTimeFromString($paramValue)); break; case "regex": $paramValue = new Regex($paramValue, 'i'); break; case "mongoid": $paramValue = new \MongoId($paramValue); break; case "array<integer>": $paramValue = array_map('intval', explode(',', $paramValue)); break; case "array<boolean>": $paramValue = array_map('boolval', explode(',', $paramValue)); break; } } if (!is_null($paramValue)) { $params[$param['name']] = $paramValue; } } return $params; }
php
private function getServiceParameters(AnalyticModel $model) { $params = []; if (!is_array($model->getParams())) { return $params; } foreach ($model->getParams() as $param) { if (!isset($param['name'])) { throw new \LogicException("Incorrect spec (no name) of param in analytics route " . $model->getRoute()); } $paramValue = $this->requestStack->getCurrentRequest()->query->get($param['name'], null); // default set? if (is_null($paramValue) && isset($param['default'])) { $paramValue = $param['default']; } // required missing? if (is_null($paramValue) && (isset($param['required']) && $param['required'] === true)) { throw new AnalyticUsageException( sprintf( "Missing parameter '%s' in analytics route '%s'", $param['name'], $model->getRoute() ) ); } if (!is_null($param['type']) && !is_null($paramValue)) { switch ($param['type']) { case "integer": $paramValue = intval($paramValue); // more than max? limit to max.. if (isset($param['max']) && is_numeric($param['max']) && intval($param['max']) < $paramValue) { $paramValue = intval($param['max']); } break; case "boolean": $paramValue = boolval($paramValue); break; case "array": $paramValue = explode(',', $paramValue); break; case "date": $paramValue = new UTCDateTime($this->dateConverter->getDateTimeFromString($paramValue)); break; case "regex": $paramValue = new Regex($paramValue, 'i'); break; case "mongoid": $paramValue = new \MongoId($paramValue); break; case "array<integer>": $paramValue = array_map('intval', explode(',', $paramValue)); break; case "array<boolean>": $paramValue = array_map('boolval', explode(',', $paramValue)); break; } } if (!is_null($paramValue)) { $params[$param['name']] = $paramValue; } } return $params; }
[ "private", "function", "getServiceParameters", "(", "AnalyticModel", "$", "model", ")", "{", "$", "params", "=", "[", "]", ";", "if", "(", "!", "is_array", "(", "$", "model", "->", "getParams", "(", ")", ")", ")", "{", "return", "$", "params", ";", "...
returns the params as passed from the user @param AnalyticModel $model model @return array the params, converted as specified @throws AnalyticUsageException
[ "returns", "the", "params", "as", "passed", "from", "the", "user" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/AnalyticsBundle/Manager/ServiceManager.php#L235-L305
train
libgraviton/graviton
src/Graviton/RestBundle/GravitonRestBundle.php
GravitonRestBundle.build
public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new RestServicesCompilerPass); $container->addCompilerPass(new RqlQueryRoutesCompilerPass()); }
php
public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new RestServicesCompilerPass); $container->addCompilerPass(new RqlQueryRoutesCompilerPass()); }
[ "public", "function", "build", "(", "ContainerBuilder", "$", "container", ")", "{", "parent", "::", "build", "(", "$", "container", ")", ";", "$", "container", "->", "addCompilerPass", "(", "new", "RestServicesCompilerPass", ")", ";", "$", "container", "->", ...
load compiler pass rest route loader @param ContainerBuilder $container container builder @return void
[ "load", "compiler", "pass", "rest", "route", "loader" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/GravitonRestBundle.php#L47-L53
train
libgraviton/graviton
src/Graviton/RestBundle/Listener/JsonRequestListener.php
JsonRequestListener.onKernelRequest
public function onKernelRequest(RestEvent $event) { $request = $event->getRequest(); if ($request->headers->has('Accept')) { $format = $request->getFormat($request->headers->get('Accept')); if (!empty($format)) { $request->setRequestFormat($format); } } }
php
public function onKernelRequest(RestEvent $event) { $request = $event->getRequest(); if ($request->headers->has('Accept')) { $format = $request->getFormat($request->headers->get('Accept')); if (!empty($format)) { $request->setRequestFormat($format); } } }
[ "public", "function", "onKernelRequest", "(", "RestEvent", "$", "event", ")", "{", "$", "request", "=", "$", "event", "->", "getRequest", "(", ")", ";", "if", "(", "$", "request", "->", "headers", "->", "has", "(", "'Accept'", ")", ")", "{", "$", "fo...
Validate the json input to prevent errors in the following components @param RestEvent $event Event @return void|null
[ "Validate", "the", "json", "input", "to", "prevent", "errors", "in", "the", "following", "components" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Listener/JsonRequestListener.php#L24-L36
train
libgraviton/graviton
src/Graviton/RestBundle/Subscriber/RestEventSubscriber.php
RestEventSubscriber.onKernelRequest
public function onKernelRequest(GetResponseEvent $event, $name, EventDispatcherInterface $dispatcher) { $restEvent = $this->getEventObject($event); if ($restEvent instanceof RestEvent) { $dispatcher->dispatch("graviton.rest.request", $restEvent); } }
php
public function onKernelRequest(GetResponseEvent $event, $name, EventDispatcherInterface $dispatcher) { $restEvent = $this->getEventObject($event); if ($restEvent instanceof RestEvent) { $dispatcher->dispatch("graviton.rest.request", $restEvent); } }
[ "public", "function", "onKernelRequest", "(", "GetResponseEvent", "$", "event", ",", "$", "name", ",", "EventDispatcherInterface", "$", "dispatcher", ")", "{", "$", "restEvent", "=", "$", "this", "->", "getEventObject", "(", "$", "event", ")", ";", "if", "("...
Handler for kernel.request events @param GetResponseEvent $event Event @param string $name Event name @param EventDispatcherInterface $dispatcher Event dispatcher @return void
[ "Handler", "for", "kernel", ".", "request", "events" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Subscriber/RestEventSubscriber.php#L82-L88
train
libgraviton/graviton
src/Graviton/RestBundle/Subscriber/RestEventSubscriber.php
RestEventSubscriber.getEventObject
private function getEventObject(Event $event) { // get the service name list ($serviceName) = explode(":", $event->getRequest()->get('_controller')); // get the controller which handles this request if ($this->container->has($serviceName)) { $controller = $this->container->get($serviceName); $restEvent = $this->restEvent; $restEvent->setRequest($event->getRequest()); $restEvent->setResponse($this->response); $restEvent->setController($controller); $returnEvent = $restEvent; } else { $returnEvent = $event; } return $returnEvent; }
php
private function getEventObject(Event $event) { // get the service name list ($serviceName) = explode(":", $event->getRequest()->get('_controller')); // get the controller which handles this request if ($this->container->has($serviceName)) { $controller = $this->container->get($serviceName); $restEvent = $this->restEvent; $restEvent->setRequest($event->getRequest()); $restEvent->setResponse($this->response); $restEvent->setController($controller); $returnEvent = $restEvent; } else { $returnEvent = $event; } return $returnEvent; }
[ "private", "function", "getEventObject", "(", "Event", "$", "event", ")", "{", "// get the service name", "list", "(", "$", "serviceName", ")", "=", "explode", "(", "\":\"", ",", "$", "event", "->", "getRequest", "(", ")", "->", "get", "(", "'_controller'", ...
Get a RestEvent object -> put this in a factory @param Event $event Original event (kernel.request / kernel.response) @return RestEvent $restEvent
[ "Get", "a", "RestEvent", "object", "-", ">", "put", "this", "in", "a", "factory" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Subscriber/RestEventSubscriber.php#L97-L116
train
libgraviton/graviton
src/Graviton/ProxyBundle/Definition/ApiDefinition.php
ApiDefinition.hasEndpoint
public function hasEndpoint($endpoint) { $retVal = false; if (isset($this->endpoints)) { $retVal = in_array($endpoint, $this->endpoints); } return $retVal; }
php
public function hasEndpoint($endpoint) { $retVal = false; if (isset($this->endpoints)) { $retVal = in_array($endpoint, $this->endpoints); } return $retVal; }
[ "public", "function", "hasEndpoint", "(", "$", "endpoint", ")", "{", "$", "retVal", "=", "false", ";", "if", "(", "isset", "(", "$", "this", "->", "endpoints", ")", ")", "{", "$", "retVal", "=", "in_array", "(", "$", "endpoint", ",", "$", "this", "...
check if an endpoint exists @param string $endpoint endpoint @return boolean
[ "check", "if", "an", "endpoint", "exists" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Definition/ApiDefinition.php#L127-L135
train
libgraviton/graviton
src/Graviton/ProxyBundle/Definition/ApiDefinition.php
ApiDefinition.getEndpoints
public function getEndpoints($withHost = true, $prefix = null, $host = '', $withBasePath = true) { $endpoints = []; $basePath = ""; if ($withHost) { $basePath = (empty($host)) ? $this->getHost() : $host; } if (!empty($prefix)) { $basePath .= $prefix; } if ($withBasePath && isset($this->basePath)) { $basePath .= $this->basePath; } foreach ($this->endpoints as $endpoint) { $endpoints[] = $basePath.$endpoint; } return $endpoints; }
php
public function getEndpoints($withHost = true, $prefix = null, $host = '', $withBasePath = true) { $endpoints = []; $basePath = ""; if ($withHost) { $basePath = (empty($host)) ? $this->getHost() : $host; } if (!empty($prefix)) { $basePath .= $prefix; } if ($withBasePath && isset($this->basePath)) { $basePath .= $this->basePath; } foreach ($this->endpoints as $endpoint) { $endpoints[] = $basePath.$endpoint; } return $endpoints; }
[ "public", "function", "getEndpoints", "(", "$", "withHost", "=", "true", ",", "$", "prefix", "=", "null", ",", "$", "host", "=", "''", ",", "$", "withBasePath", "=", "true", ")", "{", "$", "endpoints", "=", "[", "]", ";", "$", "basePath", "=", "\"\...
get all defined API endpoints @param boolean $withHost url with hostname @param string $prefix add a prefix to the url (blub/endpoint/url) @param string $host Host to be used instead of the host defined in the swagger json @param bool $withBasePath Defines whether the API's base path should be included or not @return array
[ "get", "all", "defined", "API", "endpoints" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Definition/ApiDefinition.php#L147-L165
train
libgraviton/graviton
src/Graviton/ProxyBundle/Definition/ApiDefinition.php
ApiDefinition.getSchema
public function getSchema($endpoint) { //remove base path if ('/' !== $this->basePath) { $endpoint = str_replace($this->basePath, '', $endpoint); } $retVal = new \stdClass(); if (array_key_exists($endpoint, $this->schemes)) { $retVal = $this->schemes[$endpoint]; } return $retVal; }
php
public function getSchema($endpoint) { //remove base path if ('/' !== $this->basePath) { $endpoint = str_replace($this->basePath, '', $endpoint); } $retVal = new \stdClass(); if (array_key_exists($endpoint, $this->schemes)) { $retVal = $this->schemes[$endpoint]; } return $retVal; }
[ "public", "function", "getSchema", "(", "$", "endpoint", ")", "{", "//remove base path", "if", "(", "'/'", "!==", "$", "this", "->", "basePath", ")", "{", "$", "endpoint", "=", "str_replace", "(", "$", "this", "->", "basePath", ",", "''", ",", "$", "en...
get a schema for an endpoint @param string $endpoint endpoint @return \stdClass
[ "get", "a", "schema", "for", "an", "endpoint" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Definition/ApiDefinition.php#L187-L199
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Definition/JsonDefinition.php
JsonDefinition.hasController
public function hasController() { return $this->def->getService() !== null && $this->def->getService()->getRouterBase() !== null; }
php
public function hasController() { return $this->def->getService() !== null && $this->def->getService()->getRouterBase() !== null; }
[ "public", "function", "hasController", "(", ")", "{", "return", "$", "this", "->", "def", "->", "getService", "(", ")", "!==", "null", "&&", "$", "this", "->", "def", "->", "getService", "(", ")", "->", "getRouterBase", "(", ")", "!==", "null", ";", ...
Returns whether this definition requires the generation of a controller. normally yes, but sometimes not ;-) @return bool true if yes, false if no
[ "Returns", "whether", "this", "definition", "requires", "the", "generation", "of", "a", "controller", ".", "normally", "yes", "but", "sometimes", "not", ";", "-", ")" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinition.php#L94-L98
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Definition/JsonDefinition.php
JsonDefinition.isReadOnlyService
public function isReadOnlyService() { if ($this->def->getService() === null) { return false; } return $this->def->getService()->getReadOnly(); }
php
public function isReadOnlyService() { if ($this->def->getService() === null) { return false; } return $this->def->getService()->getReadOnly(); }
[ "public", "function", "isReadOnlyService", "(", ")", "{", "if", "(", "$", "this", "->", "def", "->", "getService", "(", ")", "===", "null", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "def", "->", "getService", "(", ")", "->",...
Returns whether this service is read-only @return bool true if yes, false if not
[ "Returns", "whether", "this", "service", "is", "read", "-", "only" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinition.php#L147-L154
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Definition/JsonDefinition.php
JsonDefinition.isVersionedService
public function isVersionedService() { if ($this->def->getService() === null || !$this->def->getService()->getVersioning()) { return false; } return (boolean) $this->def->getService()->getVersioning(); }
php
public function isVersionedService() { if ($this->def->getService() === null || !$this->def->getService()->getVersioning()) { return false; } return (boolean) $this->def->getService()->getVersioning(); }
[ "public", "function", "isVersionedService", "(", ")", "{", "if", "(", "$", "this", "->", "def", "->", "getService", "(", ")", "===", "null", "||", "!", "$", "this", "->", "def", "->", "getService", "(", ")", "->", "getVersioning", "(", ")", ")", "{",...
Returns whether this service is versioning @return bool true if yes, false if not
[ "Returns", "whether", "this", "service", "is", "versioning" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinition.php#L161-L168
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Definition/JsonDefinition.php
JsonDefinition.getRouterBase
public function getRouterBase() { if ($this->def->getService() === null || $this->def->getService()->getRouterBase() === null) { return false; } $routerBase = $this->def->getService()->getRouterBase(); if (substr($routerBase, 0, 1) !== '/') { $routerBase = '/' . $routerBase; } if (substr($routerBase, -1) === '/') { $routerBase = substr($routerBase, 0, -1); } return $routerBase; }
php
public function getRouterBase() { if ($this->def->getService() === null || $this->def->getService()->getRouterBase() === null) { return false; } $routerBase = $this->def->getService()->getRouterBase(); if (substr($routerBase, 0, 1) !== '/') { $routerBase = '/' . $routerBase; } if (substr($routerBase, -1) === '/') { $routerBase = substr($routerBase, 0, -1); } return $routerBase; }
[ "public", "function", "getRouterBase", "(", ")", "{", "if", "(", "$", "this", "->", "def", "->", "getService", "(", ")", "===", "null", "||", "$", "this", "->", "def", "->", "getService", "(", ")", "->", "getRouterBase", "(", ")", "===", "null", ")",...
Returns a router base path. false if default should be used. @return string router base, i.e. /bundle/name/
[ "Returns", "a", "router", "base", "path", ".", "false", "if", "default", "should", "be", "used", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinition.php#L215-L231
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Definition/JsonDefinition.php
JsonDefinition.getBaseController
public function getBaseController() { if ($this->def->getService() === null || $this->def->getService()->getBaseController() === null) { return 'RestController'; } return $this->def->getService()->getBaseController(); }
php
public function getBaseController() { if ($this->def->getService() === null || $this->def->getService()->getBaseController() === null) { return 'RestController'; } return $this->def->getService()->getBaseController(); }
[ "public", "function", "getBaseController", "(", ")", "{", "if", "(", "$", "this", "->", "def", "->", "getService", "(", ")", "===", "null", "||", "$", "this", "->", "def", "->", "getService", "(", ")", "->", "getBaseController", "(", ")", "===", "null"...
Returns the Controller classname this services' controller shout inherit. Defaults to the RestController of the RestBundle of course. @return string base controller
[ "Returns", "the", "Controller", "classname", "this", "services", "controller", "shout", "inherit", ".", "Defaults", "to", "the", "RestController", "of", "the", "RestBundle", "of", "course", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinition.php#L239-L247
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Definition/JsonDefinition.php
JsonDefinition.getParentService
public function getParentService() { if ($this->def->getService() === null || $this->def->getService()->getParent() === null) { return 'graviton.rest.controller'; } return $this->def->getService()->getParent(); }
php
public function getParentService() { if ($this->def->getService() === null || $this->def->getService()->getParent() === null) { return 'graviton.rest.controller'; } return $this->def->getService()->getParent(); }
[ "public", "function", "getParentService", "(", ")", "{", "if", "(", "$", "this", "->", "def", "->", "getService", "(", ")", "===", "null", "||", "$", "this", "->", "def", "->", "getService", "(", ")", "->", "getParent", "(", ")", "===", "null", ")", ...
Returns the parent service to use when adding the service xml Defaults to graviton.rest.controller @return string base controller
[ "Returns", "the", "parent", "service", "to", "use", "when", "adding", "the", "service", "xml" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinition.php#L256-L264
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Definition/JsonDefinition.php
JsonDefinition.getFields
public function getFields() { $hierarchy = []; foreach ($this->def->getTarget()->getFields() as $field) { $hierarchy = array_merge_recursive( $hierarchy, $this->createFieldHierarchyRecursive($field, $field->getName()) ); } $fields = []; /******* * CONDITIONAL GENERATED FIELD AREA * * so simplify things, you can put fields here that should be conditionally created by Graviton. * @TODO refactor into a FieldBuilder* type of thing where different builders can add fields conditionally. */ // Versioning field, for version control. if ($this->def->getService() && $this->def->getService()->getVersioning()) { $definition = new Schema\Field(); $constraint = new Constraint(); $constraint->setName('versioning'); $definition->setName(VersionServiceConstraint::FIELD_NAME)->setTitle('Version')->setType('int') ->setConstraints([$constraint]) ->setDescription('Document version. You need to send current version if you want to update.'); $fields['version'] = $this->processSimpleField('version', $definition); } /******* * add fields as defined in the definition file. */ foreach ($hierarchy as $name => $definition) { $fields[$name] = $this->processFieldHierarchyRecursive($name, $definition); } return $fields; }
php
public function getFields() { $hierarchy = []; foreach ($this->def->getTarget()->getFields() as $field) { $hierarchy = array_merge_recursive( $hierarchy, $this->createFieldHierarchyRecursive($field, $field->getName()) ); } $fields = []; /******* * CONDITIONAL GENERATED FIELD AREA * * so simplify things, you can put fields here that should be conditionally created by Graviton. * @TODO refactor into a FieldBuilder* type of thing where different builders can add fields conditionally. */ // Versioning field, for version control. if ($this->def->getService() && $this->def->getService()->getVersioning()) { $definition = new Schema\Field(); $constraint = new Constraint(); $constraint->setName('versioning'); $definition->setName(VersionServiceConstraint::FIELD_NAME)->setTitle('Version')->setType('int') ->setConstraints([$constraint]) ->setDescription('Document version. You need to send current version if you want to update.'); $fields['version'] = $this->processSimpleField('version', $definition); } /******* * add fields as defined in the definition file. */ foreach ($hierarchy as $name => $definition) { $fields[$name] = $this->processFieldHierarchyRecursive($name, $definition); } return $fields; }
[ "public", "function", "getFields", "(", ")", "{", "$", "hierarchy", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "def", "->", "getTarget", "(", ")", "->", "getFields", "(", ")", "as", "$", "field", ")", "{", "$", "hierarchy", "=", "array_...
Returns the field definition @return DefinitionElementInterface[] Fields
[ "Returns", "the", "field", "definition" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinition.php#L284-L323
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Definition/JsonDefinition.php
JsonDefinition.getRelations
public function getRelations() { if ($this->def->getTarget() === null) { return []; } $relations = []; foreach ($this->def->getTarget()->getRelations() as $relation) { $relations[$relation->getLocalProperty()] = $relation; } return $relations; }
php
public function getRelations() { if ($this->def->getTarget() === null) { return []; } $relations = []; foreach ($this->def->getTarget()->getRelations() as $relation) { $relations[$relation->getLocalProperty()] = $relation; } return $relations; }
[ "public", "function", "getRelations", "(", ")", "{", "if", "(", "$", "this", "->", "def", "->", "getTarget", "(", ")", "===", "null", ")", "{", "return", "[", "]", ";", "}", "$", "relations", "=", "[", "]", ";", "foreach", "(", "$", "this", "->",...
Get target relations which are explictly defined @return Schema\Relation[] relations
[ "Get", "target", "relations", "which", "are", "explictly", "defined" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinition.php#L408-L420
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Definition/JsonDefinition.php
JsonDefinition.getRelation
private function getRelation($field) { $relations = $this->getRelations(); return isset($relations[$field]) ? $relations[$field] : null; }
php
private function getRelation($field) { $relations = $this->getRelations(); return isset($relations[$field]) ? $relations[$field] : null; }
[ "private", "function", "getRelation", "(", "$", "field", ")", "{", "$", "relations", "=", "$", "this", "->", "getRelations", "(", ")", ";", "return", "isset", "(", "$", "relations", "[", "$", "field", "]", ")", "?", "$", "relations", "[", "$", "field...
Get relation by field name @param string $field Field name @return Schema\Relation|null
[ "Get", "relation", "by", "field", "name" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinition.php#L428-L432
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Definition/JsonDefinition.php
JsonDefinition.getSolrFields
public function getSolrFields() { $solr = $this->def->getSolr(); if (!$solr instanceof Solr) { return []; } $fields = []; foreach ($solr->getFields() as $field) { $fields[] = [ 'name' => $field->getName(), 'type' => $field->getType(), 'weight' => $field->getWeight() ]; } return $fields; }
php
public function getSolrFields() { $solr = $this->def->getSolr(); if (!$solr instanceof Solr) { return []; } $fields = []; foreach ($solr->getFields() as $field) { $fields[] = [ 'name' => $field->getName(), 'type' => $field->getType(), 'weight' => $field->getWeight() ]; } return $fields; }
[ "public", "function", "getSolrFields", "(", ")", "{", "$", "solr", "=", "$", "this", "->", "def", "->", "getSolr", "(", ")", ";", "if", "(", "!", "$", "solr", "instanceof", "Solr", ")", "{", "return", "[", "]", ";", "}", "$", "fields", "=", "[", ...
gets information about solr @return array|Schema\Solr
[ "gets", "information", "about", "solr" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinition.php#L467-L484
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Definition/JsonDefinition.php
JsonDefinition.isRecordOriginModifiable
public function isRecordOriginModifiable() { $retVal = false; if ($this->isRecordOriginFlagSet()) { $retVal = $this->def->getService()->getRecordOriginModifiable(); } return $retVal; }
php
public function isRecordOriginModifiable() { $retVal = false; if ($this->isRecordOriginFlagSet()) { $retVal = $this->def->getService()->getRecordOriginModifiable(); } return $retVal; }
[ "public", "function", "isRecordOriginModifiable", "(", ")", "{", "$", "retVal", "=", "false", ";", "if", "(", "$", "this", "->", "isRecordOriginFlagSet", "(", ")", ")", "{", "$", "retVal", "=", "$", "this", "->", "def", "->", "getService", "(", ")", "-...
Can record origin be modified @return bool
[ "Can", "record", "origin", "be", "modified" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinition.php#L505-L513
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Definition/JsonDefinition.php
JsonDefinition.isRecordOriginFlagSet
public function isRecordOriginFlagSet() { $retVal = false; if ($this->def->getService() !== null && is_object($this->def->getService()) && $this->def->getService()->getRecordOriginModifiable() !== null) { $retVal = true; } return $retVal; }
php
public function isRecordOriginFlagSet() { $retVal = false; if ($this->def->getService() !== null && is_object($this->def->getService()) && $this->def->getService()->getRecordOriginModifiable() !== null) { $retVal = true; } return $retVal; }
[ "public", "function", "isRecordOriginFlagSet", "(", ")", "{", "$", "retVal", "=", "false", ";", "if", "(", "$", "this", "->", "def", "->", "getService", "(", ")", "!==", "null", "&&", "is_object", "(", "$", "this", "->", "def", "->", "getService", "(",...
check if the RecordOriginModifiable flag is set @return bool
[ "check", "if", "the", "RecordOriginModifiable", "flag", "is", "set" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinition.php#L520-L530
train
libgraviton/graviton
src/Graviton/DocumentBundle/Serializer/Handler/DateHandler.php
DateHandler.deserializeDateTimeFromJson
public function deserializeDateTimeFromJson(JsonDeserializationVisitor $visitor, $data, array $type) { if (null === $data) { return null; } return parent::deserializeDateTimeFromJson( $visitor, $this->dateConverter->getDateTimeStringInFormat($data), $type ); }
php
public function deserializeDateTimeFromJson(JsonDeserializationVisitor $visitor, $data, array $type) { if (null === $data) { return null; } return parent::deserializeDateTimeFromJson( $visitor, $this->dateConverter->getDateTimeStringInFormat($data), $type ); }
[ "public", "function", "deserializeDateTimeFromJson", "(", "JsonDeserializationVisitor", "$", "visitor", ",", "$", "data", ",", "array", "$", "type", ")", "{", "if", "(", "null", "===", "$", "data", ")", "{", "return", "null", ";", "}", "return", "parent", ...
serialize datetime from json @param JsonDeserializationVisitor $visitor visitor @param string $data data @param array $type type @return \DateTime|null DateTime instance
[ "serialize", "datetime", "from", "json" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Serializer/Handler/DateHandler.php#L71-L82
train
libgraviton/graviton
src/Graviton/DocumentBundle/Serializer/Handler/DateHandler.php
DateHandler.serializeDateTime
public function serializeDateTime(VisitorInterface $visitor, \DateTime $date, array $type, Context $context) { return $visitor->visitString($this->dateConverter->formatDateTime($date), $type, $context); }
php
public function serializeDateTime(VisitorInterface $visitor, \DateTime $date, array $type, Context $context) { return $visitor->visitString($this->dateConverter->formatDateTime($date), $type, $context); }
[ "public", "function", "serializeDateTime", "(", "VisitorInterface", "$", "visitor", ",", "\\", "DateTime", "$", "date", ",", "array", "$", "type", ",", "Context", "$", "context", ")", "{", "return", "$", "visitor", "->", "visitString", "(", "$", "this", "-...
serialize datetime to json @param VisitorInterface $visitor visitor @param \DateTime $date data @param array $type type @param Context $context context @return string serialized date
[ "serialize", "datetime", "to", "json" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Serializer/Handler/DateHandler.php#L94-L97
train
libgraviton/graviton
src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php
DocumentMap.loadDoctrineClassMap
private function loadDoctrineClassMap(Finder $finder) { $classMap = []; foreach ($finder as $file) { $classMap = array_merge( $classMap, Yaml::parseFile($file) ); } // filter out superclasses $classMap = array_filter( $classMap, function ($classEntry) { return (!isset($classEntry['type']) || $classEntry['type'] != 'mappedSuperclass'); } ); return $classMap; }
php
private function loadDoctrineClassMap(Finder $finder) { $classMap = []; foreach ($finder as $file) { $classMap = array_merge( $classMap, Yaml::parseFile($file) ); } // filter out superclasses $classMap = array_filter( $classMap, function ($classEntry) { return (!isset($classEntry['type']) || $classEntry['type'] != 'mappedSuperclass'); } ); return $classMap; }
[ "private", "function", "loadDoctrineClassMap", "(", "Finder", "$", "finder", ")", "{", "$", "classMap", "=", "[", "]", ";", "foreach", "(", "$", "finder", "as", "$", "file", ")", "{", "$", "classMap", "=", "array_merge", "(", "$", "classMap", ",", "Yam...
Load doctrine class map @param Finder $finder Mapping finder @return array
[ "Load", "doctrine", "class", "map" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php#L210-L229
train
libgraviton/graviton
src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php
DocumentMap.loadSerializerClassMap
private function loadSerializerClassMap(Finder $finder) { $classMap = []; foreach ($finder as $file) { $document = new \DOMDocument(); $document->load($file); $xpath = new \DOMXPath($document); $classMap = array_reduce( iterator_to_array($xpath->query('//class')), function (array $classMap, \DOMElement $element) { $classMap[$element->getAttribute('name')] = $element; return $classMap; }, $classMap ); } return $classMap; }
php
private function loadSerializerClassMap(Finder $finder) { $classMap = []; foreach ($finder as $file) { $document = new \DOMDocument(); $document->load($file); $xpath = new \DOMXPath($document); $classMap = array_reduce( iterator_to_array($xpath->query('//class')), function (array $classMap, \DOMElement $element) { $classMap[$element->getAttribute('name')] = $element; return $classMap; }, $classMap ); } return $classMap; }
[ "private", "function", "loadSerializerClassMap", "(", "Finder", "$", "finder", ")", "{", "$", "classMap", "=", "[", "]", ";", "foreach", "(", "$", "finder", "as", "$", "file", ")", "{", "$", "document", "=", "new", "\\", "DOMDocument", "(", ")", ";", ...
Load serializer class map @param Finder $finder Mapping finder @return array
[ "Load", "serializer", "class", "map" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php#L237-L257
train
libgraviton/graviton
src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php
DocumentMap.loadSchemaClassMap
private function loadSchemaClassMap(Finder $finder) { $classMap = []; foreach ($finder as $file) { $schema = json_decode(file_get_contents($file), true); if (!isset($schema['x-documentClass'])) { continue; } foreach ($schema['required'] as $field) { $classMap[$schema['x-documentClass']][$field]['required'] = true; } foreach ($schema['searchable'] as $field) { $classMap[$schema['x-documentClass']][$field]['searchable'] = 1; } foreach ($schema['readOnlyFields'] as $field) { $classMap[$schema['x-documentClass']][$field]['readOnly'] = true; } // flags from fields if (is_array($schema['properties'])) { foreach ($schema['properties'] as $fieldName => $field) { if (isset($field['recordOriginException']) && $field['recordOriginException'] == true) { $classMap[$schema['x-documentClass']][$fieldName]['recordOriginException'] = true; } if (isset($field['x-restrictions'])) { $classMap[$schema['x-documentClass']][$fieldName]['restrictions'] = $field['x-restrictions']; } else { $classMap[$schema['x-documentClass']][$fieldName]['restrictions'] = []; } } } if (isset($schema['solr']) && is_array($schema['solr']) && !empty($schema['solr'])) { $classMap[$schema['x-documentClass']]['_base']['solr'] = $schema['solr']; } else { $classMap[$schema['x-documentClass']]['_base']['solr'] = []; } } return $classMap; }
php
private function loadSchemaClassMap(Finder $finder) { $classMap = []; foreach ($finder as $file) { $schema = json_decode(file_get_contents($file), true); if (!isset($schema['x-documentClass'])) { continue; } foreach ($schema['required'] as $field) { $classMap[$schema['x-documentClass']][$field]['required'] = true; } foreach ($schema['searchable'] as $field) { $classMap[$schema['x-documentClass']][$field]['searchable'] = 1; } foreach ($schema['readOnlyFields'] as $field) { $classMap[$schema['x-documentClass']][$field]['readOnly'] = true; } // flags from fields if (is_array($schema['properties'])) { foreach ($schema['properties'] as $fieldName => $field) { if (isset($field['recordOriginException']) && $field['recordOriginException'] == true) { $classMap[$schema['x-documentClass']][$fieldName]['recordOriginException'] = true; } if (isset($field['x-restrictions'])) { $classMap[$schema['x-documentClass']][$fieldName]['restrictions'] = $field['x-restrictions']; } else { $classMap[$schema['x-documentClass']][$fieldName]['restrictions'] = []; } } } if (isset($schema['solr']) && is_array($schema['solr']) && !empty($schema['solr'])) { $classMap[$schema['x-documentClass']]['_base']['solr'] = $schema['solr']; } else { $classMap[$schema['x-documentClass']]['_base']['solr'] = []; } } return $classMap; }
[ "private", "function", "loadSchemaClassMap", "(", "Finder", "$", "finder", ")", "{", "$", "classMap", "=", "[", "]", ";", "foreach", "(", "$", "finder", "as", "$", "file", ")", "{", "$", "schema", "=", "json_decode", "(", "file_get_contents", "(", "$", ...
Load schema class map @param Finder $finder Mapping finder @return array
[ "Load", "schema", "class", "map" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php#L265-L307
train
libgraviton/graviton
src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php
DocumentMap.getSerializerFields
private function getSerializerFields(\DOMElement $mapping) { $xpath = new \DOMXPath($mapping->ownerDocument); return array_map( function (\DOMElement $element) { return [ 'fieldName' => $element->getAttribute('name'), 'fieldType' => $this->getSerializerFieldType($element), 'exposedName' => $element->getAttribute('serialized-name') ?: $element->getAttribute('name'), 'readOnly' => $element->getAttribute('read-only') === 'true', 'searchable' => (int) $element->getAttribute('searchable') ]; }, iterator_to_array($xpath->query('property', $mapping)) ); }
php
private function getSerializerFields(\DOMElement $mapping) { $xpath = new \DOMXPath($mapping->ownerDocument); return array_map( function (\DOMElement $element) { return [ 'fieldName' => $element->getAttribute('name'), 'fieldType' => $this->getSerializerFieldType($element), 'exposedName' => $element->getAttribute('serialized-name') ?: $element->getAttribute('name'), 'readOnly' => $element->getAttribute('read-only') === 'true', 'searchable' => (int) $element->getAttribute('searchable') ]; }, iterator_to_array($xpath->query('property', $mapping)) ); }
[ "private", "function", "getSerializerFields", "(", "\\", "DOMElement", "$", "mapping", ")", "{", "$", "xpath", "=", "new", "\\", "DOMXPath", "(", "$", "mapping", "->", "ownerDocument", ")", ";", "return", "array_map", "(", "function", "(", "\\", "DOMElement"...
Get serializer fields @param \DOMElement $mapping Serializer XML mapping @return array
[ "Get", "serializer", "fields" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php#L315-L331
train
libgraviton/graviton
src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php
DocumentMap.getSerializerFieldType
private function getSerializerFieldType(\DOMElement $field) { if ($field->getAttribute('type')) { return $field->getAttribute('type'); } $xpath = new \DOMXPath($field->ownerDocument); $type = $xpath->query('type', $field)->item(0); return $type === null ? null : $type->nodeValue; }
php
private function getSerializerFieldType(\DOMElement $field) { if ($field->getAttribute('type')) { return $field->getAttribute('type'); } $xpath = new \DOMXPath($field->ownerDocument); $type = $xpath->query('type', $field)->item(0); return $type === null ? null : $type->nodeValue; }
[ "private", "function", "getSerializerFieldType", "(", "\\", "DOMElement", "$", "field", ")", "{", "if", "(", "$", "field", "->", "getAttribute", "(", "'type'", ")", ")", "{", "return", "$", "field", "->", "getAttribute", "(", "'type'", ")", ";", "}", "$"...
Get serializer field type @param \DOMElement $field Field node @return string|null
[ "Get", "serializer", "field", "type" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php#L339-L349
train
libgraviton/graviton
src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php
DocumentMap.getDoctrineFields
private function getDoctrineFields(array $mapping) { if (!isset($mapping['fields'])) { return []; } return array_map( function ($key, $value) { if (!isset($value['type'])) { $value['type'] = ''; } return [ 'name' => $key, 'type' => $value['type'] ]; }, array_keys($mapping['fields']), $mapping['fields'] ); }
php
private function getDoctrineFields(array $mapping) { if (!isset($mapping['fields'])) { return []; } return array_map( function ($key, $value) { if (!isset($value['type'])) { $value['type'] = ''; } return [ 'name' => $key, 'type' => $value['type'] ]; }, array_keys($mapping['fields']), $mapping['fields'] ); }
[ "private", "function", "getDoctrineFields", "(", "array", "$", "mapping", ")", "{", "if", "(", "!", "isset", "(", "$", "mapping", "[", "'fields'", "]", ")", ")", "{", "return", "[", "]", ";", "}", "return", "array_map", "(", "function", "(", "$", "ke...
Get doctrine document fields @param array $mapping Doctrine mapping @return array
[ "Get", "doctrine", "document", "fields" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php#L357-L377
train
libgraviton/graviton
src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php
DocumentMap.getRelationList
private function getRelationList($mapping, $suffix) { if (!isset($mapping['embed'.$suffix]) && !isset($mapping['reference'.$suffix])) { return []; } $relations = []; if (isset($mapping['embed'.$suffix])) { $relations = array_merge($relations, $mapping['embed'.$suffix]); } if (isset($mapping['reference'.$suffix])) { $relations = array_merge($relations, $mapping['reference'.$suffix]); } return array_map( function ($key, $value) { return [ 'name' => $key, 'type' => $value['targetDocument'] ]; }, array_keys($relations), $relations ); }
php
private function getRelationList($mapping, $suffix) { if (!isset($mapping['embed'.$suffix]) && !isset($mapping['reference'.$suffix])) { return []; } $relations = []; if (isset($mapping['embed'.$suffix])) { $relations = array_merge($relations, $mapping['embed'.$suffix]); } if (isset($mapping['reference'.$suffix])) { $relations = array_merge($relations, $mapping['reference'.$suffix]); } return array_map( function ($key, $value) { return [ 'name' => $key, 'type' => $value['targetDocument'] ]; }, array_keys($relations), $relations ); }
[ "private", "function", "getRelationList", "(", "$", "mapping", ",", "$", "suffix", ")", "{", "if", "(", "!", "isset", "(", "$", "mapping", "[", "'embed'", ".", "$", "suffix", "]", ")", "&&", "!", "isset", "(", "$", "mapping", "[", "'reference'", ".",...
gets list of relations @param array $mapping mapping @param string $suffix suffix @return array relations
[ "gets", "list", "of", "relations" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php#L409-L433
train
libgraviton/graviton
src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php
DocumentMap.getFieldNamesFlat
public function getFieldNamesFlat( Document $document, $documentPrefix = '', $exposedPrefix = '', callable $callback = null, $returnFullField = false ) { $result = []; foreach ($document->getFields() as $field) { if ($this->getFlatFieldCheckCallback($field, $callback)) { if ($returnFullField) { $setValue = $field; } else { $setValue = $exposedPrefix . $field->getExposedName(); } $result[$documentPrefix . $field->getFieldName()] = $setValue; } if ($field instanceof ArrayField) { if ($this->getFlatFieldCheckCallback($field, $callback)) { if ($returnFullField) { $setValue = $field; } else { $setValue = $exposedPrefix . $field->getExposedName() . '.0'; } $result[$documentPrefix . $field->getFieldName() . '.0'] = $setValue; } } elseif ($field instanceof EmbedOne) { $result = array_merge( $result, $this->getFieldNamesFlat( $field->getDocument(), $documentPrefix.$field->getFieldName().'.', $exposedPrefix.$field->getExposedName().'.', $callback, $returnFullField ) ); } elseif ($field instanceof EmbedMany) { if ($this->getFlatFieldCheckCallback($field, $callback)) { if ($returnFullField) { $setValue = $field; } else { $setValue = $exposedPrefix . $field->getExposedName() . '.0'; } $result[$documentPrefix . $field->getFieldName() . '.0'] = $setValue; } $result = array_merge( $result, $this->getFieldNamesFlat( $field->getDocument(), $documentPrefix.$field->getFieldName().'.0.', $exposedPrefix.$field->getExposedName().'.0.', $callback, $returnFullField ) ); } } return $result; }
php
public function getFieldNamesFlat( Document $document, $documentPrefix = '', $exposedPrefix = '', callable $callback = null, $returnFullField = false ) { $result = []; foreach ($document->getFields() as $field) { if ($this->getFlatFieldCheckCallback($field, $callback)) { if ($returnFullField) { $setValue = $field; } else { $setValue = $exposedPrefix . $field->getExposedName(); } $result[$documentPrefix . $field->getFieldName()] = $setValue; } if ($field instanceof ArrayField) { if ($this->getFlatFieldCheckCallback($field, $callback)) { if ($returnFullField) { $setValue = $field; } else { $setValue = $exposedPrefix . $field->getExposedName() . '.0'; } $result[$documentPrefix . $field->getFieldName() . '.0'] = $setValue; } } elseif ($field instanceof EmbedOne) { $result = array_merge( $result, $this->getFieldNamesFlat( $field->getDocument(), $documentPrefix.$field->getFieldName().'.', $exposedPrefix.$field->getExposedName().'.', $callback, $returnFullField ) ); } elseif ($field instanceof EmbedMany) { if ($this->getFlatFieldCheckCallback($field, $callback)) { if ($returnFullField) { $setValue = $field; } else { $setValue = $exposedPrefix . $field->getExposedName() . '.0'; } $result[$documentPrefix . $field->getFieldName() . '.0'] = $setValue; } $result = array_merge( $result, $this->getFieldNamesFlat( $field->getDocument(), $documentPrefix.$field->getFieldName().'.0.', $exposedPrefix.$field->getExposedName().'.0.', $callback, $returnFullField ) ); } } return $result; }
[ "public", "function", "getFieldNamesFlat", "(", "Document", "$", "document", ",", "$", "documentPrefix", "=", "''", ",", "$", "exposedPrefix", "=", "''", ",", "callable", "$", "callback", "=", "null", ",", "$", "returnFullField", "=", "false", ")", "{", "$...
Gets an array of all fields, flat with full internal name in dot notation as key and the exposed field name as value. You can pass a callable to limit the fields return a subset of fields. If the callback returns true, the field will be included in the output. You will get the field definition passed to your callback. @param Document $document The document @param string $documentPrefix Document field prefix @param string $exposedPrefix Exposed field prefix @param callable $callback An optional callback where you can influence the number of fields returned @param boolean $returnFullField if true, the function returns the full field object instead of the full path @return array
[ "Gets", "an", "array", "of", "all", "fields", "flat", "with", "full", "internal", "name", "in", "dot", "notation", "as", "key", "and", "the", "exposed", "field", "name", "as", "value", ".", "You", "can", "pass", "a", "callable", "to", "limit", "the", "...
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php#L449-L510
train
libgraviton/graviton
src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php
DocumentMap.getFlatFieldCheckCallback
private function getFlatFieldCheckCallback($field, callable $callback = null) { if (!is_callable($callback)) { return true; } return call_user_func($callback, $field); }
php
private function getFlatFieldCheckCallback($field, callable $callback = null) { if (!is_callable($callback)) { return true; } return call_user_func($callback, $field); }
[ "private", "function", "getFlatFieldCheckCallback", "(", "$", "field", ",", "callable", "$", "callback", "=", "null", ")", "{", "if", "(", "!", "is_callable", "(", "$", "callback", ")", ")", "{", "return", "true", ";", "}", "return", "call_user_func", "(",...
Simple function to check whether a given shall be returned in the output of getFieldNamesFlat and the optional given callback there. @param AbstractField $field field @param callable|null $callback optional callback @return bool|mixed true if field should be returned, false otherwise
[ "Simple", "function", "to", "check", "whether", "a", "given", "shall", "be", "returned", "in", "the", "output", "of", "getFieldNamesFlat", "and", "the", "optional", "given", "callback", "there", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php#L521-L528
train
libgraviton/graviton
src/Graviton/ProxyBundle/DependencyInjection/Compiler/TransformerPass.php
TransformerPass.registerTaggedTransformation
private function registerTaggedTransformation(ContainerBuilder $container, Definition $definition, $tag, $callable) { $taggedServices = $container->findTaggedServiceIds($tag); foreach ($taggedServices as $id => $tags) { foreach ($tags as $attributes) { $definition->addMethodCall( $callable, array( $attributes["alias"], $attributes["endpoint"], new Reference($id) ) ); } } }
php
private function registerTaggedTransformation(ContainerBuilder $container, Definition $definition, $tag, $callable) { $taggedServices = $container->findTaggedServiceIds($tag); foreach ($taggedServices as $id => $tags) { foreach ($tags as $attributes) { $definition->addMethodCall( $callable, array( $attributes["alias"], $attributes["endpoint"], new Reference($id) ) ); } } }
[ "private", "function", "registerTaggedTransformation", "(", "ContainerBuilder", "$", "container", ",", "Definition", "$", "definition", ",", "$", "tag", ",", "$", "callable", ")", "{", "$", "taggedServices", "=", "$", "container", "->", "findTaggedServiceIds", "("...
Adds the found services to the TransformationHandler @param ContainerBuilder $container Symfony Service Container @param Definition $definition Service the services shall be add to. @param string $tag Tag identifying the service to be added @param string $callable Name of the method to call to add the tagged service. @return void
[ "Adds", "the", "found", "services", "to", "the", "TransformationHandler" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/DependencyInjection/Compiler/TransformerPass.php#L71-L87
train
libgraviton/graviton
app/AppKernel.php
AppKernel.initializeContainer
protected function initializeContainer() { static $first = true; if ('test' !== $this->getEnvironment()) { parent::initializeContainer(); return; } $debug = $this->debug; if (!$first) { // disable debug mode on all but the first initialization $this->debug = false; } // will not work with --process-isolation $first = false; try { parent::initializeContainer(); } catch (\Exception $e) { $this->debug = $debug; throw $e; } $this->debug = $debug; }
php
protected function initializeContainer() { static $first = true; if ('test' !== $this->getEnvironment()) { parent::initializeContainer(); return; } $debug = $this->debug; if (!$first) { // disable debug mode on all but the first initialization $this->debug = false; } // will not work with --process-isolation $first = false; try { parent::initializeContainer(); } catch (\Exception $e) { $this->debug = $debug; throw $e; } $this->debug = $debug; }
[ "protected", "function", "initializeContainer", "(", ")", "{", "static", "$", "first", "=", "true", ";", "if", "(", "'test'", "!==", "$", "this", "->", "getEnvironment", "(", ")", ")", "{", "parent", "::", "initializeContainer", "(", ")", ";", "return", ...
dont rebuild container with debug over and over again during tests This is very much what is described in http://kriswallsmith.net/post/27979797907 @return void
[ "dont", "rebuild", "container", "with", "debug", "over", "and", "over", "again", "during", "tests" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/app/AppKernel.php#L119-L146
train
libgraviton/graviton
src/Graviton/SecurityBundle/User/Model/ModelFactory.php
ModelFactory.create
public function create() { $serviceId = $this->container->getParameter('graviton.security.authentication.provider.model'); $service = $this->container->get('graviton.security.authentication.provider.model.noop'); if (!empty($serviceId) && $this->container->has($serviceId)) { $service = $this->container->get($serviceId); } return $service; }
php
public function create() { $serviceId = $this->container->getParameter('graviton.security.authentication.provider.model'); $service = $this->container->get('graviton.security.authentication.provider.model.noop'); if (!empty($serviceId) && $this->container->has($serviceId)) { $service = $this->container->get($serviceId); } return $service; }
[ "public", "function", "create", "(", ")", "{", "$", "serviceId", "=", "$", "this", "->", "container", "->", "getParameter", "(", "'graviton.security.authentication.provider.model'", ")", ";", "$", "service", "=", "$", "this", "->", "container", "->", "get", "(...
Determines what service to be used. @return \Graviton\RestBundle\Model\ModelInterface
[ "Determines", "what", "service", "to", "be", "used", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SecurityBundle/User/Model/ModelFactory.php#L39-L49
train
libgraviton/graviton
src/Graviton/SchemaBundle/Constraint/ReadOnlyFieldConstraint.php
ReadOnlyFieldConstraint.propertyExists
private function propertyExists($object, $fieldName) { if (property_exists($object, $fieldName)) { return true; } foreach (explode('.', $fieldName) as $field) { if (property_exists($object, $field)) { $object = $object->{$field}; if (!is_object($object)) { break; } continue; } else { return false; } } return true; }
php
private function propertyExists($object, $fieldName) { if (property_exists($object, $fieldName)) { return true; } foreach (explode('.', $fieldName) as $field) { if (property_exists($object, $field)) { $object = $object->{$field}; if (!is_object($object)) { break; } continue; } else { return false; } } return true; }
[ "private", "function", "propertyExists", "(", "$", "object", ",", "$", "fieldName", ")", "{", "if", "(", "property_exists", "(", "$", "object", ",", "$", "fieldName", ")", ")", "{", "return", "true", ";", "}", "foreach", "(", "explode", "(", "'.'", ","...
To validate before accessor brakes with not found field @param object $object To be parsed @param string $fieldName Field name, dot chained. @return bool
[ "To", "validate", "before", "accessor", "brakes", "with", "not", "found", "field" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/ReadOnlyFieldConstraint.php#L103-L121
train
libgraviton/graviton
src/Graviton/ProxyBundle/Service/MappingTransformer.php
MappingTransformer.transform
public function transform($raw, array $mapping, $transformed = []) { foreach ($mapping as $destination => $source) { $value = $this->propertyAccessor->isReadable($raw, $source) ? $this->propertyAccessor->getValue($raw, $source) : null; $this->propertyAccessor->setValue($transformed, $destination, $value); } return $transformed; }
php
public function transform($raw, array $mapping, $transformed = []) { foreach ($mapping as $destination => $source) { $value = $this->propertyAccessor->isReadable($raw, $source) ? $this->propertyAccessor->getValue($raw, $source) : null; $this->propertyAccessor->setValue($transformed, $destination, $value); } return $transformed; }
[ "public", "function", "transform", "(", "$", "raw", ",", "array", "$", "mapping", ",", "$", "transformed", "=", "[", "]", ")", "{", "foreach", "(", "$", "mapping", "as", "$", "destination", "=>", "$", "source", ")", "{", "$", "value", "=", "$", "th...
Applies the given mapping on a given object or array. @param object|array $raw The input object or array @param array $mapping The mapping @param object|array $transformed The output object or array. @return array
[ "Applies", "the", "given", "mapping", "on", "a", "given", "object", "or", "array", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Service/MappingTransformer.php#L43-L51
train
libgraviton/graviton
src/Graviton/CoreBundle/GravitonCoreBundle.php
GravitonCoreBundle.build
public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new VersionCompilerPass(new PrettyVersions())); $container->addCompilerPass(new EnvParametersCompilerPass()); $container->addCompilerPass(new RouteLoaderCompilerPass()); $container->addCompilerPass(new HttpClientOptionsCompilerPass()); }
php
public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new VersionCompilerPass(new PrettyVersions())); $container->addCompilerPass(new EnvParametersCompilerPass()); $container->addCompilerPass(new RouteLoaderCompilerPass()); $container->addCompilerPass(new HttpClientOptionsCompilerPass()); }
[ "public", "function", "build", "(", "ContainerBuilder", "$", "container", ")", "{", "parent", "::", "build", "(", "$", "container", ")", ";", "$", "container", "->", "addCompilerPass", "(", "new", "VersionCompilerPass", "(", "new", "PrettyVersions", "(", ")", ...
load version compiler pass @param ContainerBuilder $container container builder @return void
[ "load", "version", "compiler", "pass" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/GravitonCoreBundle.php#L74-L82
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Generator/ResourceGenerator/FieldMapper.php
FieldMapper.buildFields
public function buildFields(JsonDefinition $jsonDefinition) { $fields = []; foreach ($jsonDefinition->getFields() as $field) { if ($field->getName() != 'id') { $fields[] = [ 'fieldName' => $field->getName(), 'type' => $field->getTypeDoctrine() ]; } } return $fields; }
php
public function buildFields(JsonDefinition $jsonDefinition) { $fields = []; foreach ($jsonDefinition->getFields() as $field) { if ($field->getName() != 'id') { $fields[] = [ 'fieldName' => $field->getName(), 'type' => $field->getTypeDoctrine() ]; } } return $fields; }
[ "public", "function", "buildFields", "(", "JsonDefinition", "$", "jsonDefinition", ")", "{", "$", "fields", "=", "[", "]", ";", "foreach", "(", "$", "jsonDefinition", "->", "getFields", "(", ")", "as", "$", "field", ")", "{", "if", "(", "$", "field", "...
builds the initial fields array with a json definition @param JsonDefinition $jsonDefinition definition @return array fields
[ "builds", "the", "initial", "fields", "array", "with", "a", "json", "definition" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Generator/ResourceGenerator/FieldMapper.php#L39-L52
train
libgraviton/graviton
src/Graviton/CoreBundle/Event/HomepageRenderEvent.php
HomepageRenderEvent.addRoute
public function addRoute($url, $schemaUrl) { $this->addedRoutes[] = [ '$ref' => $this->normalizeRelativeUrl($url), 'profile' => $this->normalizeRelativeUrl($schemaUrl) ]; }
php
public function addRoute($url, $schemaUrl) { $this->addedRoutes[] = [ '$ref' => $this->normalizeRelativeUrl($url), 'profile' => $this->normalizeRelativeUrl($schemaUrl) ]; }
[ "public", "function", "addRoute", "(", "$", "url", ",", "$", "schemaUrl", ")", "{", "$", "this", "->", "addedRoutes", "[", "]", "=", "[", "'$ref'", "=>", "$", "this", "->", "normalizeRelativeUrl", "(", "$", "url", ")", ",", "'profile'", "=>", "$", "t...
add a route to the homepage @param string $url relative (to root) url to the service @param string $schemaUrl relative (to root) url to the schema @return void
[ "add", "a", "route", "to", "the", "homepage" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Event/HomepageRenderEvent.php#L39-L45
train
libgraviton/graviton
src/Graviton/DocumentBundle/DependencyInjection/Compiler/TranslatableFieldsCompilerPass.php
TranslatableFieldsCompilerPass.process
public function process(ContainerBuilder $container) { $this->documentMap = $container->get('graviton.document.map'); $map = []; foreach ($this->documentMap->getDocuments() as $document) { $map[$document->getClass()] = $this->getTranslatableFields($document); } $container->setParameter('graviton.document.type.translatable.fields', $map); // write default language to a file so we can statically read it out file_put_contents( __DIR__.'/../../Entity/Translatable.defaultLanguage', $container->getParameter('graviton.translator.default.locale') ); }
php
public function process(ContainerBuilder $container) { $this->documentMap = $container->get('graviton.document.map'); $map = []; foreach ($this->documentMap->getDocuments() as $document) { $map[$document->getClass()] = $this->getTranslatableFields($document); } $container->setParameter('graviton.document.type.translatable.fields', $map); // write default language to a file so we can statically read it out file_put_contents( __DIR__.'/../../Entity/Translatable.defaultLanguage', $container->getParameter('graviton.translator.default.locale') ); }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", "{", "$", "this", "->", "documentMap", "=", "$", "container", "->", "get", "(", "'graviton.document.map'", ")", ";", "$", "map", "=", "[", "]", ";", "foreach", "(", "$", "th...
Make translatable fields map and set it to parameter @param ContainerBuilder $container container builder @return void
[ "Make", "translatable", "fields", "map", "and", "set", "it", "to", "parameter" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/TranslatableFieldsCompilerPass.php#L36-L50
train
libgraviton/graviton
src/Graviton/DocumentBundle/DependencyInjection/Compiler/TranslatableFieldsCompilerPass.php
TranslatableFieldsCompilerPass.getTranslatableFields
private function getTranslatableFields(Document $document, $prefix = '') { $result = []; foreach ($document->getFields() as $field) { if ($field instanceof Field) { if ($field->getType() == 'translatable') { $result[] = $prefix.$field->getExposedName(); } } elseif ($field instanceof EmbedOne) { $result = array_merge( $result, $this->getTranslatableFields( $field->getDocument(), $prefix.$field->getExposedName().'.' ) ); } elseif ($field instanceof EmbedMany) { $result = array_merge( $result, $this->getTranslatableFields( $field->getDocument(), $prefix.$field->getExposedName().'.0.' ) ); } } return $result; }
php
private function getTranslatableFields(Document $document, $prefix = '') { $result = []; foreach ($document->getFields() as $field) { if ($field instanceof Field) { if ($field->getType() == 'translatable') { $result[] = $prefix.$field->getExposedName(); } } elseif ($field instanceof EmbedOne) { $result = array_merge( $result, $this->getTranslatableFields( $field->getDocument(), $prefix.$field->getExposedName().'.' ) ); } elseif ($field instanceof EmbedMany) { $result = array_merge( $result, $this->getTranslatableFields( $field->getDocument(), $prefix.$field->getExposedName().'.0.' ) ); } } return $result; }
[ "private", "function", "getTranslatableFields", "(", "Document", "$", "document", ",", "$", "prefix", "=", "''", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "document", "->", "getFields", "(", ")", "as", "$", "field", ")", "{", ...
Get document fields @param Document $document Document @param string $prefix Field prefix @return array
[ "Get", "document", "fields" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/TranslatableFieldsCompilerPass.php#L59-L87
train
libgraviton/graviton
src/Graviton/SchemaBundle/Constraint/Builder/RangeConstraintBuilder.php
RangeConstraintBuilder.supportsConstraint
public function supportsConstraint($type, array $options = []) { if (in_array($type, $this->types)) { $this->type = $type; return true; } return false; }
php
public function supportsConstraint($type, array $options = []) { if (in_array($type, $this->types)) { $this->type = $type; return true; } return false; }
[ "public", "function", "supportsConstraint", "(", "$", "type", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "in_array", "(", "$", "type", ",", "$", "this", "->", "types", ")", ")", "{", "$", "this", "->", "type", "=", "$", "ty...
if this builder supports a given constraint @param string $type Field type @param array $options Options @return bool
[ "if", "this", "builder", "supports", "a", "given", "constraint" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/Builder/RangeConstraintBuilder.php#L41-L49
train
libgraviton/graviton
src/Graviton/SchemaBundle/SchemaUtils.php
SchemaUtils.getCollectionSchema
public function getCollectionSchema($modelName, DocumentModel $model) { $collectionSchema = new Schema; $collectionSchema->setTitle(sprintf('Array of %s objects', $modelName)); $collectionSchema->setType('array'); $collectionSchema->setItems($this->getModelSchema($modelName, $model)); return $collectionSchema; }
php
public function getCollectionSchema($modelName, DocumentModel $model) { $collectionSchema = new Schema; $collectionSchema->setTitle(sprintf('Array of %s objects', $modelName)); $collectionSchema->setType('array'); $collectionSchema->setItems($this->getModelSchema($modelName, $model)); return $collectionSchema; }
[ "public", "function", "getCollectionSchema", "(", "$", "modelName", ",", "DocumentModel", "$", "model", ")", "{", "$", "collectionSchema", "=", "new", "Schema", ";", "$", "collectionSchema", "->", "setTitle", "(", "sprintf", "(", "'Array of %s objects'", ",", "$...
get schema for an array of models @param string $modelName name of model @param DocumentModel $model model @return Schema
[ "get", "schema", "for", "an", "array", "of", "models" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/SchemaUtils.php#L163-L170
train
libgraviton/graviton
src/Graviton/SchemaBundle/SchemaUtils.php
SchemaUtils.getSchemaVariationName
private function getSchemaVariationName($userData, $variations) { foreach ($variations as $variationName => $expressions) { $results = array_map( function ($expression) use ($userData) { return $this->jmesRuntime->__invoke($expression, $userData); }, $expressions ); $results = array_unique($results); if (count($results) == 1 && $results[0] === true) { return $variationName; } } return null; }
php
private function getSchemaVariationName($userData, $variations) { foreach ($variations as $variationName => $expressions) { $results = array_map( function ($expression) use ($userData) { return $this->jmesRuntime->__invoke($expression, $userData); }, $expressions ); $results = array_unique($results); if (count($results) == 1 && $results[0] === true) { return $variationName; } } return null; }
[ "private", "function", "getSchemaVariationName", "(", "$", "userData", ",", "$", "variations", ")", "{", "foreach", "(", "$", "variations", "as", "$", "variationName", "=>", "$", "expressions", ")", "{", "$", "results", "=", "array_map", "(", "function", "("...
gets the name of the variation to apply based on userdata and the service definition @param \stdClass $userData user data @param \stdClass $variations variations as defined in schema @return string|null the variation name or null if none
[ "gets", "the", "name", "of", "the", "variation", "to", "apply", "based", "on", "userdata", "and", "the", "service", "definition" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/SchemaUtils.php#L482-L500
train
libgraviton/graviton
src/Graviton/SchemaBundle/SchemaUtils.php
SchemaUtils.makeTranslatable
public function makeTranslatable(Schema $property, $languages) { $property->setType('object'); $property->setTranslatable(true); array_walk( $languages, function ($language) use ($property) { $schema = new Schema; $schema->setType('string'); $schema->setTitle('Translated String'); $schema->setDescription('String in ' . $language . ' locale.'); $property->addProperty($language, $schema); } ); $property->setRequired(['en']); return $property; }
php
public function makeTranslatable(Schema $property, $languages) { $property->setType('object'); $property->setTranslatable(true); array_walk( $languages, function ($language) use ($property) { $schema = new Schema; $schema->setType('string'); $schema->setTitle('Translated String'); $schema->setDescription('String in ' . $language . ' locale.'); $property->addProperty($language, $schema); } ); $property->setRequired(['en']); return $property; }
[ "public", "function", "makeTranslatable", "(", "Schema", "$", "property", ",", "$", "languages", ")", "{", "$", "property", "->", "setType", "(", "'object'", ")", ";", "$", "property", "->", "setTranslatable", "(", "true", ")", ";", "array_walk", "(", "$",...
turn a property into a translatable property @param Schema $property simple string property @param string[] $languages available languages @return Schema
[ "turn", "a", "property", "into", "a", "translatable", "property" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/SchemaUtils.php#L510-L527
train
libgraviton/graviton
src/Graviton/SchemaBundle/SchemaUtils.php
SchemaUtils.makeArrayTranslatable
public function makeArrayTranslatable(Schema $property, $languages) { $property->setType('array'); $property->setItems($this->makeTranslatable(new Schema(), $languages)); return $property; }
php
public function makeArrayTranslatable(Schema $property, $languages) { $property->setType('array'); $property->setItems($this->makeTranslatable(new Schema(), $languages)); return $property; }
[ "public", "function", "makeArrayTranslatable", "(", "Schema", "$", "property", ",", "$", "languages", ")", "{", "$", "property", "->", "setType", "(", "'array'", ")", ";", "$", "property", "->", "setItems", "(", "$", "this", "->", "makeTranslatable", "(", ...
turn a array property into a translatable property @param Schema $property simple string property @param string[] $languages available languages @return Schema
[ "turn", "a", "array", "property", "into", "a", "translatable", "property" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/SchemaUtils.php#L537-L542
train
libgraviton/graviton
src/Graviton/SchemaBundle/SchemaUtils.php
SchemaUtils.getSchemaRouteName
public static function getSchemaRouteName($routeName) { $routeParts = explode('.', $routeName); $routeType = array_pop($routeParts); // check if we need to create an item or collection schema $realRouteType = 'canonicalSchema'; if ($routeType != 'options' && $routeType != 'all') { $realRouteType = 'canonicalIdSchema'; } return implode('.', array_merge($routeParts, array($realRouteType))); }
php
public static function getSchemaRouteName($routeName) { $routeParts = explode('.', $routeName); $routeType = array_pop($routeParts); // check if we need to create an item or collection schema $realRouteType = 'canonicalSchema'; if ($routeType != 'options' && $routeType != 'all') { $realRouteType = 'canonicalIdSchema'; } return implode('.', array_merge($routeParts, array($realRouteType))); }
[ "public", "static", "function", "getSchemaRouteName", "(", "$", "routeName", ")", "{", "$", "routeParts", "=", "explode", "(", "'.'", ",", "$", "routeName", ")", ";", "$", "routeType", "=", "array_pop", "(", "$", "routeParts", ")", ";", "// check if we need ...
get canonical route to a schema based on a route @param string $routeName route name @return string schema route name
[ "get", "canonical", "route", "to", "a", "schema", "based", "on", "a", "route" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/SchemaUtils.php#L551-L563
train
libgraviton/graviton
src/Graviton/SchemaBundle/SchemaUtils.php
SchemaUtils.getCollectionItemType
private function getCollectionItemType($className, $fieldName) { $serializerMetadata = $this->serializerMetadataFactory->getMetadataForClass($className); if ($serializerMetadata === null) { return null; } if (!isset($serializerMetadata->propertyMetadata[$fieldName])) { return null; } $type = $serializerMetadata->propertyMetadata[$fieldName]->type; return isset($type['name'], $type['params'][0]['name']) && $type['name'] === 'array' ? $type['params'][0]['name'] : null; }
php
private function getCollectionItemType($className, $fieldName) { $serializerMetadata = $this->serializerMetadataFactory->getMetadataForClass($className); if ($serializerMetadata === null) { return null; } if (!isset($serializerMetadata->propertyMetadata[$fieldName])) { return null; } $type = $serializerMetadata->propertyMetadata[$fieldName]->type; return isset($type['name'], $type['params'][0]['name']) && $type['name'] === 'array' ? $type['params'][0]['name'] : null; }
[ "private", "function", "getCollectionItemType", "(", "$", "className", ",", "$", "fieldName", ")", "{", "$", "serializerMetadata", "=", "$", "this", "->", "serializerMetadataFactory", "->", "getMetadataForClass", "(", "$", "className", ")", ";", "if", "(", "$", ...
Get item type of collection field @param string $className Class name @param string $fieldName Field name @return string|null
[ "Get", "item", "type", "of", "collection", "field" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/SchemaUtils.php#L572-L586
train
libgraviton/graviton
src/Graviton/RestBundle/Service/RestUtils.php
RestUtils.serializeContent
public function serializeContent($content, $format = 'json') { try { return $this->getSerializer()->serialize( $content, $format ); } catch (\Exception $e) { $msg = sprintf( 'Cannot serialize content class: %s; with id: %s; Message: %s', get_class($content), method_exists($content, 'getId') ? $content->getId() : '-no id-', str_replace('MongoDBODMProxies\__CG__\GravitonDyn', '', $e->getMessage()) ); $this->logger->alert($msg); throw new \Exception($msg, $e->getCode()); } }
php
public function serializeContent($content, $format = 'json') { try { return $this->getSerializer()->serialize( $content, $format ); } catch (\Exception $e) { $msg = sprintf( 'Cannot serialize content class: %s; with id: %s; Message: %s', get_class($content), method_exists($content, 'getId') ? $content->getId() : '-no id-', str_replace('MongoDBODMProxies\__CG__\GravitonDyn', '', $e->getMessage()) ); $this->logger->alert($msg); throw new \Exception($msg, $e->getCode()); } }
[ "public", "function", "serializeContent", "(", "$", "content", ",", "$", "format", "=", "'json'", ")", "{", "try", "{", "return", "$", "this", "->", "getSerializer", "(", ")", "->", "serialize", "(", "$", "content", ",", "$", "format", ")", ";", "}", ...
Public function to serialize stuff according to the serializer rules. @param object $content Any content to serialize @param string $format Which format to serialize into @throws \Exception @return string $content Json content
[ "Public", "function", "to", "serialize", "stuff", "according", "to", "the", "serializer", "rules", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Service/RestUtils.php#L143-L160
train
libgraviton/graviton
src/Graviton/RestBundle/Service/RestUtils.php
RestUtils.validateContent
public function validateContent($content, DocumentModel $model) { if (is_string($content)) { $content = json_decode($content); } return $this->schemaValidator->validate( $content, $this->schemaUtils->getModelSchema(null, $model, true, true, true, $content) ); }
php
public function validateContent($content, DocumentModel $model) { if (is_string($content)) { $content = json_decode($content); } return $this->schemaValidator->validate( $content, $this->schemaUtils->getModelSchema(null, $model, true, true, true, $content) ); }
[ "public", "function", "validateContent", "(", "$", "content", ",", "DocumentModel", "$", "model", ")", "{", "if", "(", "is_string", "(", "$", "content", ")", ")", "{", "$", "content", "=", "json_decode", "(", "$", "content", ")", ";", "}", "return", "$...
Validates content with the given schema, returning an array of errors. If all is good, you will receive an empty array. @param object $content \stdClass of the request content @param DocumentModel $model the model to check the schema for @return \Graviton\JsonSchemaBundle\Exception\ValidationExceptionError[] @throws \Exception
[ "Validates", "content", "with", "the", "given", "schema", "returning", "an", "array", "of", "errors", ".", "If", "all", "is", "good", "you", "will", "receive", "an", "empty", "array", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Service/RestUtils.php#L194-L204
train
libgraviton/graviton
src/Graviton/RestBundle/Service/RestUtils.php
RestUtils.checkJsonRequest
public function checkJsonRequest(Request $request, Response $response, DocumentModel $model, $content = '') { if (empty($content)) { $content = $request->getContent(); } if (is_resource($content)) { throw new BadRequestHttpException('unexpected resource in validation'); } // is request body empty if ($content === '') { $e = new NoInputException(); $e->setResponse($response); throw $e; } $input = json_decode($content, true); if (JSON_ERROR_NONE !== json_last_error()) { $e = new MalformedInputException($this->getLastJsonErrorMessage()); $e->setErrorType(json_last_error()); $e->setResponse($response); throw $e; } if (!is_array($input)) { $e = new MalformedInputException('JSON request body must be an object'); $e->setResponse($response); throw $e; } if ($request->getMethod() == 'PUT' && array_key_exists('id', $input)) { // we need to check for id mismatches.... if ($request->attributes->get('id') != $input['id']) { $e = new MalformedInputException('Record ID in your payload must be the same'); $e->setResponse($response); throw $e; } } if ($request->getMethod() == 'POST' && array_key_exists('id', $input) && !$model->isIdInPostAllowed() ) { $e = new MalformedInputException( '"id" can not be given on a POST request. Do a PUT request instead to update an existing record.' ); $e->setResponse($response); throw $e; } }
php
public function checkJsonRequest(Request $request, Response $response, DocumentModel $model, $content = '') { if (empty($content)) { $content = $request->getContent(); } if (is_resource($content)) { throw new BadRequestHttpException('unexpected resource in validation'); } // is request body empty if ($content === '') { $e = new NoInputException(); $e->setResponse($response); throw $e; } $input = json_decode($content, true); if (JSON_ERROR_NONE !== json_last_error()) { $e = new MalformedInputException($this->getLastJsonErrorMessage()); $e->setErrorType(json_last_error()); $e->setResponse($response); throw $e; } if (!is_array($input)) { $e = new MalformedInputException('JSON request body must be an object'); $e->setResponse($response); throw $e; } if ($request->getMethod() == 'PUT' && array_key_exists('id', $input)) { // we need to check for id mismatches.... if ($request->attributes->get('id') != $input['id']) { $e = new MalformedInputException('Record ID in your payload must be the same'); $e->setResponse($response); throw $e; } } if ($request->getMethod() == 'POST' && array_key_exists('id', $input) && !$model->isIdInPostAllowed() ) { $e = new MalformedInputException( '"id" can not be given on a POST request. Do a PUT request instead to update an existing record.' ); $e->setResponse($response); throw $e; } }
[ "public", "function", "checkJsonRequest", "(", "Request", "$", "request", ",", "Response", "$", "response", ",", "DocumentModel", "$", "model", ",", "$", "content", "=", "''", ")", "{", "if", "(", "empty", "(", "$", "content", ")", ")", "{", "$", "cont...
validate raw json input @param Request $request request @param Response $response response @param DocumentModel $model model @param string $content Alternative request content. @return void
[ "validate", "raw", "json", "input" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Service/RestUtils.php#L216-L265
train
libgraviton/graviton
src/Graviton/RestBundle/Service/RestUtils.php
RestUtils.checkJsonPatchRequest
public function checkJsonPatchRequest(array $jsonPatch) { foreach ($jsonPatch as $operation) { if (!is_array($operation)) { throw new InvalidJsonPatchException('Patch request should be an array of operations.'); } if (array_key_exists('path', $operation) && trim($operation['path']) == '/id') { throw new InvalidJsonPatchException('Change/remove of ID not allowed'); } } }
php
public function checkJsonPatchRequest(array $jsonPatch) { foreach ($jsonPatch as $operation) { if (!is_array($operation)) { throw new InvalidJsonPatchException('Patch request should be an array of operations.'); } if (array_key_exists('path', $operation) && trim($operation['path']) == '/id') { throw new InvalidJsonPatchException('Change/remove of ID not allowed'); } } }
[ "public", "function", "checkJsonPatchRequest", "(", "array", "$", "jsonPatch", ")", "{", "foreach", "(", "$", "jsonPatch", "as", "$", "operation", ")", "{", "if", "(", "!", "is_array", "(", "$", "operation", ")", ")", "{", "throw", "new", "InvalidJsonPatch...
Validate JSON patch for any object @param array $jsonPatch json patch as array @throws InvalidJsonPatchException @return void
[ "Validate", "JSON", "patch", "for", "any", "object" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Service/RestUtils.php#L275-L285
train
libgraviton/graviton
src/Graviton/RestBundle/Service/RestUtils.php
RestUtils.getOptionRoutes
public function getOptionRoutes() { $cached = $this->cacheProvider->fetch('cached_restutils_route_options'); if ($cached) { return $cached; } $ret = array_filter( $this->router->getRouteCollection()->all(), function ($route) { if (!in_array('OPTIONS', $route->getMethods())) { return false; } // ignore all schema routes if (strpos($route->getPath(), '/schema') === 0) { return false; } if ($route->getPath() == '/' || $route->getPath() == '/core/version') { return false; } return is_null($route->getRequirement('id')); } ); $this->cacheProvider->save('cached_restutils_route_options', $ret); return $ret; }
php
public function getOptionRoutes() { $cached = $this->cacheProvider->fetch('cached_restutils_route_options'); if ($cached) { return $cached; } $ret = array_filter( $this->router->getRouteCollection()->all(), function ($route) { if (!in_array('OPTIONS', $route->getMethods())) { return false; } // ignore all schema routes if (strpos($route->getPath(), '/schema') === 0) { return false; } if ($route->getPath() == '/' || $route->getPath() == '/core/version') { return false; } return is_null($route->getRequirement('id')); } ); $this->cacheProvider->save('cached_restutils_route_options', $ret); return $ret; }
[ "public", "function", "getOptionRoutes", "(", ")", "{", "$", "cached", "=", "$", "this", "->", "cacheProvider", "->", "fetch", "(", "'cached_restutils_route_options'", ")", ";", "if", "(", "$", "cached", ")", "{", "return", "$", "cached", ";", "}", "$", ...
It has been deemed that we search for OPTION routes in order to detect our service routes and then derive the rest from them. @return array An array with option routes
[ "It", "has", "been", "deemed", "that", "we", "search", "for", "OPTION", "routes", "in", "order", "to", "detect", "our", "service", "routes", "and", "then", "derive", "the", "rest", "from", "them", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Service/RestUtils.php#L319-L344
train
libgraviton/graviton
src/Graviton/RestBundle/Service/RestUtils.php
RestUtils.getModelFromRoute
public function getModelFromRoute(Route $route) { $ret = false; $controller = $this->getControllerFromRoute($route); if ($controller instanceof RestController) { $ret = $controller->getModel(); } return $ret; }
php
public function getModelFromRoute(Route $route) { $ret = false; $controller = $this->getControllerFromRoute($route); if ($controller instanceof RestController) { $ret = $controller->getModel(); } return $ret; }
[ "public", "function", "getModelFromRoute", "(", "Route", "$", "route", ")", "{", "$", "ret", "=", "false", ";", "$", "controller", "=", "$", "this", "->", "getControllerFromRoute", "(", "$", "route", ")", ";", "if", "(", "$", "controller", "instanceof", ...
Gets the Model assigned to the RestController @param Route $route Route @return bool|object The model or false @throws \Exception
[ "Gets", "the", "Model", "assigned", "to", "the", "RestController" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Service/RestUtils.php#L381-L391
train
libgraviton/graviton
src/Graviton/RestBundle/Service/RestUtils.php
RestUtils.getControllerFromRoute
public function getControllerFromRoute(Route $route) { $ret = false; $actionParts = explode(':', $route->getDefault('_controller')); if (count($actionParts) == 2) { $ret = $this->container->get($actionParts[0]); } return $ret; }
php
public function getControllerFromRoute(Route $route) { $ret = false; $actionParts = explode(':', $route->getDefault('_controller')); if (count($actionParts) == 2) { $ret = $this->container->get($actionParts[0]); } return $ret; }
[ "public", "function", "getControllerFromRoute", "(", "Route", "$", "route", ")", "{", "$", "ret", "=", "false", ";", "$", "actionParts", "=", "explode", "(", "':'", ",", "$", "route", "->", "getDefault", "(", "'_controller'", ")", ")", ";", "if", "(", ...
Gets the controller from a Route @param Route $route Route @return bool|object The controller or false
[ "Gets", "the", "controller", "from", "a", "Route" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Service/RestUtils.php#L400-L410
train
libgraviton/graviton
src/Graviton/RestBundle/Service/RestUtils.php
RestUtils.serialize
public function serialize($result) { try { // array is serialized as an object {"0":{...},"1":{...},...} when data contains an empty objects // we serialize each item because we can assume this bug affects only root array element if (is_array($result) && array_keys($result) === range(0, count($result) - 1)) { $result = array_map( function ($item) { return $this->serializeContent($item); }, $result ); return '['.implode(',', array_filter($result)).']'; } return $this->serializeContent($result); } catch (\Exception $e) { throw new SerializationException($e); } }
php
public function serialize($result) { try { // array is serialized as an object {"0":{...},"1":{...},...} when data contains an empty objects // we serialize each item because we can assume this bug affects only root array element if (is_array($result) && array_keys($result) === range(0, count($result) - 1)) { $result = array_map( function ($item) { return $this->serializeContent($item); }, $result ); return '['.implode(',', array_filter($result)).']'; } return $this->serializeContent($result); } catch (\Exception $e) { throw new SerializationException($e); } }
[ "public", "function", "serialize", "(", "$", "result", ")", "{", "try", "{", "// array is serialized as an object {\"0\":{...},\"1\":{...},...} when data contains an empty objects", "// we serialize each item because we can assume this bug affects only root array element", "if", "(", "is...
Serialize the given record and throw an exception if something went wrong @param object|object[] $result Record(s) @throws \Graviton\ExceptionBundle\Exception\SerializationException @return string $content Json content
[ "Serialize", "the", "given", "record", "and", "throw", "an", "exception", "if", "something", "went", "wrong" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Service/RestUtils.php#L438-L458
train
libgraviton/graviton
src/Graviton/RestBundle/Service/RestUtils.php
RestUtils.validateRequest
public function validateRequest($content, DocumentModel $model) { $errors = $this->validateContent($content, $model); if (!empty($errors)) { throw new ValidationException($errors); } return $this->deserialize($content, $model->getEntityClass()); }
php
public function validateRequest($content, DocumentModel $model) { $errors = $this->validateContent($content, $model); if (!empty($errors)) { throw new ValidationException($errors); } return $this->deserialize($content, $model->getEntityClass()); }
[ "public", "function", "validateRequest", "(", "$", "content", ",", "DocumentModel", "$", "model", ")", "{", "$", "errors", "=", "$", "this", "->", "validateContent", "(", "$", "content", ",", "$", "model", ")", ";", "if", "(", "!", "empty", "(", "$", ...
Validates the current request on schema violations. If there are errors, the exception is thrown. If not, the deserialized record is returned. @param object|string $content \stdClass of the request content @param DocumentModel $model the model to check the schema for @return ValidationExceptionError|Object @throws \Exception
[ "Validates", "the", "current", "request", "on", "schema", "violations", ".", "If", "there", "are", "errors", "the", "exception", "is", "thrown", ".", "If", "not", "the", "deserialized", "record", "is", "returned", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Service/RestUtils.php#L494-L501
train
libgraviton/graviton
src/Graviton/RestBundle/ExclusionStrategy/SelectExclusionStrategy.php
SelectExclusionStrategy.createArrayByPath
private function createArrayByPath($path) { $keys = explode('.', $path); $val = true; $localArray = []; for ($i=count($keys)-1; $i>=0; $i--) { $localArray = [$keys[$i]=>$val]; $val = $localArray; } return $localArray; }
php
private function createArrayByPath($path) { $keys = explode('.', $path); $val = true; $localArray = []; for ($i=count($keys)-1; $i>=0; $i--) { $localArray = [$keys[$i]=>$val]; $val = $localArray; } return $localArray; }
[ "private", "function", "createArrayByPath", "(", "$", "path", ")", "{", "$", "keys", "=", "explode", "(", "'.'", ",", "$", "path", ")", ";", "$", "val", "=", "true", ";", "$", "localArray", "=", "[", "]", ";", "for", "(", "$", "i", "=", "count", ...
Convert dot string to array. @param string $path string dotted array @return array
[ "Convert", "dot", "string", "to", "array", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/ExclusionStrategy/SelectExclusionStrategy.php#L62-L72
train
libgraviton/graviton
src/Graviton/RestBundle/Model/DocumentModel.php
DocumentModel.setRepository
public function setRepository(DocumentRepository $repository) { $this->repository = $repository; $this->manager = $repository->getDocumentManager(); return $this; }
php
public function setRepository(DocumentRepository $repository) { $this->repository = $repository; $this->manager = $repository->getDocumentManager(); return $this; }
[ "public", "function", "setRepository", "(", "DocumentRepository", "$", "repository", ")", "{", "$", "this", "->", "repository", "=", "$", "repository", ";", "$", "this", "->", "manager", "=", "$", "repository", "->", "getDocumentManager", "(", ")", ";", "ret...
create new app model @param DocumentRepository $repository Repository of countries @return \Graviton\RestBundle\Model\DocumentModel
[ "create", "new", "app", "model" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Model/DocumentModel.php#L113-L118
train
libgraviton/graviton
src/Graviton/RestBundle/Model/DocumentModel.php
DocumentModel.find
public function find($documentId, $forceClear = false) { if ($forceClear) { $this->repository->clear(); } $result = $this->repository->find($documentId); if (empty($result)) { throw new NotFoundException("Entry with id " . $documentId . " not found!"); } return $result; }
php
public function find($documentId, $forceClear = false) { if ($forceClear) { $this->repository->clear(); } $result = $this->repository->find($documentId); if (empty($result)) { throw new NotFoundException("Entry with id " . $documentId . " not found!"); } return $result; }
[ "public", "function", "find", "(", "$", "documentId", ",", "$", "forceClear", "=", "false", ")", "{", "if", "(", "$", "forceClear", ")", "{", "$", "this", "->", "repository", "->", "clear", "(", ")", ";", "}", "$", "result", "=", "$", "this", "->",...
finds a single entity @param string $documentId id of entity to find @param boolean $forceClear if we should clear the repository prior to fetching @throws NotFoundException @return Object
[ "finds", "a", "single", "entity" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Model/DocumentModel.php#L165-L177
train
libgraviton/graviton
src/Graviton/RestBundle/Model/DocumentModel.php
DocumentModel.getSerialised
public function getSerialised($documentId, Request $request = null) { if (is_null($request)) { $request = Request::create(''); } $request->attributes->set('singleDocument', $documentId); $document = $this->queryService->getWithRequest($request, $this->repository); if (empty($document)) { throw new NotFoundException( sprintf( "Entry with id '%s' not found!", $documentId ) ); } return $this->restUtils->serialize($document); }
php
public function getSerialised($documentId, Request $request = null) { if (is_null($request)) { $request = Request::create(''); } $request->attributes->set('singleDocument', $documentId); $document = $this->queryService->getWithRequest($request, $this->repository); if (empty($document)) { throw new NotFoundException( sprintf( "Entry with id '%s' not found!", $documentId ) ); } return $this->restUtils->serialize($document); }
[ "public", "function", "getSerialised", "(", "$", "documentId", ",", "Request", "$", "request", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "request", ")", ")", "{", "$", "request", "=", "Request", "::", "create", "(", "''", ")", ";", "}", ...
Will attempt to find Document by ID. If config cache is enabled for document it will save it. @param string $documentId id of entity to find @param Request $request request @throws NotFoundException @return string Serialised object
[ "Will", "attempt", "to", "find", "Document", "by", "ID", ".", "If", "config", "cache", "is", "enabled", "for", "document", "it", "will", "save", "it", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Model/DocumentModel.php#L189-L208
train
libgraviton/graviton
src/Graviton/RestBundle/Model/DocumentModel.php
DocumentModel.deleteById
private function deleteById($id) { $builder = $this->repository->createQueryBuilder(); $builder ->remove() ->field('id')->equals($id) ->getQuery() ->execute(); }
php
private function deleteById($id) { $builder = $this->repository->createQueryBuilder(); $builder ->remove() ->field('id')->equals($id) ->getQuery() ->execute(); }
[ "private", "function", "deleteById", "(", "$", "id", ")", "{", "$", "builder", "=", "$", "this", "->", "repository", "->", "createQueryBuilder", "(", ")", ";", "$", "builder", "->", "remove", "(", ")", "->", "field", "(", "'id'", ")", "->", "equals", ...
A low level delete without any checks @param mixed $id record id @return void
[ "A", "low", "level", "delete", "without", "any", "checks" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Model/DocumentModel.php#L293-L301
train
libgraviton/graviton
src/Graviton/RestBundle/Model/DocumentModel.php
DocumentModel.checkIfOriginRecord
protected function checkIfOriginRecord($record) { if ($record instanceof RecordOriginInterface && !$record->isRecordOriginModifiable() ) { $values = $this->notModifiableOriginRecords; $originValue = strtolower(trim($record->getRecordOrigin())); if (in_array($originValue, $values)) { $msg = sprintf("Must not be one of the following keywords: %s", implode(', ', $values)); throw new RecordOriginModifiedException($msg); } } }
php
protected function checkIfOriginRecord($record) { if ($record instanceof RecordOriginInterface && !$record->isRecordOriginModifiable() ) { $values = $this->notModifiableOriginRecords; $originValue = strtolower(trim($record->getRecordOrigin())); if (in_array($originValue, $values)) { $msg = sprintf("Must not be one of the following keywords: %s", implode(', ', $values)); throw new RecordOriginModifiedException($msg); } } }
[ "protected", "function", "checkIfOriginRecord", "(", "$", "record", ")", "{", "if", "(", "$", "record", "instanceof", "RecordOriginInterface", "&&", "!", "$", "record", "->", "isRecordOriginModifiable", "(", ")", ")", "{", "$", "values", "=", "$", "this", "-...
Checks the recordOrigin attribute of a record and will throw an exception if value is not allowed @param Object $record record @return void
[ "Checks", "the", "recordOrigin", "attribute", "of", "a", "record", "and", "will", "throw", "an", "exception", "if", "value", "is", "not", "allowed" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Model/DocumentModel.php#L364-L378
train
libgraviton/graviton
src/Graviton/RestBundle/Model/DocumentModel.php
DocumentModel.dispatchModelEvent
private function dispatchModelEvent($action, $collection) { if (!($this->repository instanceof DocumentRepository)) { return; } if (!method_exists($collection, 'getId')) { return; } $event = new ModelEvent(); $event->setCollectionId($collection->getId()); $event->setActionByDispatchName($action); $event->setCollectionName($this->repository->getClassMetadata()->getCollection()); $event->setCollectionClass($this->repository->getClassName()); $event->setCollection($collection); $this->eventDispatcher->dispatch($action, $event); }
php
private function dispatchModelEvent($action, $collection) { if (!($this->repository instanceof DocumentRepository)) { return; } if (!method_exists($collection, 'getId')) { return; } $event = new ModelEvent(); $event->setCollectionId($collection->getId()); $event->setActionByDispatchName($action); $event->setCollectionName($this->repository->getClassMetadata()->getCollection()); $event->setCollectionClass($this->repository->getClassName()); $event->setCollection($collection); $this->eventDispatcher->dispatch($action, $event); }
[ "private", "function", "dispatchModelEvent", "(", "$", "action", ",", "$", "collection", ")", "{", "if", "(", "!", "(", "$", "this", "->", "repository", "instanceof", "DocumentRepository", ")", ")", "{", "return", ";", "}", "if", "(", "!", "method_exists",...
Will fire a ModelEvent @param string $action insert or update @param Object $collection the changed Document @return void
[ "Will", "fire", "a", "ModelEvent" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Model/DocumentModel.php#L390-L407
train
libgraviton/graviton
src/Graviton/SecurityBundle/Service/SecurityUtils.php
SecurityUtils.isSecurityUser
public function isSecurityUser() { if ($this->securityUser) { return true; } /** @var PreAuthenticatedToken $token */ if (($token = $this->tokenStorage->getToken()) && ($user = $token->getUser()) instanceof UserInterface ) { $this->securityUser = $user; return true; } return false; }
php
public function isSecurityUser() { if ($this->securityUser) { return true; } /** @var PreAuthenticatedToken $token */ if (($token = $this->tokenStorage->getToken()) && ($user = $token->getUser()) instanceof UserInterface ) { $this->securityUser = $user; return true; } return false; }
[ "public", "function", "isSecurityUser", "(", ")", "{", "if", "(", "$", "this", "->", "securityUser", ")", "{", "return", "true", ";", "}", "/** @var PreAuthenticatedToken $token */", "if", "(", "(", "$", "token", "=", "$", "this", "->", "tokenStorage", "->",...
Check if there is a security user @return bool
[ "Check", "if", "there", "is", "a", "security", "user" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SecurityBundle/Service/SecurityUtils.php#L43-L56
train
libgraviton/graviton
src/Graviton/SecurityBundle/Service/SecurityUtils.php
SecurityUtils.hasRole
public function hasRole($role) { if ($this->isSecurityUser()) { return (bool) $this->securityUser->hasRole($role); } throw new UsernameNotFoundException('No security user'); }
php
public function hasRole($role) { if ($this->isSecurityUser()) { return (bool) $this->securityUser->hasRole($role); } throw new UsernameNotFoundException('No security user'); }
[ "public", "function", "hasRole", "(", "$", "role", ")", "{", "if", "(", "$", "this", "->", "isSecurityUser", "(", ")", ")", "{", "return", "(", "bool", ")", "$", "this", "->", "securityUser", "->", "hasRole", "(", "$", "role", ")", ";", "}", "throw...
Check if current user is in Role @param string $role User role expected @return bool @throws UsernameNotFoundException
[ "Check", "if", "current", "user", "is", "in", "Role" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SecurityBundle/Service/SecurityUtils.php#L93-L99
train
libgraviton/graviton
src/Graviton/SecurityBundle/Service/SecurityUtils.php
SecurityUtils.generateUuid
private function generateUuid() { if (!function_exists('openssl_random_pseudo_bytes')) { $this->requestId = uniqid('unq', true); } else { $data = openssl_random_pseudo_bytes(16); // set version to 0100 $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set bits 6-7 to 10 $data[8] = chr(ord($data[8]) & 0x3f | 0x80); $this->requestId = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); } return $this->requestId; }
php
private function generateUuid() { if (!function_exists('openssl_random_pseudo_bytes')) { $this->requestId = uniqid('unq', true); } else { $data = openssl_random_pseudo_bytes(16); // set version to 0100 $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set bits 6-7 to 10 $data[8] = chr(ord($data[8]) & 0x3f | 0x80); $this->requestId = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); } return $this->requestId; }
[ "private", "function", "generateUuid", "(", ")", "{", "if", "(", "!", "function_exists", "(", "'openssl_random_pseudo_bytes'", ")", ")", "{", "$", "this", "->", "requestId", "=", "uniqid", "(", "'unq'", ",", "true", ")", ";", "}", "else", "{", "$", "data...
Generate a unique UUID. @return string
[ "Generate", "a", "unique", "UUID", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SecurityBundle/Service/SecurityUtils.php#L119-L133
train
libgraviton/graviton
src/Graviton/I18nBundle/Serializer/Handler/TranslatableHandler.php
TranslatableHandler.serializeTranslatableToJson
public function serializeTranslatableToJson( JsonSerializationVisitor $visitor, $translatable, array $type, Context $context ) { if (is_array($translatable) && empty($translatable)) { return $translatable; } $translations = $translatable->getTranslations(); $defaultLanguage = $this->utils->getDefaultLanguage(); if (isset($translations[$defaultLanguage]) && count($translations) != $this->utils->getLanguages()) { // languages missing $original = $translations[$defaultLanguage]; $translated = $this->utils->getTranslatedField($original); $translatable->setTranslations( array_merge( $translated, $translatable->getTranslations() ) ); } return $translatable; }
php
public function serializeTranslatableToJson( JsonSerializationVisitor $visitor, $translatable, array $type, Context $context ) { if (is_array($translatable) && empty($translatable)) { return $translatable; } $translations = $translatable->getTranslations(); $defaultLanguage = $this->utils->getDefaultLanguage(); if (isset($translations[$defaultLanguage]) && count($translations) != $this->utils->getLanguages()) { // languages missing $original = $translations[$defaultLanguage]; $translated = $this->utils->getTranslatedField($original); $translatable->setTranslations( array_merge( $translated, $translatable->getTranslations() ) ); } return $translatable; }
[ "public", "function", "serializeTranslatableToJson", "(", "JsonSerializationVisitor", "$", "visitor", ",", "$", "translatable", ",", "array", "$", "type", ",", "Context", "$", "context", ")", "{", "if", "(", "is_array", "(", "$", "translatable", ")", "&&", "em...
Serialize Translatable to JSON @param JsonSerializationVisitor $visitor Visitor @param Translatable $translatable translatable @param array $type Type @param Context $context Context @return string|null
[ "Serialize", "Translatable", "to", "JSON" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Serializer/Handler/TranslatableHandler.php#L47-L73
train
libgraviton/graviton
src/Graviton/I18nBundle/Serializer/Handler/TranslatableHandler.php
TranslatableHandler.deserializeTranslatableFromJson
public function deserializeTranslatableFromJson( JsonDeserializationVisitor $visitor, $data, array $type, Context $context ) { if (!is_null($data)) { $translatable = Translatable::createFromTranslations($data); $this->utils->persistTranslatable($translatable); return $translatable; } return null; }
php
public function deserializeTranslatableFromJson( JsonDeserializationVisitor $visitor, $data, array $type, Context $context ) { if (!is_null($data)) { $translatable = Translatable::createFromTranslations($data); $this->utils->persistTranslatable($translatable); return $translatable; } return null; }
[ "public", "function", "deserializeTranslatableFromJson", "(", "JsonDeserializationVisitor", "$", "visitor", ",", "$", "data", ",", "array", "$", "type", ",", "Context", "$", "context", ")", "{", "if", "(", "!", "is_null", "(", "$", "data", ")", ")", "{", "...
Serialize Translatable from JSON @param JsonDeserializationVisitor $visitor Visitor @param array $data translation array as we represent if to users @param array $type Type @param Context $context Context @return Translatable|null
[ "Serialize", "Translatable", "from", "JSON" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Serializer/Handler/TranslatableHandler.php#L85-L97
train
libgraviton/graviton
src/Graviton/BundleBundle/DependencyInjection/GravitonBundleExtension.php
GravitonBundleExtension.loadFiles
private function loadFiles($dir, ContainerBuilder $container, array $allowed) { $locator = new FileLocator($dir); $xmlLoader = new Loader\XmlFileLoader($container, $locator); $ymlLoader = new Loader\YamlFileLoader($container, $locator); $finder = new Finder(); $finder->files()->in($dir); /** @var SplFileInfo $file */ foreach ($finder as $file) { if (!in_array($file->getFilename(), $allowed)) { continue; } if ('xml' == $file->getExtension()) { $xmlLoader->load($file->getRealPath()); } elseif ('yml' == $file->getExtension()) { $ymlLoader->load($file->getRealPath()); } } }
php
private function loadFiles($dir, ContainerBuilder $container, array $allowed) { $locator = new FileLocator($dir); $xmlLoader = new Loader\XmlFileLoader($container, $locator); $ymlLoader = new Loader\YamlFileLoader($container, $locator); $finder = new Finder(); $finder->files()->in($dir); /** @var SplFileInfo $file */ foreach ($finder as $file) { if (!in_array($file->getFilename(), $allowed)) { continue; } if ('xml' == $file->getExtension()) { $xmlLoader->load($file->getRealPath()); } elseif ('yml' == $file->getExtension()) { $ymlLoader->load($file->getRealPath()); } } }
[ "private", "function", "loadFiles", "(", "$", "dir", ",", "ContainerBuilder", "$", "container", ",", "array", "$", "allowed", ")", "{", "$", "locator", "=", "new", "FileLocator", "(", "$", "dir", ")", ";", "$", "xmlLoader", "=", "new", "Loader", "\\", ...
Load config files, xml or yml. If will only include the config file if it's in the allowed array. @param string $dir folder @param ContainerBuilder $container Sf container @param array $allowed array of files to load @return void
[ "Load", "config", "files", "xml", "or", "yml", ".", "If", "will", "only", "include", "the", "config", "file", "if", "it", "s", "in", "the", "allowed", "array", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/BundleBundle/DependencyInjection/GravitonBundleExtension.php#L88-L108
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Command/BundeBundleUnloadCommand.php
BundeBundleUnloadCommand.getContentData
private function getContentData($content) { $res = []; $res['startStringPos'] = strpos($content, $this->startString) + strlen($this->startString); $res['endStringPos'] = strpos($content, $this->endString); $res['bundleList'] = substr($content, $res['startStringPos'], ($res['endStringPos'] - $res['startStringPos'])); return $res; }
php
private function getContentData($content) { $res = []; $res['startStringPos'] = strpos($content, $this->startString) + strlen($this->startString); $res['endStringPos'] = strpos($content, $this->endString); $res['bundleList'] = substr($content, $res['startStringPos'], ($res['endStringPos'] - $res['startStringPos'])); return $res; }
[ "private", "function", "getContentData", "(", "$", "content", ")", "{", "$", "res", "=", "[", "]", ";", "$", "res", "[", "'startStringPos'", "]", "=", "strpos", "(", "$", "content", ",", "$", "this", "->", "startString", ")", "+", "strlen", "(", "$",...
gets our positions and the bundlelist @param string $content the bundlebundle content @return array data
[ "gets", "our", "positions", "and", "the", "bundlelist" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/BundeBundleUnloadCommand.php#L136-L143
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Command/BundeBundleUnloadCommand.php
BundeBundleUnloadCommand.getNewContent
private function getNewContent($content, array $newBundleList) { $contentData = $this->getContentData($content); $beforePart = substr($content, 0, $contentData['startStringPos']); $endPart = substr($content, $contentData['endStringPos']); return $beforePart.PHP_EOL.implode(','.PHP_EOL, $newBundleList).PHP_EOL.$endPart; }
php
private function getNewContent($content, array $newBundleList) { $contentData = $this->getContentData($content); $beforePart = substr($content, 0, $contentData['startStringPos']); $endPart = substr($content, $contentData['endStringPos']); return $beforePart.PHP_EOL.implode(','.PHP_EOL, $newBundleList).PHP_EOL.$endPart; }
[ "private", "function", "getNewContent", "(", "$", "content", ",", "array", "$", "newBundleList", ")", "{", "$", "contentData", "=", "$", "this", "->", "getContentData", "(", "$", "content", ")", ";", "$", "beforePart", "=", "substr", "(", "$", "content", ...
replaces the stuff in the content @param string $content the bundlebundle content @param array $newBundleList new bundle list @return string new content
[ "replaces", "the", "stuff", "in", "the", "content" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/BundeBundleUnloadCommand.php#L153-L161
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Command/BundeBundleUnloadCommand.php
BundeBundleUnloadCommand.filterBundleList
private function filterBundleList(array $bundleList) { $groups = []; foreach ($_ENV as $name => $val) { if (substr($name, 0, strlen($this->envDynGroupPrefix)) == $this->envDynGroupPrefix) { $groups[substr($name, strlen($this->envDynGroupPrefix))] = $val; } } if (empty($groups)) { // no groups.. exit return $bundleList; } foreach ($groups as $groupName => $filter) { if (isset($_ENV[$this->envDynSettingPrefix.$groupName]) && $_ENV[$this->envDynSettingPrefix.$groupName] == 'false' ) { $bundleList = array_filter( $bundleList, function ($value) use ($filter) { if (preg_match('/'.$filter.'/i', $value) || empty(trim($value))) { return false; } return true; } ); } } return $bundleList; }
php
private function filterBundleList(array $bundleList) { $groups = []; foreach ($_ENV as $name => $val) { if (substr($name, 0, strlen($this->envDynGroupPrefix)) == $this->envDynGroupPrefix) { $groups[substr($name, strlen($this->envDynGroupPrefix))] = $val; } } if (empty($groups)) { // no groups.. exit return $bundleList; } foreach ($groups as $groupName => $filter) { if (isset($_ENV[$this->envDynSettingPrefix.$groupName]) && $_ENV[$this->envDynSettingPrefix.$groupName] == 'false' ) { $bundleList = array_filter( $bundleList, function ($value) use ($filter) { if (preg_match('/'.$filter.'/i', $value) || empty(trim($value))) { return false; } return true; } ); } } return $bundleList; }
[ "private", "function", "filterBundleList", "(", "array", "$", "bundleList", ")", "{", "$", "groups", "=", "[", "]", ";", "foreach", "(", "$", "_ENV", "as", "$", "name", "=>", "$", "val", ")", "{", "if", "(", "substr", "(", "$", "name", ",", "0", ...
filters the bundlelist according to ENV vars @param array $bundleList bundle list @return array filtered bundle list
[ "filters", "the", "bundlelist", "according", "to", "ENV", "vars" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/BundeBundleUnloadCommand.php#L170-L201
train
libgraviton/graviton
src/Graviton/DocumentBundle/Serializer/Handler/ExtReferenceHandler.php
ExtReferenceHandler.validateExtRef
public function validateExtRef(ConstraintEventFormat $event) { $schema = $event->getSchema(); if (!isset($schema->format) || (isset($schema->format) && $schema->format != 'extref')) { return; } $value = $event->getElement(); // 1st) can it be converted to extref? try { $this->converter->getExtReference( $value ); } catch (\InvalidArgumentException $e) { $event->addError(sprintf('Value "%s" is not a valid extref.', $value)); return; } // 2nd) if yes, correct collection(s)? if (!isset($schema->{'x-collection'})) { return; } $collections = $schema->{'x-collection'}; if (in_array('*', $collections)) { return; } $allValues = implode('-', $collections); if (!isset($this->extRefPatternCache[$allValues])) { $paths = []; foreach ($collections as $url) { $urlParts = parse_url($url); $paths[] = str_replace('/', '\\/', $urlParts['path']); } $this->extRefPatternCache[$allValues] = '(' . implode('|', $paths) . ')(' . ActionUtils::ID_PATTERN . ')$'; } $stringConstraint = $event->getFactory()->createInstanceFor('string'); $schema->format = null; $schema->pattern = $this->extRefPatternCache[$allValues]; $stringConstraint->check($value, $schema, $event->getPath()); if (!empty($stringConstraint->getErrors())) { $event->addError(sprintf('Value "%s" does not refer to a correct collection for this extref.', $value)); } }
php
public function validateExtRef(ConstraintEventFormat $event) { $schema = $event->getSchema(); if (!isset($schema->format) || (isset($schema->format) && $schema->format != 'extref')) { return; } $value = $event->getElement(); // 1st) can it be converted to extref? try { $this->converter->getExtReference( $value ); } catch (\InvalidArgumentException $e) { $event->addError(sprintf('Value "%s" is not a valid extref.', $value)); return; } // 2nd) if yes, correct collection(s)? if (!isset($schema->{'x-collection'})) { return; } $collections = $schema->{'x-collection'}; if (in_array('*', $collections)) { return; } $allValues = implode('-', $collections); if (!isset($this->extRefPatternCache[$allValues])) { $paths = []; foreach ($collections as $url) { $urlParts = parse_url($url); $paths[] = str_replace('/', '\\/', $urlParts['path']); } $this->extRefPatternCache[$allValues] = '(' . implode('|', $paths) . ')(' . ActionUtils::ID_PATTERN . ')$'; } $stringConstraint = $event->getFactory()->createInstanceFor('string'); $schema->format = null; $schema->pattern = $this->extRefPatternCache[$allValues]; $stringConstraint->check($value, $schema, $event->getPath()); if (!empty($stringConstraint->getErrors())) { $event->addError(sprintf('Value "%s" does not refer to a correct collection for this extref.', $value)); } }
[ "public", "function", "validateExtRef", "(", "ConstraintEventFormat", "$", "event", ")", "{", "$", "schema", "=", "$", "event", "->", "getSchema", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "schema", "->", "format", ")", "||", "(", "isset", "(",...
Schema validation function for extref values. Will be executed when a user submits an extref @param ConstraintEventFormat $event event @return void
[ "Schema", "validation", "function", "for", "extref", "values", ".", "Will", "be", "executed", "when", "a", "user", "submits", "an", "extref" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Serializer/Handler/ExtReferenceHandler.php#L98-L147
train
libgraviton/graviton
src/Graviton/ProxyBundle/Definition/Loader/LoaderFactory.php
LoaderFactory.getLoaderDefinition
public function getLoaderDefinition($key) { if (array_key_exists($key, $this->loader)) { return $this->loader[$key]; } return null; }
php
public function getLoaderDefinition($key) { if (array_key_exists($key, $this->loader)) { return $this->loader[$key]; } return null; }
[ "public", "function", "getLoaderDefinition", "(", "$", "key", ")", "{", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "loader", ")", ")", "{", "return", "$", "this", "->", "loader", "[", "$", "key", "]", ";", "}", "return", ...
Provides the definition loader identified by the given key. @param string $key Name of the loader to be returned @return LoaderInterface|null
[ "Provides", "the", "definition", "loader", "identified", "by", "the", "given", "key", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Definition/Loader/LoaderFactory.php#L44-L51
train
libgraviton/graviton
src/Graviton/SchemaBundle/Serializer/Handler/SchemaEnumHandler.php
SchemaEnumHandler.serializeSchemaEnumToJson
public function serializeSchemaEnumToJson( JsonSerializationVisitor $visitor, SchemaEnum $schemaEnum, array $type, Context $context ) { return $schemaEnum->getValues(); }
php
public function serializeSchemaEnumToJson( JsonSerializationVisitor $visitor, SchemaEnum $schemaEnum, array $type, Context $context ) { return $schemaEnum->getValues(); }
[ "public", "function", "serializeSchemaEnumToJson", "(", "JsonSerializationVisitor", "$", "visitor", ",", "SchemaEnum", "$", "schemaEnum", ",", "array", "$", "type", ",", "Context", "$", "context", ")", "{", "return", "$", "schemaEnum", "->", "getValues", "(", ")...
Serialize SchemaEnum to JSON @param JsonSerializationVisitor $visitor Visitor @param SchemaEnum $schemaEnum enum @param array $type Type @param Context $context Context @return array
[ "Serialize", "SchemaEnum", "to", "JSON" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Serializer/Handler/SchemaEnumHandler.php#L30-L37
train
libgraviton/graviton
src/Graviton/DocumentBundle/Serializer/Listener/EmptyExtRefListener.php
EmptyExtRefListener.onPreSerialize
public function onPreSerialize(PreSerializeEvent $event) { $object = $event->getObject(); if ($object instanceof ExtRefHoldingDocumentInterface && $object->isEmptyExtRefObject() === true) { $event->setType('Empty', [$object]); } }
php
public function onPreSerialize(PreSerializeEvent $event) { $object = $event->getObject(); if ($object instanceof ExtRefHoldingDocumentInterface && $object->isEmptyExtRefObject() === true) { $event->setType('Empty', [$object]); } }
[ "public", "function", "onPreSerialize", "(", "PreSerializeEvent", "$", "event", ")", "{", "$", "object", "=", "$", "event", "->", "getObject", "(", ")", ";", "if", "(", "$", "object", "instanceof", "ExtRefHoldingDocumentInterface", "&&", "$", "object", "->", ...
if is empty extref object, divert serializing to type Empty, which creates a null instead of empty object @param PreSerializeEvent $event event @return void @throws \Exception
[ "if", "is", "empty", "extref", "object", "divert", "serializing", "to", "type", "Empty", "which", "creates", "a", "null", "instead", "of", "empty", "object" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Serializer/Listener/EmptyExtRefListener.php#L28-L34
train
libgraviton/graviton
src/Graviton/SecurityBundle/Authentication/Strategies/SameSubnetStrategy.php
SameSubnetStrategy.apply
public function apply(Request $request) { if (IpUtils::checkIp($request->getClientIp(), $this->subnet)) { $name = $this->extractFieldInfo($request->headers, $this->headerField); if (!empty($name)) { return $name; } } return ''; }
php
public function apply(Request $request) { if (IpUtils::checkIp($request->getClientIp(), $this->subnet)) { $name = $this->extractFieldInfo($request->headers, $this->headerField); if (!empty($name)) { return $name; } } return ''; }
[ "public", "function", "apply", "(", "Request", "$", "request", ")", "{", "if", "(", "IpUtils", "::", "checkIp", "(", "$", "request", "->", "getClientIp", "(", ")", ",", "$", "this", "->", "subnet", ")", ")", "{", "$", "name", "=", "$", "this", "->"...
Applies the defined strategy on the provided request. @param Request $request request to handle @return string
[ "Applies", "the", "defined", "strategy", "on", "the", "provided", "request", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SecurityBundle/Authentication/Strategies/SameSubnetStrategy.php#L54-L64
train
konduto/php-sdk
src/Models/BaseModel.php
BaseModel.get
public function get($field) { return key_exists($field, $this->_properties) ? $this->_properties[$field] : null; }
php
public function get($field) { return key_exists($field, $this->_properties) ? $this->_properties[$field] : null; }
[ "public", "function", "get", "(", "$", "field", ")", "{", "return", "key_exists", "(", "$", "field", ",", "$", "this", "->", "_properties", ")", "?", "$", "this", "->", "_properties", "[", "$", "field", "]", ":", "null", ";", "}" ]
Return the value of the field. @param string $field @return mixed
[ "Return", "the", "value", "of", "the", "field", "." ]
ff095590c30307897c557f980845f613ff351585
https://github.com/konduto/php-sdk/blob/ff095590c30307897c557f980845f613ff351585/src/Models/BaseModel.php#L52-L54
train
konduto/php-sdk
src/Models/BaseModel.php
BaseModel.addField
public function addField($field, $value=null) { $this->fields[] = $field; if ($value != null) $this->set($field, $value); }
php
public function addField($field, $value=null) { $this->fields[] = $field; if ($value != null) $this->set($field, $value); }
[ "public", "function", "addField", "(", "$", "field", ",", "$", "value", "=", "null", ")", "{", "$", "this", "->", "fields", "[", "]", "=", "$", "field", ";", "if", "(", "$", "value", "!=", "null", ")", "$", "this", "->", "set", "(", "$", "field...
Add a new field that can be enter in the json array representation of the model. @param string $field name of the field @param mixed $value a value to be set
[ "Add", "a", "new", "field", "that", "can", "be", "enter", "in", "the", "json", "array", "representation", "of", "the", "model", "." ]
ff095590c30307897c557f980845f613ff351585
https://github.com/konduto/php-sdk/blob/ff095590c30307897c557f980845f613ff351585/src/Models/BaseModel.php#L62-L65
train
libgraviton/graviton
src/Graviton/AnalyticsBundle/Manager/AnalyticsManager.php
AnalyticsManager.convertData
private function convertData(array $data = null) { if (!is_array($data)) { return $data; } foreach ($data as $key => $val) { /** convert dbrefs */ if (is_array($val) && isset($val['$ref']) && isset($val['$id'])) { $data[$key] = $this->convertData( $this->resolveObject($val['$ref'], $val['$id']) ); } elseif (is_array($val)) { $data[$key] = $this->convertData($val); } /** convert mongodate to text dates **/ if ($val instanceof \MongoDate) { $data[$key] = $this->dateConverter->formatDateTime($val->toDateTime()); } /** convert mongoid */ if ($val instanceof \MongoId) { $data[$key] = (string) $val; } } return $data; }
php
private function convertData(array $data = null) { if (!is_array($data)) { return $data; } foreach ($data as $key => $val) { /** convert dbrefs */ if (is_array($val) && isset($val['$ref']) && isset($val['$id'])) { $data[$key] = $this->convertData( $this->resolveObject($val['$ref'], $val['$id']) ); } elseif (is_array($val)) { $data[$key] = $this->convertData($val); } /** convert mongodate to text dates **/ if ($val instanceof \MongoDate) { $data[$key] = $this->dateConverter->formatDateTime($val->toDateTime()); } /** convert mongoid */ if ($val instanceof \MongoId) { $data[$key] = (string) $val; } } return $data; }
[ "private", "function", "convertData", "(", "array", "$", "data", "=", "null", ")", "{", "if", "(", "!", "is_array", "(", "$", "data", ")", ")", "{", "return", "$", "data", ";", "}", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "val",...
convert various things in the data that should be rendered differently @param array $data data @return array data with changed things
[ "convert", "various", "things", "in", "the", "data", "that", "should", "be", "rendered", "differently" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/AnalyticsBundle/Manager/AnalyticsManager.php#L145-L171
train
libgraviton/graviton
src/Graviton/AnalyticsBundle/Manager/AnalyticsManager.php
AnalyticsManager.resolveObject
private function resolveObject($collection, $id) { return $this->connection->selectCollection($this->databaseName, $collection)->findOne(['_id' => $id]); }
php
private function resolveObject($collection, $id) { return $this->connection->selectCollection($this->databaseName, $collection)->findOne(['_id' => $id]); }
[ "private", "function", "resolveObject", "(", "$", "collection", ",", "$", "id", ")", "{", "return", "$", "this", "->", "connection", "->", "selectCollection", "(", "$", "this", "->", "databaseName", ",", "$", "collection", ")", "->", "findOne", "(", "[", ...
resolves a dbref array into the actual object @param string $collection collection name @param string $id record id @return array|null record as array or null
[ "resolves", "a", "dbref", "array", "into", "the", "actual", "object" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/AnalyticsBundle/Manager/AnalyticsManager.php#L181-L184
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Definition/JsonDefinitionHash.php
JsonDefinitionHash.getDefAsArray
public function getDefAsArray() { return array_replace( [ 'name' => $this->getName(), 'type' => $this->getType(), 'exposedName' => $this->getName(), 'doctrineType' => $this->getTypeDoctrine(), 'serializerType' => $this->getTypeSerializer(), 'relType' => self::REL_TYPE_EMBED, 'isClassType' => true, 'constraints' => [], 'required' => false, 'searchable' => 0, ], $this->definition === null ? [ 'required' => $this->isRequired() ] : [ 'exposedName' => $this->definition->getExposeAs() ?: $this->getName(), 'title' => $this->definition->getTitle(), 'description' => $this->definition->getDescription(), 'readOnly' => $this->definition->getReadOnly(), 'required' => $this->definition->getRequired(), 'searchable' => $this->definition->getSearchable(), 'constraints' => array_map( [Utils\ConstraintNormalizer::class, 'normalize'], $this->definition->getConstraints() ), ] ); }
php
public function getDefAsArray() { return array_replace( [ 'name' => $this->getName(), 'type' => $this->getType(), 'exposedName' => $this->getName(), 'doctrineType' => $this->getTypeDoctrine(), 'serializerType' => $this->getTypeSerializer(), 'relType' => self::REL_TYPE_EMBED, 'isClassType' => true, 'constraints' => [], 'required' => false, 'searchable' => 0, ], $this->definition === null ? [ 'required' => $this->isRequired() ] : [ 'exposedName' => $this->definition->getExposeAs() ?: $this->getName(), 'title' => $this->definition->getTitle(), 'description' => $this->definition->getDescription(), 'readOnly' => $this->definition->getReadOnly(), 'required' => $this->definition->getRequired(), 'searchable' => $this->definition->getSearchable(), 'constraints' => array_map( [Utils\ConstraintNormalizer::class, 'normalize'], $this->definition->getConstraints() ), ] ); }
[ "public", "function", "getDefAsArray", "(", ")", "{", "return", "array_replace", "(", "[", "'name'", "=>", "$", "this", "->", "getName", "(", ")", ",", "'type'", "=>", "$", "this", "->", "getType", "(", ")", ",", "'exposedName'", "=>", "$", "this", "->...
Returns the definition as array.. @return array the definition
[ "Returns", "the", "definition", "as", "array", ".." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinitionHash.php#L62-L92
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Definition/JsonDefinitionHash.php
JsonDefinitionHash.isRequired
public function isRequired() { $isRequired = false; // see if on the first level of fields we have a required=true in the definition foreach ($this->fields as $field) { if ($field instanceof JsonDefinitionField && $field->getDef() instanceof Field && $field->getDef()->getRequired() === true ) { $isRequired = true; } } return $isRequired; }
php
public function isRequired() { $isRequired = false; // see if on the first level of fields we have a required=true in the definition foreach ($this->fields as $field) { if ($field instanceof JsonDefinitionField && $field->getDef() instanceof Field && $field->getDef()->getRequired() === true ) { $isRequired = true; } } return $isRequired; }
[ "public", "function", "isRequired", "(", ")", "{", "$", "isRequired", "=", "false", ";", "// see if on the first level of fields we have a required=true in the definition", "foreach", "(", "$", "this", "->", "fields", "as", "$", "field", ")", "{", "if", "(", "$", ...
in an 'anonymous' hash situation, we will check if any children are required @return bool if required or not
[ "in", "an", "anonymous", "hash", "situation", "we", "will", "check", "if", "any", "children", "are", "required" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinitionHash.php#L120-L135
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Definition/JsonDefinitionHash.php
JsonDefinitionHash.cloneFieldDefinition
private function cloneFieldDefinition(Schema\Field $field) { $clone = clone $field; $clone->setName(preg_replace('/^'.preg_quote($this->name, '/').'\.(\d+\.)*/', '', $clone->getName())); return $clone; }
php
private function cloneFieldDefinition(Schema\Field $field) { $clone = clone $field; $clone->setName(preg_replace('/^'.preg_quote($this->name, '/').'\.(\d+\.)*/', '', $clone->getName())); return $clone; }
[ "private", "function", "cloneFieldDefinition", "(", "Schema", "\\", "Field", "$", "field", ")", "{", "$", "clone", "=", "clone", "$", "field", ";", "$", "clone", "->", "setName", "(", "preg_replace", "(", "'/^'", ".", "preg_quote", "(", "$", "this", "->"...
Clone field definition @param Schema\Field $field Field @return Schema\Field
[ "Clone", "field", "definition" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinitionHash.php#L220-L225
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Definition/JsonDefinitionHash.php
JsonDefinitionHash.processParentRelation
private function processParentRelation(Schema\Relation $relation) { $prefixRegex = '/^'.preg_quote($this->name, '/').'\.(\d+\.)*(?P<sub>.*)/'; if (!preg_match($prefixRegex, $relation->getLocalProperty(), $matches)) { return null; } $clone = clone $relation; $clone->setLocalProperty($matches['sub']); return $clone; }
php
private function processParentRelation(Schema\Relation $relation) { $prefixRegex = '/^'.preg_quote($this->name, '/').'\.(\d+\.)*(?P<sub>.*)/'; if (!preg_match($prefixRegex, $relation->getLocalProperty(), $matches)) { return null; } $clone = clone $relation; $clone->setLocalProperty($matches['sub']); return $clone; }
[ "private", "function", "processParentRelation", "(", "Schema", "\\", "Relation", "$", "relation", ")", "{", "$", "prefixRegex", "=", "'/^'", ".", "preg_quote", "(", "$", "this", "->", "name", ",", "'/'", ")", ".", "'\\.(\\d+\\.)*(?P<sub>.*)/'", ";", "if", "(...
Process parent relation @param Schema\Relation $relation Parent relation @return Schema\Relation|null
[ "Process", "parent", "relation" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinitionHash.php#L233-L243
train
libgraviton/graviton
src/Graviton/GeneratorBundle/Definition/JsonDefinitionHash.php
JsonDefinitionHash.getClassName
private function getClassName($fq = false) { $className = ucfirst($this->parent->getId()).ucfirst($this->getName()); if ($fq) { $className = $this->parent->getNamespace().'\\Document\\'.$className; } return $className; }
php
private function getClassName($fq = false) { $className = ucfirst($this->parent->getId()).ucfirst($this->getName()); if ($fq) { $className = $this->parent->getNamespace().'\\Document\\'.$className; } return $className; }
[ "private", "function", "getClassName", "(", "$", "fq", "=", "false", ")", "{", "$", "className", "=", "ucfirst", "(", "$", "this", "->", "parent", "->", "getId", "(", ")", ")", ".", "ucfirst", "(", "$", "this", "->", "getName", "(", ")", ")", ";", ...
Returns the class name of this hash, possibly taking the parent element into the name. this string here results in the name of the generated Document. @param boolean $fq if true, we'll return the class name full qualified @return string
[ "Returns", "the", "class", "name", "of", "this", "hash", "possibly", "taking", "the", "parent", "element", "into", "the", "name", ".", "this", "string", "here", "results", "in", "the", "name", "of", "the", "generated", "Document", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/JsonDefinitionHash.php#L254-L262
train
libgraviton/graviton
src/Graviton/DocumentBundle/Service/ExtReferenceConverter.php
ExtReferenceConverter.getExtReference
public function getExtReference($url) { $path = parse_url($url, PHP_URL_PATH); if ($path === false) { throw new \InvalidArgumentException(sprintf('URL %s', $url)); } $id = null; $collection = null; if (!isset($this->resolvingCache[$path])) { foreach ($this->router->getRouteCollection()->all() as $route) { list($collection, $id) = $this->getDataFromRoute($route, $path); if ($collection !== null && $id !== null) { $this->resolvingCache[$path] = $route; return ExtReference::create($collection, $id); } } } else { list($collection, $id) = $this->getDataFromRoute($this->resolvingCache[$path], $path); return ExtReference::create($collection, $id); } throw new \InvalidArgumentException(sprintf('Could not read URL %s', $url)); }
php
public function getExtReference($url) { $path = parse_url($url, PHP_URL_PATH); if ($path === false) { throw new \InvalidArgumentException(sprintf('URL %s', $url)); } $id = null; $collection = null; if (!isset($this->resolvingCache[$path])) { foreach ($this->router->getRouteCollection()->all() as $route) { list($collection, $id) = $this->getDataFromRoute($route, $path); if ($collection !== null && $id !== null) { $this->resolvingCache[$path] = $route; return ExtReference::create($collection, $id); } } } else { list($collection, $id) = $this->getDataFromRoute($this->resolvingCache[$path], $path); return ExtReference::create($collection, $id); } throw new \InvalidArgumentException(sprintf('Could not read URL %s', $url)); }
[ "public", "function", "getExtReference", "(", "$", "url", ")", "{", "$", "path", "=", "parse_url", "(", "$", "url", ",", "PHP_URL_PATH", ")", ";", "if", "(", "$", "path", "===", "false", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", ...
return the extref from URL @param string $url Extref URL @return ExtReference @throws \InvalidArgumentException
[ "return", "the", "extref", "from", "URL" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Service/ExtReferenceConverter.php#L54-L78
train
libgraviton/graviton
src/Graviton/DocumentBundle/Service/ExtReferenceConverter.php
ExtReferenceConverter.getUrl
public function getUrl(ExtReference $extReference) { if (!isset($this->mapping[$extReference->getRef()])) { throw new \InvalidArgumentException( sprintf( 'Could not create URL from extref "%s"', json_encode($extReference) ) ); } return $this->router->generate( $this->mapping[$extReference->getRef()].'.get', ['id' => $extReference->getId()], UrlGeneratorInterface::ABSOLUTE_URL ); }
php
public function getUrl(ExtReference $extReference) { if (!isset($this->mapping[$extReference->getRef()])) { throw new \InvalidArgumentException( sprintf( 'Could not create URL from extref "%s"', json_encode($extReference) ) ); } return $this->router->generate( $this->mapping[$extReference->getRef()].'.get', ['id' => $extReference->getId()], UrlGeneratorInterface::ABSOLUTE_URL ); }
[ "public", "function", "getUrl", "(", "ExtReference", "$", "extReference", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "mapping", "[", "$", "extReference", "->", "getRef", "(", ")", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgume...
return the URL from extref @param ExtReference $extReference Extref @return string @throws \InvalidArgumentException
[ "return", "the", "URL", "from", "extref" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Service/ExtReferenceConverter.php#L87-L103
train
libgraviton/graviton
src/Graviton/DocumentBundle/Service/ExtReferenceConverter.php
ExtReferenceConverter.getDataFromRoute
private function getDataFromRoute(Route $route, $value) { if ($route->getRequirement('id') !== null && $route->getMethods() === ['GET'] && preg_match($route->compile()->getRegex(), $value, $matches) ) { $id = $matches['id']; list($routeService) = explode(':', $route->getDefault('_controller')); list($core, $bundle,,$name) = explode('.', $routeService); $serviceName = implode('.', [$core, $bundle, 'rest', $name]); $collection = array_search($serviceName, $this->mapping); return [$collection, $id]; } return [null, null]; }
php
private function getDataFromRoute(Route $route, $value) { if ($route->getRequirement('id') !== null && $route->getMethods() === ['GET'] && preg_match($route->compile()->getRegex(), $value, $matches) ) { $id = $matches['id']; list($routeService) = explode(':', $route->getDefault('_controller')); list($core, $bundle,,$name) = explode('.', $routeService); $serviceName = implode('.', [$core, $bundle, 'rest', $name]); $collection = array_search($serviceName, $this->mapping); return [$collection, $id]; } return [null, null]; }
[ "private", "function", "getDataFromRoute", "(", "Route", "$", "route", ",", "$", "value", ")", "{", "if", "(", "$", "route", "->", "getRequirement", "(", "'id'", ")", "!==", "null", "&&", "$", "route", "->", "getMethods", "(", ")", "===", "[", "'GET'",...
get collection and id from route @param Route $route route to look at @param string $value value of reference as URI @return array
[ "get", "collection", "and", "id", "from", "route" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Service/ExtReferenceConverter.php#L113-L130
train
libgraviton/graviton
src/Graviton/RabbitMqBundle/DependencyInjection/GravitonRabbitMqExtension.php
GravitonRabbitMqExtension.prepend
public function prepend(ContainerBuilder $container) { parent::prepend($container); // populated from cf's VCAP_SERVICES variable $services = getenv('VCAP_SERVICES'); if (!empty($services)) { $services = json_decode($services, true); if (!isset($services['rabbitmq'][0]['credentials'])) { return false; } $creds = $services['rabbitmq'][0]['credentials']; $container->setParameter('rabbitmq.host', $creds['host']); $container->setParameter('rabbitmq.port', $creds['port']); $container->setParameter('rabbitmq.user', $creds['username']); $container->setParameter('rabbitmq.password', $creds['password']); $container->setParameter('rabbitmq.vhost', $creds['vhost']); } else { $container->setParameter('rabbitmq.host', $container->getParameter('graviton.rabbitmq.host')); $container->setParameter('rabbitmq.port', $container->getParameter('graviton.rabbitmq.port')); $container->setParameter('rabbitmq.user', $container->getParameter('graviton.rabbitmq.user')); $container->setParameter('rabbitmq.password', $container->getParameter('graviton.rabbitmq.password')); $container->setParameter('rabbitmq.vhost', $container->getParameter('graviton.rabbitmq.vhost')); } }
php
public function prepend(ContainerBuilder $container) { parent::prepend($container); // populated from cf's VCAP_SERVICES variable $services = getenv('VCAP_SERVICES'); if (!empty($services)) { $services = json_decode($services, true); if (!isset($services['rabbitmq'][0]['credentials'])) { return false; } $creds = $services['rabbitmq'][0]['credentials']; $container->setParameter('rabbitmq.host', $creds['host']); $container->setParameter('rabbitmq.port', $creds['port']); $container->setParameter('rabbitmq.user', $creds['username']); $container->setParameter('rabbitmq.password', $creds['password']); $container->setParameter('rabbitmq.vhost', $creds['vhost']); } else { $container->setParameter('rabbitmq.host', $container->getParameter('graviton.rabbitmq.host')); $container->setParameter('rabbitmq.port', $container->getParameter('graviton.rabbitmq.port')); $container->setParameter('rabbitmq.user', $container->getParameter('graviton.rabbitmq.user')); $container->setParameter('rabbitmq.password', $container->getParameter('graviton.rabbitmq.password')); $container->setParameter('rabbitmq.vhost', $container->getParameter('graviton.rabbitmq.vhost')); } }
[ "public", "function", "prepend", "(", "ContainerBuilder", "$", "container", ")", "{", "parent", "::", "prepend", "(", "$", "container", ")", ";", "// populated from cf's VCAP_SERVICES variable", "$", "services", "=", "getenv", "(", "'VCAP_SERVICES'", ")", ";", "if...
Overwrite rabbitmq config from cloud if available @param ContainerBuilder $container instance @return void
[ "Overwrite", "rabbitmq", "config", "from", "cloud", "if", "available" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RabbitMqBundle/DependencyInjection/GravitonRabbitMqExtension.php#L35-L61
train
SimpleBus/DoctrineORMBridge
src/EventListener/CollectsEventsFromEntities.php
CollectsEventsFromEntities.postFlush
public function postFlush(PostFlushEventArgs $eventArgs) { $em = $eventArgs->getEntityManager(); $uow = $em->getUnitOfWork(); foreach ($uow->getIdentityMap() as $entities) { foreach ($entities as $entity){ $this->collectEventsFromEntity($entity); } } }
php
public function postFlush(PostFlushEventArgs $eventArgs) { $em = $eventArgs->getEntityManager(); $uow = $em->getUnitOfWork(); foreach ($uow->getIdentityMap() as $entities) { foreach ($entities as $entity){ $this->collectEventsFromEntity($entity); } } }
[ "public", "function", "postFlush", "(", "PostFlushEventArgs", "$", "eventArgs", ")", "{", "$", "em", "=", "$", "eventArgs", "->", "getEntityManager", "(", ")", ";", "$", "uow", "=", "$", "em", "->", "getUnitOfWork", "(", ")", ";", "foreach", "(", "$", ...
We need to listen on postFlush for Lifecycle Events All Lifecycle callback events are triggered after the onFlush event @param PostFlushEventArgs $eventArgs
[ "We", "need", "to", "listen", "on", "postFlush", "for", "Lifecycle", "Events", "All", "Lifecycle", "callback", "events", "are", "triggered", "after", "the", "onFlush", "event" ]
f372224d3434f166b36c3826cb2d54aaf4c2f717
https://github.com/SimpleBus/DoctrineORMBridge/blob/f372224d3434f166b36c3826cb2d54aaf4c2f717/src/EventListener/CollectsEventsFromEntities.php#L44-L53
train
libgraviton/graviton
src/Graviton/ProxyBundle/Service/ApiDefinitionLoader.php
ApiDefinitionLoader.getDefinitionLoader
public function getDefinitionLoader() { if (empty($this->definitionLoader) && array_key_exists('prefix', $this->options)) { $this->definitionLoader = $this->loaderFactory->create($this->options['prefix']); } return $this->definitionLoader; }
php
public function getDefinitionLoader() { if (empty($this->definitionLoader) && array_key_exists('prefix', $this->options)) { $this->definitionLoader = $this->loaderFactory->create($this->options['prefix']); } return $this->definitionLoader; }
[ "public", "function", "getDefinitionLoader", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "definitionLoader", ")", "&&", "array_key_exists", "(", "'prefix'", ",", "$", "this", "->", "options", ")", ")", "{", "$", "this", "->", "definitionLoad...
Provides the definition loader instance. @return LoaderInterface
[ "Provides", "the", "definition", "loader", "instance", "." ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Service/ApiDefinitionLoader.php#L74-L81
train
libgraviton/graviton
src/Graviton/ProxyBundle/Service/ApiDefinitionLoader.php
ApiDefinitionLoader.getEndpointSchema
public function getEndpointSchema($endpoint, $forceReload = false) { $this->loadApiDefinition($forceReload); return $this->definition->getSchema($endpoint); }
php
public function getEndpointSchema($endpoint, $forceReload = false) { $this->loadApiDefinition($forceReload); return $this->definition->getSchema($endpoint); }
[ "public", "function", "getEndpointSchema", "(", "$", "endpoint", ",", "$", "forceReload", "=", "false", ")", "{", "$", "this", "->", "loadApiDefinition", "(", "$", "forceReload", ")", ";", "return", "$", "this", "->", "definition", "->", "getSchema", "(", ...
get a schema for one endpoint @param string $endpoint endpoint @param bool $forceReload Switch to force a new api definition object will be provided. @return \stdClass
[ "get", "a", "schema", "for", "one", "endpoint" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Service/ApiDefinitionLoader.php#L140-L145
train
libgraviton/graviton
src/Graviton/ProxyBundle/Service/ApiDefinitionLoader.php
ApiDefinitionLoader.getEndpoint
public function getEndpoint($endpoint, $withHost = false, $forceReload = false) { $this->loadApiDefinition($forceReload); $url = ""; if ($withHost) { $url = empty($this->options['host']) ? $this->definition->getHost() : $this->options['host']; } // If the base path is not already included, we need to add it. $url .= (empty($this->options['includeBasePath']) ? $this->definition->getBasePath() : '') . $endpoint; return $url; }
php
public function getEndpoint($endpoint, $withHost = false, $forceReload = false) { $this->loadApiDefinition($forceReload); $url = ""; if ($withHost) { $url = empty($this->options['host']) ? $this->definition->getHost() : $this->options['host']; } // If the base path is not already included, we need to add it. $url .= (empty($this->options['includeBasePath']) ? $this->definition->getBasePath() : '') . $endpoint; return $url; }
[ "public", "function", "getEndpoint", "(", "$", "endpoint", ",", "$", "withHost", "=", "false", ",", "$", "forceReload", "=", "false", ")", "{", "$", "this", "->", "loadApiDefinition", "(", "$", "forceReload", ")", ";", "$", "url", "=", "\"\"", ";", "if...
get an endpoint @param string $endpoint endpoint @param boolean $withHost attach host name to the url @param bool $forceReload Switch to force a new api definition object will be provided. @return string
[ "get", "an", "endpoint" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Service/ApiDefinitionLoader.php#L156-L168
train
libgraviton/graviton
src/Graviton/ProxyBundle/Service/ApiDefinitionLoader.php
ApiDefinitionLoader.getAllEndpoints
public function getAllEndpoints($withHost = false, $forceReload = false) { $this->loadApiDefinition($forceReload); $host = empty($this->options['host']) ? '' : $this->options['host']; $prefix = self::PROXY_ROUTE; if (isset($this->options['prefix'])) { $prefix .= "/".$this->options['prefix']; } return !is_object($this->definition) ? [] : $this->definition->getEndpoints( $withHost, $prefix, $host, !empty($this->options['includeBasePath']) ); }
php
public function getAllEndpoints($withHost = false, $forceReload = false) { $this->loadApiDefinition($forceReload); $host = empty($this->options['host']) ? '' : $this->options['host']; $prefix = self::PROXY_ROUTE; if (isset($this->options['prefix'])) { $prefix .= "/".$this->options['prefix']; } return !is_object($this->definition) ? [] : $this->definition->getEndpoints( $withHost, $prefix, $host, !empty($this->options['includeBasePath']) ); }
[ "public", "function", "getAllEndpoints", "(", "$", "withHost", "=", "false", ",", "$", "forceReload", "=", "false", ")", "{", "$", "this", "->", "loadApiDefinition", "(", "$", "forceReload", ")", ";", "$", "host", "=", "empty", "(", "$", "this", "->", ...
get all endpoints for an API @param boolean $withHost attach host name to the url @param bool $forceReload Switch to force a new api definition object will be provided. @return array
[ "get", "all", "endpoints", "for", "an", "API" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Service/ApiDefinitionLoader.php#L178-L194
train
libgraviton/graviton
src/Graviton/ProxyBundle/Service/ApiDefinitionLoader.php
ApiDefinitionLoader.loadApiDefinition
private function loadApiDefinition($forceReload = false) { $definitionLoader = $this->getDefinitionLoader(); $supported = $definitionLoader->supports($this->options['uri']); if ($forceReload || ($this->definition == null && $supported)) { $this->definition = $definitionLoader->load($this->options['uri']); } elseif (!$supported) { throw new \RuntimeException("This resource (".$this->options['uri'].") is not supported."); } }
php
private function loadApiDefinition($forceReload = false) { $definitionLoader = $this->getDefinitionLoader(); $supported = $definitionLoader->supports($this->options['uri']); if ($forceReload || ($this->definition == null && $supported)) { $this->definition = $definitionLoader->load($this->options['uri']); } elseif (!$supported) { throw new \RuntimeException("This resource (".$this->options['uri'].") is not supported."); } }
[ "private", "function", "loadApiDefinition", "(", "$", "forceReload", "=", "false", ")", "{", "$", "definitionLoader", "=", "$", "this", "->", "getDefinitionLoader", "(", ")", ";", "$", "supported", "=", "$", "definitionLoader", "->", "supports", "(", "$", "t...
internal load method @param bool $forceReload Switch to force a new api definition object will be provided. @return void
[ "internal", "load", "method" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Service/ApiDefinitionLoader.php#L203-L214
train
libgraviton/graviton
src/Graviton/RestBundle/Listener/WriteLockListener.php
WriteLockListener.onKernelController
public function onKernelController(FilterControllerEvent $event) { $currentMethod = $this->requestStack->getCurrentRequest()->getMethod(); // ignore not defined methods.. if (!in_array($currentMethod, $this->interestedMethods)) { return; } $url = $this->requestStack->getCurrentRequest()->getPathInfo(); $cacheKey = $this->cacheKeyPrefix.$url; // should we do a random delay here? only applies to writing methods! if (in_array($currentMethod, $this->lockingMethods) && $this->doRandomDelay($url) ) { $delay = rand($this->randomDelayMin, $this->randomDelayMax) * 1000; $this->logger->info("LOCK CHECK DELAY BY ".$delay." = ".$cacheKey); usleep(rand($this->randomDelayMin, $this->randomDelayMax) * 1000); } $this->logger->info("LOCK CHECK START = ".$cacheKey); // check for existing one while ($this->cache->fetch($cacheKey) === true) { usleep(250000); } $this->logger->info("LOCK CHECK FINISHED = ".$cacheKey); if (in_array($currentMethod, $this->waitingMethods)) { // current method just wants to wait.. return; } // create new $this->cache->save($cacheKey, true, $this->maxTime); $this->logger->info("LOCK ADD = ".$cacheKey); $event->getRequest()->attributes->set('writeLockOn', $cacheKey); }
php
public function onKernelController(FilterControllerEvent $event) { $currentMethod = $this->requestStack->getCurrentRequest()->getMethod(); // ignore not defined methods.. if (!in_array($currentMethod, $this->interestedMethods)) { return; } $url = $this->requestStack->getCurrentRequest()->getPathInfo(); $cacheKey = $this->cacheKeyPrefix.$url; // should we do a random delay here? only applies to writing methods! if (in_array($currentMethod, $this->lockingMethods) && $this->doRandomDelay($url) ) { $delay = rand($this->randomDelayMin, $this->randomDelayMax) * 1000; $this->logger->info("LOCK CHECK DELAY BY ".$delay." = ".$cacheKey); usleep(rand($this->randomDelayMin, $this->randomDelayMax) * 1000); } $this->logger->info("LOCK CHECK START = ".$cacheKey); // check for existing one while ($this->cache->fetch($cacheKey) === true) { usleep(250000); } $this->logger->info("LOCK CHECK FINISHED = ".$cacheKey); if (in_array($currentMethod, $this->waitingMethods)) { // current method just wants to wait.. return; } // create new $this->cache->save($cacheKey, true, $this->maxTime); $this->logger->info("LOCK ADD = ".$cacheKey); $event->getRequest()->attributes->set('writeLockOn', $cacheKey); }
[ "public", "function", "onKernelController", "(", "FilterControllerEvent", "$", "event", ")", "{", "$", "currentMethod", "=", "$", "this", "->", "requestStack", "->", "getCurrentRequest", "(", ")", "->", "getMethod", "(", ")", ";", "// ignore not defined methods..", ...
all "waiting" methods wait until no lock is around.. "writelock" methods wait and create a lock @param FilterControllerEvent $event response listener event @return void
[ "all", "waiting", "methods", "wait", "until", "no", "lock", "is", "around", "..", "writelock", "methods", "wait", "and", "create", "a", "lock" ]
5eccfb2fba31dadf659f0f55edeb1ebca403563e
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Listener/WriteLockListener.php#L118-L159
train