id
int32 0
241k
| 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
26,400
|
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",
"(",
")",
";",
"return",
"$",
"this",
";",
"}"
] |
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
|
26,401
|
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",
"->",
"repository",
"->",
"find",
"(",
"$",
"documentId",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"result",
")",
")",
"{",
"throw",
"new",
"NotFoundException",
"(",
"\"Entry with id \"",
".",
"$",
"documentId",
".",
"\" not found!\"",
")",
";",
"}",
"return",
"$",
"result",
";",
"}"
] |
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
|
26,402
|
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",
"(",
"''",
")",
";",
"}",
"$",
"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",
")",
";",
"}"
] |
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
|
26,403
|
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",
"(",
"$",
"id",
")",
"->",
"getQuery",
"(",
")",
"->",
"execute",
"(",
")",
";",
"}"
] |
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
|
26,404
|
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",
"->",
"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",
")",
";",
"}",
"}",
"}"
] |
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
|
26,405
|
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",
"(",
"$",
"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",
")",
";",
"}"
] |
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
|
26,406
|
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",
"->",
"getToken",
"(",
")",
")",
"&&",
"(",
"$",
"user",
"=",
"$",
"token",
"->",
"getUser",
"(",
")",
")",
"instanceof",
"UserInterface",
")",
"{",
"$",
"this",
"->",
"securityUser",
"=",
"$",
"user",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
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
|
26,407
|
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",
"new",
"UsernameNotFoundException",
"(",
"'No security user'",
")",
";",
"}"
] |
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
|
26,408
|
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",
"=",
"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",
";",
"}"
] |
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
|
26,409
|
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",
")",
"&&",
"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",
";",
"}"
] |
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
|
26,410
|
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",
")",
")",
"{",
"$",
"translatable",
"=",
"Translatable",
"::",
"createFromTranslations",
"(",
"$",
"data",
")",
";",
"$",
"this",
"->",
"utils",
"->",
"persistTranslatable",
"(",
"$",
"translatable",
")",
";",
"return",
"$",
"translatable",
";",
"}",
"return",
"null",
";",
"}"
] |
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
|
26,411
|
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",
"\\",
"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",
"(",
")",
")",
";",
"}",
"}",
"}"
] |
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
|
26,412
|
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",
"(",
"$",
"this",
"->",
"startString",
")",
";",
"$",
"res",
"[",
"'endStringPos'",
"]",
"=",
"strpos",
"(",
"$",
"content",
",",
"$",
"this",
"->",
"endString",
")",
";",
"$",
"res",
"[",
"'bundleList'",
"]",
"=",
"substr",
"(",
"$",
"content",
",",
"$",
"res",
"[",
"'startStringPos'",
"]",
",",
"(",
"$",
"res",
"[",
"'endStringPos'",
"]",
"-",
"$",
"res",
"[",
"'startStringPos'",
"]",
")",
")",
";",
"return",
"$",
"res",
";",
"}"
] |
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
|
26,413
|
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",
",",
"0",
",",
"$",
"contentData",
"[",
"'startStringPos'",
"]",
")",
";",
"$",
"endPart",
"=",
"substr",
"(",
"$",
"content",
",",
"$",
"contentData",
"[",
"'endStringPos'",
"]",
")",
";",
"return",
"$",
"beforePart",
".",
"PHP_EOL",
".",
"implode",
"(",
"','",
".",
"PHP_EOL",
",",
"$",
"newBundleList",
")",
".",
"PHP_EOL",
".",
"$",
"endPart",
";",
"}"
] |
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
|
26,414
|
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",
",",
"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",
";",
"}"
] |
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
|
26,415
|
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",
"->",
"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",
")",
")",
";",
"}",
"}"
] |
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
|
26,416
|
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",
"null",
";",
"}"
] |
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
|
26,417
|
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
|
26,418
|
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",
"->",
"isEmptyExtRefObject",
"(",
")",
"===",
"true",
")",
"{",
"$",
"event",
"->",
"setType",
"(",
"'Empty'",
",",
"[",
"$",
"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
|
26,419
|
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",
"->",
"extractFieldInfo",
"(",
"$",
"request",
"->",
"headers",
",",
"$",
"this",
"->",
"headerField",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"name",
")",
")",
"{",
"return",
"$",
"name",
";",
"}",
"}",
"return",
"''",
";",
"}"
] |
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
|
26,420
|
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
|
26,421
|
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",
",",
"$",
"value",
")",
";",
"}"
] |
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
|
26,422
|
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 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",
";",
"}"
] |
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
|
26,423
|
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",
"(",
"[",
"'_id'",
"=>",
"$",
"id",
"]",
")",
";",
"}"
] |
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
|
26,424
|
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",
"->",
"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",
"(",
")",
")",
",",
"]",
")",
";",
"}"
] |
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
|
26,425
|
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",
"(",
"$",
"field",
"instanceof",
"JsonDefinitionField",
"&&",
"$",
"field",
"->",
"getDef",
"(",
")",
"instanceof",
"Field",
"&&",
"$",
"field",
"->",
"getDef",
"(",
")",
"->",
"getRequired",
"(",
")",
"===",
"true",
")",
"{",
"$",
"isRequired",
"=",
"true",
";",
"}",
"}",
"return",
"$",
"isRequired",
";",
"}"
] |
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
|
26,426
|
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",
"->",
"name",
",",
"'/'",
")",
".",
"'\\.(\\d+\\.)*/'",
",",
"''",
",",
"$",
"clone",
"->",
"getName",
"(",
")",
")",
")",
";",
"return",
"$",
"clone",
";",
"}"
] |
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
|
26,427
|
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",
"(",
"!",
"preg_match",
"(",
"$",
"prefixRegex",
",",
"$",
"relation",
"->",
"getLocalProperty",
"(",
")",
",",
"$",
"matches",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"clone",
"=",
"clone",
"$",
"relation",
";",
"$",
"clone",
"->",
"setLocalProperty",
"(",
"$",
"matches",
"[",
"'sub'",
"]",
")",
";",
"return",
"$",
"clone",
";",
"}"
] |
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
|
26,428
|
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",
"(",
")",
")",
";",
"if",
"(",
"$",
"fq",
")",
"{",
"$",
"className",
"=",
"$",
"this",
"->",
"parent",
"->",
"getNamespace",
"(",
")",
".",
"'\\\\Document\\\\'",
".",
"$",
"className",
";",
"}",
"return",
"$",
"className",
";",
"}"
] |
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
|
26,429
|
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",
"(",
"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",
")",
")",
";",
"}"
] |
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
|
26,430
|
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",
"\\",
"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",
")",
";",
"}"
] |
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
|
26,431
|
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'",
"]",
"&&",
"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",
"]",
";",
"}"
] |
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
|
26,432
|
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",
"(",
"!",
"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'",
")",
")",
";",
"}",
"}"
] |
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
|
26,433
|
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",
"(",
"$",
"uow",
"->",
"getIdentityMap",
"(",
")",
"as",
"$",
"entities",
")",
"{",
"foreach",
"(",
"$",
"entities",
"as",
"$",
"entity",
")",
"{",
"$",
"this",
"->",
"collectEventsFromEntity",
"(",
"$",
"entity",
")",
";",
"}",
"}",
"}"
] |
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
|
26,434
|
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",
"->",
"definitionLoader",
"=",
"$",
"this",
"->",
"loaderFactory",
"->",
"create",
"(",
"$",
"this",
"->",
"options",
"[",
"'prefix'",
"]",
")",
";",
"}",
"return",
"$",
"this",
"->",
"definitionLoader",
";",
"}"
] |
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
|
26,435
|
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",
"(",
"$",
"endpoint",
")",
";",
"}"
] |
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
|
26,436
|
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",
"(",
"$",
"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",
";",
"}"
] |
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
|
26,437
|
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",
"->",
"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'",
"]",
")",
")",
";",
"}"
] |
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
|
26,438
|
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",
"(",
"$",
"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.\"",
")",
";",
"}",
"}"
] |
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
|
26,439
|
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..",
"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",
")",
";",
"}"
] |
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
|
26,440
|
libgraviton/graviton
|
src/Graviton/RestBundle/Listener/WriteLockListener.php
|
WriteLockListener.doRandomDelay
|
private function doRandomDelay($url)
{
return array_reduce(
$this->randomWaitUrls,
function ($carry, $value) use ($url) {
if ($carry !== true) {
return (strpos($url, $value) === 0);
} else {
return $carry;
}
}
);
}
|
php
|
private function doRandomDelay($url)
{
return array_reduce(
$this->randomWaitUrls,
function ($carry, $value) use ($url) {
if ($carry !== true) {
return (strpos($url, $value) === 0);
} else {
return $carry;
}
}
);
}
|
[
"private",
"function",
"doRandomDelay",
"(",
"$",
"url",
")",
"{",
"return",
"array_reduce",
"(",
"$",
"this",
"->",
"randomWaitUrls",
",",
"function",
"(",
"$",
"carry",
",",
"$",
"value",
")",
"use",
"(",
"$",
"url",
")",
"{",
"if",
"(",
"$",
"carry",
"!==",
"true",
")",
"{",
"return",
"(",
"strpos",
"(",
"$",
"url",
",",
"$",
"value",
")",
"===",
"0",
")",
";",
"}",
"else",
"{",
"return",
"$",
"carry",
";",
"}",
"}",
")",
";",
"}"
] |
if we should randomly wait on current request
@param string $url the current url
@return boolean true if yes, false otherwise
|
[
"if",
"we",
"should",
"randomly",
"wait",
"on",
"current",
"request"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Listener/WriteLockListener.php#L184-L196
|
26,441
|
libgraviton/graviton
|
src/Graviton/ProxyBundle/Controller/ProxyController.php
|
ProxyController.proxyAction
|
public function proxyAction(Request $request)
{
$api = $this->decideApiAndEndpoint($request->getUri());
$this->registerProxySources($api['apiName']);
$this->apiLoader->addOptions($api);
$url = new Uri($this->apiLoader->getEndpoint($api['endpoint'], true));
if ($url->getScheme() === null) {
$url = $url->withScheme($request->getScheme());
}
$response = null;
try {
$newRequest = Request::create(
(string) $url,
$request->getMethod(),
[],
[],
[],
[],
$request->getContent(false)
);
$newRequest->headers->add($request->headers->all());
$newRequest->query->add($request->query->all());
$newRequest = $this->transformationHandler->transformRequest(
$api['apiName'],
$api['endpoint'],
$request,
$newRequest
);
$psrRequest = $this->psrHttpFactory->createRequest($newRequest);
$psrRequestUri = $psrRequest->getUri();
$psrRequestUriPort = $url->getPort();
if (is_numeric($psrRequestUriPort) || is_null($psrRequestUriPort)) {
$psrRequestUri = $psrRequestUri->withPort($psrRequestUriPort);
}
$psrRequest = $psrRequest->withUri($psrRequestUri);
$psrResponse = $this->proxy->forward($psrRequest)->to($this->getHostWithScheme($url));
$response = $this->httpFoundationFactory->createResponse($psrResponse);
$this->cleanResponseHeaders($response->headers);
$this->transformationHandler->transformResponse(
$api['apiName'],
$api['endpoint'],
$response,
clone $response
);
} catch (ClientException $e) {
$response = (new HttpFoundationFactory())->createResponse($e->getResponse());
} catch (ServerException $serverException) {
$response = (new HttpFoundationFactory())->createResponse($serverException->getResponse());
} catch (TransformationException $e) {
$message = json_encode(
['code' => 404, 'message' => 'HTTP 404 Not found']
);
throw new NotFoundHttpException($message, $e);
} catch (RequestException $e) {
$message = json_encode(
['code' => 404, 'message' => 'HTTP 404 Not found']
);
throw new NotFoundHttpException($message, $e);
}
return $response;
}
|
php
|
public function proxyAction(Request $request)
{
$api = $this->decideApiAndEndpoint($request->getUri());
$this->registerProxySources($api['apiName']);
$this->apiLoader->addOptions($api);
$url = new Uri($this->apiLoader->getEndpoint($api['endpoint'], true));
if ($url->getScheme() === null) {
$url = $url->withScheme($request->getScheme());
}
$response = null;
try {
$newRequest = Request::create(
(string) $url,
$request->getMethod(),
[],
[],
[],
[],
$request->getContent(false)
);
$newRequest->headers->add($request->headers->all());
$newRequest->query->add($request->query->all());
$newRequest = $this->transformationHandler->transformRequest(
$api['apiName'],
$api['endpoint'],
$request,
$newRequest
);
$psrRequest = $this->psrHttpFactory->createRequest($newRequest);
$psrRequestUri = $psrRequest->getUri();
$psrRequestUriPort = $url->getPort();
if (is_numeric($psrRequestUriPort) || is_null($psrRequestUriPort)) {
$psrRequestUri = $psrRequestUri->withPort($psrRequestUriPort);
}
$psrRequest = $psrRequest->withUri($psrRequestUri);
$psrResponse = $this->proxy->forward($psrRequest)->to($this->getHostWithScheme($url));
$response = $this->httpFoundationFactory->createResponse($psrResponse);
$this->cleanResponseHeaders($response->headers);
$this->transformationHandler->transformResponse(
$api['apiName'],
$api['endpoint'],
$response,
clone $response
);
} catch (ClientException $e) {
$response = (new HttpFoundationFactory())->createResponse($e->getResponse());
} catch (ServerException $serverException) {
$response = (new HttpFoundationFactory())->createResponse($serverException->getResponse());
} catch (TransformationException $e) {
$message = json_encode(
['code' => 404, 'message' => 'HTTP 404 Not found']
);
throw new NotFoundHttpException($message, $e);
} catch (RequestException $e) {
$message = json_encode(
['code' => 404, 'message' => 'HTTP 404 Not found']
);
throw new NotFoundHttpException($message, $e);
}
return $response;
}
|
[
"public",
"function",
"proxyAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"api",
"=",
"$",
"this",
"->",
"decideApiAndEndpoint",
"(",
"$",
"request",
"->",
"getUri",
"(",
")",
")",
";",
"$",
"this",
"->",
"registerProxySources",
"(",
"$",
"api",
"[",
"'apiName'",
"]",
")",
";",
"$",
"this",
"->",
"apiLoader",
"->",
"addOptions",
"(",
"$",
"api",
")",
";",
"$",
"url",
"=",
"new",
"Uri",
"(",
"$",
"this",
"->",
"apiLoader",
"->",
"getEndpoint",
"(",
"$",
"api",
"[",
"'endpoint'",
"]",
",",
"true",
")",
")",
";",
"if",
"(",
"$",
"url",
"->",
"getScheme",
"(",
")",
"===",
"null",
")",
"{",
"$",
"url",
"=",
"$",
"url",
"->",
"withScheme",
"(",
"$",
"request",
"->",
"getScheme",
"(",
")",
")",
";",
"}",
"$",
"response",
"=",
"null",
";",
"try",
"{",
"$",
"newRequest",
"=",
"Request",
"::",
"create",
"(",
"(",
"string",
")",
"$",
"url",
",",
"$",
"request",
"->",
"getMethod",
"(",
")",
",",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"$",
"request",
"->",
"getContent",
"(",
"false",
")",
")",
";",
"$",
"newRequest",
"->",
"headers",
"->",
"add",
"(",
"$",
"request",
"->",
"headers",
"->",
"all",
"(",
")",
")",
";",
"$",
"newRequest",
"->",
"query",
"->",
"add",
"(",
"$",
"request",
"->",
"query",
"->",
"all",
"(",
")",
")",
";",
"$",
"newRequest",
"=",
"$",
"this",
"->",
"transformationHandler",
"->",
"transformRequest",
"(",
"$",
"api",
"[",
"'apiName'",
"]",
",",
"$",
"api",
"[",
"'endpoint'",
"]",
",",
"$",
"request",
",",
"$",
"newRequest",
")",
";",
"$",
"psrRequest",
"=",
"$",
"this",
"->",
"psrHttpFactory",
"->",
"createRequest",
"(",
"$",
"newRequest",
")",
";",
"$",
"psrRequestUri",
"=",
"$",
"psrRequest",
"->",
"getUri",
"(",
")",
";",
"$",
"psrRequestUriPort",
"=",
"$",
"url",
"->",
"getPort",
"(",
")",
";",
"if",
"(",
"is_numeric",
"(",
"$",
"psrRequestUriPort",
")",
"||",
"is_null",
"(",
"$",
"psrRequestUriPort",
")",
")",
"{",
"$",
"psrRequestUri",
"=",
"$",
"psrRequestUri",
"->",
"withPort",
"(",
"$",
"psrRequestUriPort",
")",
";",
"}",
"$",
"psrRequest",
"=",
"$",
"psrRequest",
"->",
"withUri",
"(",
"$",
"psrRequestUri",
")",
";",
"$",
"psrResponse",
"=",
"$",
"this",
"->",
"proxy",
"->",
"forward",
"(",
"$",
"psrRequest",
")",
"->",
"to",
"(",
"$",
"this",
"->",
"getHostWithScheme",
"(",
"$",
"url",
")",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"httpFoundationFactory",
"->",
"createResponse",
"(",
"$",
"psrResponse",
")",
";",
"$",
"this",
"->",
"cleanResponseHeaders",
"(",
"$",
"response",
"->",
"headers",
")",
";",
"$",
"this",
"->",
"transformationHandler",
"->",
"transformResponse",
"(",
"$",
"api",
"[",
"'apiName'",
"]",
",",
"$",
"api",
"[",
"'endpoint'",
"]",
",",
"$",
"response",
",",
"clone",
"$",
"response",
")",
";",
"}",
"catch",
"(",
"ClientException",
"$",
"e",
")",
"{",
"$",
"response",
"=",
"(",
"new",
"HttpFoundationFactory",
"(",
")",
")",
"->",
"createResponse",
"(",
"$",
"e",
"->",
"getResponse",
"(",
")",
")",
";",
"}",
"catch",
"(",
"ServerException",
"$",
"serverException",
")",
"{",
"$",
"response",
"=",
"(",
"new",
"HttpFoundationFactory",
"(",
")",
")",
"->",
"createResponse",
"(",
"$",
"serverException",
"->",
"getResponse",
"(",
")",
")",
";",
"}",
"catch",
"(",
"TransformationException",
"$",
"e",
")",
"{",
"$",
"message",
"=",
"json_encode",
"(",
"[",
"'code'",
"=>",
"404",
",",
"'message'",
"=>",
"'HTTP 404 Not found'",
"]",
")",
";",
"throw",
"new",
"NotFoundHttpException",
"(",
"$",
"message",
",",
"$",
"e",
")",
";",
"}",
"catch",
"(",
"RequestException",
"$",
"e",
")",
"{",
"$",
"message",
"=",
"json_encode",
"(",
"[",
"'code'",
"=>",
"404",
",",
"'message'",
"=>",
"'HTTP 404 Not found'",
"]",
")",
";",
"throw",
"new",
"NotFoundHttpException",
"(",
"$",
"message",
",",
"$",
"e",
")",
";",
"}",
"return",
"$",
"response",
";",
"}"
] |
action for routing all requests directly to the third party API
@param Request $request request
@return \Psr\Http\Message\ResponseInterface|Response
|
[
"action",
"for",
"routing",
"all",
"requests",
"directly",
"to",
"the",
"third",
"party",
"API"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Controller/ProxyController.php#L107-L178
|
26,442
|
libgraviton/graviton
|
src/Graviton/ProxyBundle/Controller/ProxyController.php
|
ProxyController.cleanResponseHeaders
|
protected function cleanResponseHeaders(HeaderBag $headers)
{
$headers->remove('transfer-encoding'); // Chunked responses get not automatically re-chunked by graviton
$headers->remove('trailer'); // Only for chunked responses, graviton should re-set this when chunking
// Change naming to Graviton output Allow options
if ($allow = $headers->get('Allow', false)) {
$headers->set('Access-Control-Allow-Methods', $allow);
$headers->remove('Allow');
}
}
|
php
|
protected function cleanResponseHeaders(HeaderBag $headers)
{
$headers->remove('transfer-encoding'); // Chunked responses get not automatically re-chunked by graviton
$headers->remove('trailer'); // Only for chunked responses, graviton should re-set this when chunking
// Change naming to Graviton output Allow options
if ($allow = $headers->get('Allow', false)) {
$headers->set('Access-Control-Allow-Methods', $allow);
$headers->remove('Allow');
}
}
|
[
"protected",
"function",
"cleanResponseHeaders",
"(",
"HeaderBag",
"$",
"headers",
")",
"{",
"$",
"headers",
"->",
"remove",
"(",
"'transfer-encoding'",
")",
";",
"// Chunked responses get not automatically re-chunked by graviton",
"$",
"headers",
"->",
"remove",
"(",
"'trailer'",
")",
";",
"// Only for chunked responses, graviton should re-set this when chunking",
"// Change naming to Graviton output Allow options",
"if",
"(",
"$",
"allow",
"=",
"$",
"headers",
"->",
"get",
"(",
"'Allow'",
",",
"false",
")",
")",
"{",
"$",
"headers",
"->",
"set",
"(",
"'Access-Control-Allow-Methods'",
",",
"$",
"allow",
")",
";",
"$",
"headers",
"->",
"remove",
"(",
"'Allow'",
")",
";",
"}",
"}"
] |
Removes some headers from the thirdparty API's response. These headers get always invalid by graviton's
forwarding and should therefore not be delivered to the client.
@param HeaderBag $headers The headerbag holding the thirdparty API's response headers
@return void
|
[
"Removes",
"some",
"headers",
"from",
"the",
"thirdparty",
"API",
"s",
"response",
".",
"These",
"headers",
"get",
"always",
"invalid",
"by",
"graviton",
"s",
"forwarding",
"and",
"should",
"therefore",
"not",
"be",
"delivered",
"to",
"the",
"client",
"."
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Controller/ProxyController.php#L188-L198
|
26,443
|
libgraviton/graviton
|
src/Graviton/ProxyBundle/Controller/ProxyController.php
|
ProxyController.schemaAction
|
public function schemaAction(Request $request)
{
$api = $this->decideApiAndEndpoint($request->getUri());
$this->registerProxySources($api['apiName']);
$this->apiLoader->addOptions($api);
$schema = $this->apiLoader->getEndpointSchema(urldecode($api['endpoint']));
$schema = $this->transformationHandler->transformSchema(
$api['apiName'],
$api['endpoint'],
$schema,
clone $schema
);
$response = new Response(json_encode($schema), 200);
$response->headers->set('Content-Type', 'application/json');
return $this->templating->renderResponse(
'GravitonCoreBundle:Main:index.json.twig',
array ('response' => $response->getContent()),
$response
);
}
|
php
|
public function schemaAction(Request $request)
{
$api = $this->decideApiAndEndpoint($request->getUri());
$this->registerProxySources($api['apiName']);
$this->apiLoader->addOptions($api);
$schema = $this->apiLoader->getEndpointSchema(urldecode($api['endpoint']));
$schema = $this->transformationHandler->transformSchema(
$api['apiName'],
$api['endpoint'],
$schema,
clone $schema
);
$response = new Response(json_encode($schema), 200);
$response->headers->set('Content-Type', 'application/json');
return $this->templating->renderResponse(
'GravitonCoreBundle:Main:index.json.twig',
array ('response' => $response->getContent()),
$response
);
}
|
[
"public",
"function",
"schemaAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"api",
"=",
"$",
"this",
"->",
"decideApiAndEndpoint",
"(",
"$",
"request",
"->",
"getUri",
"(",
")",
")",
";",
"$",
"this",
"->",
"registerProxySources",
"(",
"$",
"api",
"[",
"'apiName'",
"]",
")",
";",
"$",
"this",
"->",
"apiLoader",
"->",
"addOptions",
"(",
"$",
"api",
")",
";",
"$",
"schema",
"=",
"$",
"this",
"->",
"apiLoader",
"->",
"getEndpointSchema",
"(",
"urldecode",
"(",
"$",
"api",
"[",
"'endpoint'",
"]",
")",
")",
";",
"$",
"schema",
"=",
"$",
"this",
"->",
"transformationHandler",
"->",
"transformSchema",
"(",
"$",
"api",
"[",
"'apiName'",
"]",
",",
"$",
"api",
"[",
"'endpoint'",
"]",
",",
"$",
"schema",
",",
"clone",
"$",
"schema",
")",
";",
"$",
"response",
"=",
"new",
"Response",
"(",
"json_encode",
"(",
"$",
"schema",
")",
",",
"200",
")",
";",
"$",
"response",
"->",
"headers",
"->",
"set",
"(",
"'Content-Type'",
",",
"'application/json'",
")",
";",
"return",
"$",
"this",
"->",
"templating",
"->",
"renderResponse",
"(",
"'GravitonCoreBundle:Main:index.json.twig'",
",",
"array",
"(",
"'response'",
"=>",
"$",
"response",
"->",
"getContent",
"(",
")",
")",
",",
"$",
"response",
")",
";",
"}"
] |
get schema info
@param Request $request request
@return Response
|
[
"get",
"schema",
"info"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Controller/ProxyController.php#L207-L228
|
26,444
|
libgraviton/graviton
|
src/Graviton/ProxyBundle/Controller/ProxyController.php
|
ProxyController.registerProxySources
|
private function registerProxySources($apiPrefix = '')
{
foreach (array_keys($this->proxySourceConfiguration) as $source) {
foreach ($this->proxySourceConfiguration[$source] as $config) {
if ($apiPrefix == $config['prefix']) {
$this->apiLoader->setOption($config);
return;
}
}
}
$e = new NotFoundException('No such thirdparty API.');
$e->setResponse(Response::create());
throw $e;
}
|
php
|
private function registerProxySources($apiPrefix = '')
{
foreach (array_keys($this->proxySourceConfiguration) as $source) {
foreach ($this->proxySourceConfiguration[$source] as $config) {
if ($apiPrefix == $config['prefix']) {
$this->apiLoader->setOption($config);
return;
}
}
}
$e = new NotFoundException('No such thirdparty API.');
$e->setResponse(Response::create());
throw $e;
}
|
[
"private",
"function",
"registerProxySources",
"(",
"$",
"apiPrefix",
"=",
"''",
")",
"{",
"foreach",
"(",
"array_keys",
"(",
"$",
"this",
"->",
"proxySourceConfiguration",
")",
"as",
"$",
"source",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"proxySourceConfiguration",
"[",
"$",
"source",
"]",
"as",
"$",
"config",
")",
"{",
"if",
"(",
"$",
"apiPrefix",
"==",
"$",
"config",
"[",
"'prefix'",
"]",
")",
"{",
"$",
"this",
"->",
"apiLoader",
"->",
"setOption",
"(",
"$",
"config",
")",
";",
"return",
";",
"}",
"}",
"}",
"$",
"e",
"=",
"new",
"NotFoundException",
"(",
"'No such thirdparty API.'",
")",
";",
"$",
"e",
"->",
"setResponse",
"(",
"Response",
"::",
"create",
"(",
")",
")",
";",
"throw",
"$",
"e",
";",
"}"
] |
Registers configured external services to be proxied.
@param string $apiPrefix The prefix of the API
@return void
|
[
"Registers",
"configured",
"external",
"services",
"to",
"be",
"proxied",
"."
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Controller/ProxyController.php#L265-L279
|
26,445
|
libgraviton/graviton
|
src/Graviton/ProxyBundle/Controller/ProxyController.php
|
ProxyController.getHostWithScheme
|
private function getHostWithScheme(UriInterface $url)
{
$target = new Uri();
$target = $target
->withScheme($url->getScheme())
->withHost($url->getHost())
->withPort($url->getPort());
return (string) $target;
}
|
php
|
private function getHostWithScheme(UriInterface $url)
{
$target = new Uri();
$target = $target
->withScheme($url->getScheme())
->withHost($url->getHost())
->withPort($url->getPort());
return (string) $target;
}
|
[
"private",
"function",
"getHostWithScheme",
"(",
"UriInterface",
"$",
"url",
")",
"{",
"$",
"target",
"=",
"new",
"Uri",
"(",
")",
";",
"$",
"target",
"=",
"$",
"target",
"->",
"withScheme",
"(",
"$",
"url",
"->",
"getScheme",
"(",
")",
")",
"->",
"withHost",
"(",
"$",
"url",
"->",
"getHost",
"(",
")",
")",
"->",
"withPort",
"(",
"$",
"url",
"->",
"getPort",
"(",
")",
")",
";",
"return",
"(",
"string",
")",
"$",
"target",
";",
"}"
] |
get host, scheme and port
@param string $url the url
@return string
|
[
"get",
"host",
"scheme",
"and",
"port"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Controller/ProxyController.php#L288-L297
|
26,446
|
libgraviton/graviton
|
src/Graviton/GeneratorBundle/Definition/Loader/Loader.php
|
Loader.load
|
public function load($input)
{
foreach ($this->strategies as $strategy) {
if ($strategy->supports($input)) {
return array_map([$this, 'createJsonDefinition'], $strategy->load($input));
}
}
return [];
}
|
php
|
public function load($input)
{
foreach ($this->strategies as $strategy) {
if ($strategy->supports($input)) {
return array_map([$this, 'createJsonDefinition'], $strategy->load($input));
}
}
return [];
}
|
[
"public",
"function",
"load",
"(",
"$",
"input",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"strategies",
"as",
"$",
"strategy",
")",
"{",
"if",
"(",
"$",
"strategy",
"->",
"supports",
"(",
"$",
"input",
")",
")",
"{",
"return",
"array_map",
"(",
"[",
"$",
"this",
",",
"'createJsonDefinition'",
"]",
",",
"$",
"strategy",
"->",
"load",
"(",
"$",
"input",
")",
")",
";",
"}",
"}",
"return",
"[",
"]",
";",
"}"
] |
load from input
@param string|null $input input from command
@return JsonDefinition[]
|
[
"load",
"from",
"input"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/Loader/Loader.php#L72-L81
|
26,447
|
libgraviton/graviton
|
src/Graviton/GeneratorBundle/Definition/Loader/Loader.php
|
Loader.createJsonDefinition
|
protected function createJsonDefinition($json)
{
$errors = $this->validator->validateJsonDefinition($json);
if (!empty($errors)) {
throw new ValidationException($errors);
}
$definition = $this->serializer->deserialize(
$json,
'Graviton\\GeneratorBundle\\Definition\\Schema\\Definition',
'json'
);
return new JsonDefinition($definition);
}
|
php
|
protected function createJsonDefinition($json)
{
$errors = $this->validator->validateJsonDefinition($json);
if (!empty($errors)) {
throw new ValidationException($errors);
}
$definition = $this->serializer->deserialize(
$json,
'Graviton\\GeneratorBundle\\Definition\\Schema\\Definition',
'json'
);
return new JsonDefinition($definition);
}
|
[
"protected",
"function",
"createJsonDefinition",
"(",
"$",
"json",
")",
"{",
"$",
"errors",
"=",
"$",
"this",
"->",
"validator",
"->",
"validateJsonDefinition",
"(",
"$",
"json",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"errors",
")",
")",
"{",
"throw",
"new",
"ValidationException",
"(",
"$",
"errors",
")",
";",
"}",
"$",
"definition",
"=",
"$",
"this",
"->",
"serializer",
"->",
"deserialize",
"(",
"$",
"json",
",",
"'Graviton\\\\GeneratorBundle\\\\Definition\\\\Schema\\\\Definition'",
",",
"'json'",
")",
";",
"return",
"new",
"JsonDefinition",
"(",
"$",
"definition",
")",
";",
"}"
] |
Deserialize JSON definition
@param string $json JSON code
@return JsonDefinition
@throws InvalidJsonException If JSON is invalid
@throws ValidationException If definition is not valid
|
[
"Deserialize",
"JSON",
"definition"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Definition/Loader/Loader.php#L91-L105
|
26,448
|
libgraviton/graviton
|
src/Graviton/I18nBundle/Translator/Translator.php
|
Translator.translate
|
public function translate($original)
{
$cached = $this->getFromCache($original);
if (is_array($cached)) {
return $cached;
}
$translations = $this->translationCollection->find(['original' => $original])->toArray();
$baseArray = [];
foreach ($translations as $item) {
$baseArray[$item['language']] = $item['localized'];
}
$translation = [];
foreach ($this->getLanguages() as $language) {
if (isset($baseArray[$language])) {
$translation[$language] = $baseArray[$language];
} else {
$translation[$language] = $original;
}
}
// ensure existence of default language
$translation[$this->defaultLanguage] = $original;
$this->saveToCache($original, $translation);
return $translation;
}
|
php
|
public function translate($original)
{
$cached = $this->getFromCache($original);
if (is_array($cached)) {
return $cached;
}
$translations = $this->translationCollection->find(['original' => $original])->toArray();
$baseArray = [];
foreach ($translations as $item) {
$baseArray[$item['language']] = $item['localized'];
}
$translation = [];
foreach ($this->getLanguages() as $language) {
if (isset($baseArray[$language])) {
$translation[$language] = $baseArray[$language];
} else {
$translation[$language] = $original;
}
}
// ensure existence of default language
$translation[$this->defaultLanguage] = $original;
$this->saveToCache($original, $translation);
return $translation;
}
|
[
"public",
"function",
"translate",
"(",
"$",
"original",
")",
"{",
"$",
"cached",
"=",
"$",
"this",
"->",
"getFromCache",
"(",
"$",
"original",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"cached",
")",
")",
"{",
"return",
"$",
"cached",
";",
"}",
"$",
"translations",
"=",
"$",
"this",
"->",
"translationCollection",
"->",
"find",
"(",
"[",
"'original'",
"=>",
"$",
"original",
"]",
")",
"->",
"toArray",
"(",
")",
";",
"$",
"baseArray",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"translations",
"as",
"$",
"item",
")",
"{",
"$",
"baseArray",
"[",
"$",
"item",
"[",
"'language'",
"]",
"]",
"=",
"$",
"item",
"[",
"'localized'",
"]",
";",
"}",
"$",
"translation",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getLanguages",
"(",
")",
"as",
"$",
"language",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"baseArray",
"[",
"$",
"language",
"]",
")",
")",
"{",
"$",
"translation",
"[",
"$",
"language",
"]",
"=",
"$",
"baseArray",
"[",
"$",
"language",
"]",
";",
"}",
"else",
"{",
"$",
"translation",
"[",
"$",
"language",
"]",
"=",
"$",
"original",
";",
"}",
"}",
"// ensure existence of default language",
"$",
"translation",
"[",
"$",
"this",
"->",
"defaultLanguage",
"]",
"=",
"$",
"original",
";",
"$",
"this",
"->",
"saveToCache",
"(",
"$",
"original",
",",
"$",
"translation",
")",
";",
"return",
"$",
"translation",
";",
"}"
] |
translate a string, returning an array with translations
@param string $original original string
@return array translation array
|
[
"translate",
"a",
"string",
"returning",
"an",
"array",
"with",
"translations"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Translator/Translator.php#L79-L108
|
26,449
|
libgraviton/graviton
|
src/Graviton/I18nBundle/Translator/Translator.php
|
Translator.persistTranslatable
|
public function persistTranslatable(Translatable $translatable)
{
$translations = $translatable->getTranslations();
if (!isset($translations[$this->defaultLanguage])) {
throw new \LogicException('Not possible to persist a Translatable without default language!');
}
$original = $translations[$this->defaultLanguage];
unset($translations[$this->defaultLanguage]);
foreach ($translations as $language => $translation) {
$this->translationCollection->upsert(
[
'original' => $original,
'language' => $language
],
[
'original' => $original,
'language' => $language,
'localized' => $translation
]
);
}
$this->removeFromCache($original);
}
|
php
|
public function persistTranslatable(Translatable $translatable)
{
$translations = $translatable->getTranslations();
if (!isset($translations[$this->defaultLanguage])) {
throw new \LogicException('Not possible to persist a Translatable without default language!');
}
$original = $translations[$this->defaultLanguage];
unset($translations[$this->defaultLanguage]);
foreach ($translations as $language => $translation) {
$this->translationCollection->upsert(
[
'original' => $original,
'language' => $language
],
[
'original' => $original,
'language' => $language,
'localized' => $translation
]
);
}
$this->removeFromCache($original);
}
|
[
"public",
"function",
"persistTranslatable",
"(",
"Translatable",
"$",
"translatable",
")",
"{",
"$",
"translations",
"=",
"$",
"translatable",
"->",
"getTranslations",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"translations",
"[",
"$",
"this",
"->",
"defaultLanguage",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'Not possible to persist a Translatable without default language!'",
")",
";",
"}",
"$",
"original",
"=",
"$",
"translations",
"[",
"$",
"this",
"->",
"defaultLanguage",
"]",
";",
"unset",
"(",
"$",
"translations",
"[",
"$",
"this",
"->",
"defaultLanguage",
"]",
")",
";",
"foreach",
"(",
"$",
"translations",
"as",
"$",
"language",
"=>",
"$",
"translation",
")",
"{",
"$",
"this",
"->",
"translationCollection",
"->",
"upsert",
"(",
"[",
"'original'",
"=>",
"$",
"original",
",",
"'language'",
"=>",
"$",
"language",
"]",
",",
"[",
"'original'",
"=>",
"$",
"original",
",",
"'language'",
"=>",
"$",
"language",
",",
"'localized'",
"=>",
"$",
"translation",
"]",
")",
";",
"}",
"$",
"this",
"->",
"removeFromCache",
"(",
"$",
"original",
")",
";",
"}"
] |
persists a translatable to database
@param Translatable $translatable the translatable
@return void
|
[
"persists",
"a",
"translatable",
"to",
"database"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Translator/Translator.php#L127-L152
|
26,450
|
libgraviton/graviton
|
src/Graviton/I18nBundle/Translator/Translator.php
|
Translator.getLanguages
|
public function getLanguages()
{
if (!empty($this->languages)) {
return $this->languages;
}
$this->languages = array_map(
function ($record) {
return $record['_id'];
},
$this->languageCollection->find([], ['_id' => 1])->toArray()
);
asort($this->languages);
$this->languages = array_values($this->languages);
return $this->languages;
}
|
php
|
public function getLanguages()
{
if (!empty($this->languages)) {
return $this->languages;
}
$this->languages = array_map(
function ($record) {
return $record['_id'];
},
$this->languageCollection->find([], ['_id' => 1])->toArray()
);
asort($this->languages);
$this->languages = array_values($this->languages);
return $this->languages;
}
|
[
"public",
"function",
"getLanguages",
"(",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"languages",
")",
")",
"{",
"return",
"$",
"this",
"->",
"languages",
";",
"}",
"$",
"this",
"->",
"languages",
"=",
"array_map",
"(",
"function",
"(",
"$",
"record",
")",
"{",
"return",
"$",
"record",
"[",
"'_id'",
"]",
";",
"}",
",",
"$",
"this",
"->",
"languageCollection",
"->",
"find",
"(",
"[",
"]",
",",
"[",
"'_id'",
"=>",
"1",
"]",
")",
"->",
"toArray",
"(",
")",
")",
";",
"asort",
"(",
"$",
"this",
"->",
"languages",
")",
";",
"$",
"this",
"->",
"languages",
"=",
"array_values",
"(",
"$",
"this",
"->",
"languages",
")",
";",
"return",
"$",
"this",
"->",
"languages",
";",
"}"
] |
returns all available languages
@return array languages
|
[
"returns",
"all",
"available",
"languages"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Translator/Translator.php#L159-L177
|
26,451
|
libgraviton/graviton
|
src/Graviton/I18nBundle/Translator/Translator.php
|
Translator.getFromCache
|
private function getFromCache($original)
{
$cacheContent = $this->cache->fetch($this->getCacheKey($original));
if (is_array($cacheContent) && isset($cacheContent[$original])) {
return $cacheContent[$original];
}
return null;
}
|
php
|
private function getFromCache($original)
{
$cacheContent = $this->cache->fetch($this->getCacheKey($original));
if (is_array($cacheContent) && isset($cacheContent[$original])) {
return $cacheContent[$original];
}
return null;
}
|
[
"private",
"function",
"getFromCache",
"(",
"$",
"original",
")",
"{",
"$",
"cacheContent",
"=",
"$",
"this",
"->",
"cache",
"->",
"fetch",
"(",
"$",
"this",
"->",
"getCacheKey",
"(",
"$",
"original",
")",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"cacheContent",
")",
"&&",
"isset",
"(",
"$",
"cacheContent",
"[",
"$",
"original",
"]",
")",
")",
"{",
"return",
"$",
"cacheContent",
"[",
"$",
"original",
"]",
";",
"}",
"return",
"null",
";",
"}"
] |
gets entry from cache
@param string $original original string
@return array|null entry
|
[
"gets",
"entry",
"from",
"cache"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Translator/Translator.php#L186-L194
|
26,452
|
libgraviton/graviton
|
src/Graviton/I18nBundle/Translator/Translator.php
|
Translator.saveToCache
|
private function saveToCache($original, $translations)
{
$cacheKey = $this->getCacheKey($original);
$cacheContent = $this->cache->fetch($cacheKey);
if (is_array($cacheContent)) {
$cacheContent[$original] = $translations;
} else {
$cacheContent = [$original => $translations];
}
$this->cache->save($cacheKey, $cacheContent);
}
|
php
|
private function saveToCache($original, $translations)
{
$cacheKey = $this->getCacheKey($original);
$cacheContent = $this->cache->fetch($cacheKey);
if (is_array($cacheContent)) {
$cacheContent[$original] = $translations;
} else {
$cacheContent = [$original => $translations];
}
$this->cache->save($cacheKey, $cacheContent);
}
|
[
"private",
"function",
"saveToCache",
"(",
"$",
"original",
",",
"$",
"translations",
")",
"{",
"$",
"cacheKey",
"=",
"$",
"this",
"->",
"getCacheKey",
"(",
"$",
"original",
")",
";",
"$",
"cacheContent",
"=",
"$",
"this",
"->",
"cache",
"->",
"fetch",
"(",
"$",
"cacheKey",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"cacheContent",
")",
")",
"{",
"$",
"cacheContent",
"[",
"$",
"original",
"]",
"=",
"$",
"translations",
";",
"}",
"else",
"{",
"$",
"cacheContent",
"=",
"[",
"$",
"original",
"=>",
"$",
"translations",
"]",
";",
"}",
"$",
"this",
"->",
"cache",
"->",
"save",
"(",
"$",
"cacheKey",
",",
"$",
"cacheContent",
")",
";",
"}"
] |
saves entry to cache
@param string $original original string
@param array $translations translations
@return void
|
[
"saves",
"entry",
"to",
"cache"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Translator/Translator.php#L204-L215
|
26,453
|
libgraviton/graviton
|
src/Graviton/I18nBundle/Translator/Translator.php
|
Translator.removeFromCache
|
private function removeFromCache($original)
{
$cacheKey = $this->getCacheKey($original);
$cacheContent = $this->cache->fetch($this->getCacheKey($original));
if (is_array($cacheContent) && isset($cacheContent[$original])) {
unset($cacheContent[$original]);
$this->cache->save($cacheKey, $cacheContent);
}
}
|
php
|
private function removeFromCache($original)
{
$cacheKey = $this->getCacheKey($original);
$cacheContent = $this->cache->fetch($this->getCacheKey($original));
if (is_array($cacheContent) && isset($cacheContent[$original])) {
unset($cacheContent[$original]);
$this->cache->save($cacheKey, $cacheContent);
}
}
|
[
"private",
"function",
"removeFromCache",
"(",
"$",
"original",
")",
"{",
"$",
"cacheKey",
"=",
"$",
"this",
"->",
"getCacheKey",
"(",
"$",
"original",
")",
";",
"$",
"cacheContent",
"=",
"$",
"this",
"->",
"cache",
"->",
"fetch",
"(",
"$",
"this",
"->",
"getCacheKey",
"(",
"$",
"original",
")",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"cacheContent",
")",
"&&",
"isset",
"(",
"$",
"cacheContent",
"[",
"$",
"original",
"]",
")",
")",
"{",
"unset",
"(",
"$",
"cacheContent",
"[",
"$",
"original",
"]",
")",
";",
"$",
"this",
"->",
"cache",
"->",
"save",
"(",
"$",
"cacheKey",
",",
"$",
"cacheContent",
")",
";",
"}",
"}"
] |
removes entry from cache
@param string $original original string
@return void
|
[
"removes",
"entry",
"from",
"cache"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Translator/Translator.php#L224-L232
|
26,454
|
libgraviton/graviton
|
src/Graviton/I18nBundle/Translator/Translator.php
|
Translator.getCacheKey
|
private function getCacheKey($original)
{
return sprintf(
'translator_%s_%s',
implode('.', $this->getLanguages()),
str_pad(strtolower(substr($original, 0, $this->cacheNameDepth)), $this->cacheNameDepth, '.')
);
}
|
php
|
private function getCacheKey($original)
{
return sprintf(
'translator_%s_%s',
implode('.', $this->getLanguages()),
str_pad(strtolower(substr($original, 0, $this->cacheNameDepth)), $this->cacheNameDepth, '.')
);
}
|
[
"private",
"function",
"getCacheKey",
"(",
"$",
"original",
")",
"{",
"return",
"sprintf",
"(",
"'translator_%s_%s'",
",",
"implode",
"(",
"'.'",
",",
"$",
"this",
"->",
"getLanguages",
"(",
")",
")",
",",
"str_pad",
"(",
"strtolower",
"(",
"substr",
"(",
"$",
"original",
",",
"0",
",",
"$",
"this",
"->",
"cacheNameDepth",
")",
")",
",",
"$",
"this",
"->",
"cacheNameDepth",
",",
"'.'",
")",
")",
";",
"}"
] |
returns the caching key
@param string $original original string
@return string cache key
|
[
"returns",
"the",
"caching",
"key"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/I18nBundle/Translator/Translator.php#L241-L248
|
26,455
|
libgraviton/graviton
|
src/Graviton/RestBundle/HttpFoundation/LinkHeaderItem.php
|
LinkHeaderItem.fromString
|
public static function fromString($itemValue)
{
$bits = preg_split('/(".+?"|[^;]+)(?:;|$)/', $itemValue, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$value = array_shift($bits);
$attributes = [];
foreach ($bits as $bit) {
list($bitName, $bitValue) = explode('=', trim($bit));
$bitValue = self::trimEdge($bitValue, '"');
$bitValue = self::trimEdge($bitValue, '\'');
$attributes[$bitName] = $bitValue;
}
$url = self::trimEdge($value, '<');
return new self($url, $attributes);
}
|
php
|
public static function fromString($itemValue)
{
$bits = preg_split('/(".+?"|[^;]+)(?:;|$)/', $itemValue, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$value = array_shift($bits);
$attributes = [];
foreach ($bits as $bit) {
list($bitName, $bitValue) = explode('=', trim($bit));
$bitValue = self::trimEdge($bitValue, '"');
$bitValue = self::trimEdge($bitValue, '\'');
$attributes[$bitName] = $bitValue;
}
$url = self::trimEdge($value, '<');
return new self($url, $attributes);
}
|
[
"public",
"static",
"function",
"fromString",
"(",
"$",
"itemValue",
")",
"{",
"$",
"bits",
"=",
"preg_split",
"(",
"'/(\".+?\"|[^;]+)(?:;|$)/'",
",",
"$",
"itemValue",
",",
"0",
",",
"PREG_SPLIT_NO_EMPTY",
"|",
"PREG_SPLIT_DELIM_CAPTURE",
")",
";",
"$",
"value",
"=",
"array_shift",
"(",
"$",
"bits",
")",
";",
"$",
"attributes",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"bits",
"as",
"$",
"bit",
")",
"{",
"list",
"(",
"$",
"bitName",
",",
"$",
"bitValue",
")",
"=",
"explode",
"(",
"'='",
",",
"trim",
"(",
"$",
"bit",
")",
")",
";",
"$",
"bitValue",
"=",
"self",
"::",
"trimEdge",
"(",
"$",
"bitValue",
",",
"'\"'",
")",
";",
"$",
"bitValue",
"=",
"self",
"::",
"trimEdge",
"(",
"$",
"bitValue",
",",
"'\\''",
")",
";",
"$",
"attributes",
"[",
"$",
"bitName",
"]",
"=",
"$",
"bitValue",
";",
"}",
"$",
"url",
"=",
"self",
"::",
"trimEdge",
"(",
"$",
"value",
",",
"'<'",
")",
";",
"return",
"new",
"self",
"(",
"$",
"url",
",",
"$",
"attributes",
")",
";",
"}"
] |
Builds a LinkHeaderItem instance from a string.
@param string $itemValue value of a single link header
@return \Graviton\RestBundle\HttpFoundation\LinkHeaderItem
|
[
"Builds",
"a",
"LinkHeaderItem",
"instance",
"from",
"a",
"string",
"."
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/HttpFoundation/LinkHeaderItem.php#L51-L69
|
26,456
|
libgraviton/graviton
|
src/Graviton/RestBundle/HttpFoundation/LinkHeaderItem.php
|
LinkHeaderItem.trimEdge
|
private static function trimEdge($string, $char)
{
if (substr($string, 0, 1) == $char) {
$string = substr($string, 1, -1);
}
return $string;
}
|
php
|
private static function trimEdge($string, $char)
{
if (substr($string, 0, 1) == $char) {
$string = substr($string, 1, -1);
}
return $string;
}
|
[
"private",
"static",
"function",
"trimEdge",
"(",
"$",
"string",
",",
"$",
"char",
")",
"{",
"if",
"(",
"substr",
"(",
"$",
"string",
",",
"0",
",",
"1",
")",
"==",
"$",
"char",
")",
"{",
"$",
"string",
"=",
"substr",
"(",
"$",
"string",
",",
"1",
",",
"-",
"1",
")",
";",
"}",
"return",
"$",
"string",
";",
"}"
] |
trim edge of string if char maches
@param string $string string
@param string $char char
@return string
|
[
"trim",
"edge",
"of",
"string",
"if",
"char",
"maches"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/HttpFoundation/LinkHeaderItem.php#L158-L165
|
26,457
|
libgraviton/graviton
|
src/Graviton/SecurityBundle/Authentication/Provider/AuthenticationProviderDummy.php
|
AuthenticationProviderDummy.loadUserByUsername
|
public function loadUserByUsername($username)
{
if ($username !== 'testUsername') {
return false;
}
/** @var UserInterface $user */
$user = new \stdClass();
$user->id = 123;
$user->username = $username;
$user->firstName = 'aName';
$user->lastName = 'aSurname';
return $user;
}
|
php
|
public function loadUserByUsername($username)
{
if ($username !== 'testUsername') {
return false;
}
/** @var UserInterface $user */
$user = new \stdClass();
$user->id = 123;
$user->username = $username;
$user->firstName = 'aName';
$user->lastName = 'aSurname';
return $user;
}
|
[
"public",
"function",
"loadUserByUsername",
"(",
"$",
"username",
")",
"{",
"if",
"(",
"$",
"username",
"!==",
"'testUsername'",
")",
"{",
"return",
"false",
";",
"}",
"/** @var UserInterface $user */",
"$",
"user",
"=",
"new",
"\\",
"stdClass",
"(",
")",
";",
"$",
"user",
"->",
"id",
"=",
"123",
";",
"$",
"user",
"->",
"username",
"=",
"$",
"username",
";",
"$",
"user",
"->",
"firstName",
"=",
"'aName'",
";",
"$",
"user",
"->",
"lastName",
"=",
"'aSurname'",
";",
"return",
"$",
"user",
";",
"}"
] |
Dummy loader for test case
This method must throw UsernameNotFoundException if the user is not
found.
@param string $username the consultants username
@return false|UserInterface
|
[
"Dummy",
"loader",
"for",
"test",
"case"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SecurityBundle/Authentication/Provider/AuthenticationProviderDummy.php#L36-L50
|
26,458
|
libgraviton/graviton
|
src/Graviton/RestBundle/Service/QueryService.php
|
QueryService.hasSearchIndex
|
private function hasSearchIndex()
{
$metadata = $this->repository->getClassMetadata();
$indexes = $metadata->getIndexes();
if (empty($indexes)) {
return false;
}
$text = array_filter(
$indexes,
function ($index) {
if (isset($index['keys'])) {
$hasText = false;
foreach ($index['keys'] as $name => $direction) {
if ($direction == 'text') {
$hasText = true;
}
}
return $hasText;
}
}
);
return !empty($text);
}
|
php
|
private function hasSearchIndex()
{
$metadata = $this->repository->getClassMetadata();
$indexes = $metadata->getIndexes();
if (empty($indexes)) {
return false;
}
$text = array_filter(
$indexes,
function ($index) {
if (isset($index['keys'])) {
$hasText = false;
foreach ($index['keys'] as $name => $direction) {
if ($direction == 'text') {
$hasText = true;
}
}
return $hasText;
}
}
);
return !empty($text);
}
|
[
"private",
"function",
"hasSearchIndex",
"(",
")",
"{",
"$",
"metadata",
"=",
"$",
"this",
"->",
"repository",
"->",
"getClassMetadata",
"(",
")",
";",
"$",
"indexes",
"=",
"$",
"metadata",
"->",
"getIndexes",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"indexes",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"text",
"=",
"array_filter",
"(",
"$",
"indexes",
",",
"function",
"(",
"$",
"index",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"index",
"[",
"'keys'",
"]",
")",
")",
"{",
"$",
"hasText",
"=",
"false",
";",
"foreach",
"(",
"$",
"index",
"[",
"'keys'",
"]",
"as",
"$",
"name",
"=>",
"$",
"direction",
")",
"{",
"if",
"(",
"$",
"direction",
"==",
"'text'",
")",
"{",
"$",
"hasText",
"=",
"true",
";",
"}",
"}",
"return",
"$",
"hasText",
";",
"}",
"}",
")",
";",
"return",
"!",
"empty",
"(",
"$",
"text",
")",
";",
"}"
] |
Check if collection has search indexes in DB
@return bool
|
[
"Check",
"if",
"collection",
"has",
"search",
"indexes",
"in",
"DB"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Service/QueryService.php#L246-L270
|
26,459
|
libgraviton/graviton
|
src/Graviton/RestBundle/Service/QueryService.php
|
QueryService.getPaginationPageSize
|
private function getPaginationPageSize()
{
$limitNode = $this->getPaginationLimitNode();
if ($limitNode) {
$limit = $limitNode->getLimit();
if ($limit < 1) {
throw new SyntaxErrorException('invalid limit in rql');
}
return $limit;
}
return $this->paginationDefaultLimit;
}
|
php
|
private function getPaginationPageSize()
{
$limitNode = $this->getPaginationLimitNode();
if ($limitNode) {
$limit = $limitNode->getLimit();
if ($limit < 1) {
throw new SyntaxErrorException('invalid limit in rql');
}
return $limit;
}
return $this->paginationDefaultLimit;
}
|
[
"private",
"function",
"getPaginationPageSize",
"(",
")",
"{",
"$",
"limitNode",
"=",
"$",
"this",
"->",
"getPaginationLimitNode",
"(",
")",
";",
"if",
"(",
"$",
"limitNode",
")",
"{",
"$",
"limit",
"=",
"$",
"limitNode",
"->",
"getLimit",
"(",
")",
";",
"if",
"(",
"$",
"limit",
"<",
"1",
")",
"{",
"throw",
"new",
"SyntaxErrorException",
"(",
"'invalid limit in rql'",
")",
";",
"}",
"return",
"$",
"limit",
";",
"}",
"return",
"$",
"this",
"->",
"paginationDefaultLimit",
";",
"}"
] |
get the pagination page size
@return int page size
|
[
"get",
"the",
"pagination",
"page",
"size"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Service/QueryService.php#L277-L292
|
26,460
|
libgraviton/graviton
|
src/Graviton/RestBundle/Service/QueryService.php
|
QueryService.getPaginationLimitNode
|
private function getPaginationLimitNode()
{
/** @var Query $rqlQuery */
$rqlQuery = $this->request->attributes->get('rqlQuery');
if ($rqlQuery instanceof Query && $rqlQuery->getLimit() instanceof LimitNode) {
return $rqlQuery->getLimit();
}
return false;
}
|
php
|
private function getPaginationLimitNode()
{
/** @var Query $rqlQuery */
$rqlQuery = $this->request->attributes->get('rqlQuery');
if ($rqlQuery instanceof Query && $rqlQuery->getLimit() instanceof LimitNode) {
return $rqlQuery->getLimit();
}
return false;
}
|
[
"private",
"function",
"getPaginationLimitNode",
"(",
")",
"{",
"/** @var Query $rqlQuery */",
"$",
"rqlQuery",
"=",
"$",
"this",
"->",
"request",
"->",
"attributes",
"->",
"get",
"(",
"'rqlQuery'",
")",
";",
"if",
"(",
"$",
"rqlQuery",
"instanceof",
"Query",
"&&",
"$",
"rqlQuery",
"->",
"getLimit",
"(",
")",
"instanceof",
"LimitNode",
")",
"{",
"return",
"$",
"rqlQuery",
"->",
"getLimit",
"(",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
gets the limit node
@return bool|LimitNode the node or false
|
[
"gets",
"the",
"limit",
"node"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Service/QueryService.php#L315-L325
|
26,461
|
libgraviton/graviton
|
src/Graviton/FileBundle/Manager/FileManager.php
|
FileManager.buildGetContentResponse
|
public function buildGetContentResponse(Response $response, FileDocument $file)
{
/** @var FileMetadataBase $metadata */
$metadata = $file->getMetadata();
if (!$metadata) {
throw new InvalidArgumentException('Loaded file have no valid metadata');
}
// We use file's mimeType, just in case none we use DB's.
$mimeType = null;
if ($this->readFileSystemMimeType) {
$mimeType = $this->fileSystem->getMimetype($file->getId());
}
if (!$mimeType) {
$mimeType = $metadata->getMime();
}
if ($this->allowedMimeTypes && !in_array($mimeType, $this->allowedMimeTypes)) {
throw new InvalidArgumentException('File mime type: '.$mimeType.' is not allowed as response.');
}
// Create Response
$disposition = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_INLINE,
$metadata->getFilename()
);
$response
->setStatusCode(Response::HTTP_OK)
->setContent($this->fileSystem->read($file->getId()));
$response
->headers->set('Content-Type', $mimeType);
$response
->headers->set('Content-Disposition', $disposition);
return $response;
}
|
php
|
public function buildGetContentResponse(Response $response, FileDocument $file)
{
/** @var FileMetadataBase $metadata */
$metadata = $file->getMetadata();
if (!$metadata) {
throw new InvalidArgumentException('Loaded file have no valid metadata');
}
// We use file's mimeType, just in case none we use DB's.
$mimeType = null;
if ($this->readFileSystemMimeType) {
$mimeType = $this->fileSystem->getMimetype($file->getId());
}
if (!$mimeType) {
$mimeType = $metadata->getMime();
}
if ($this->allowedMimeTypes && !in_array($mimeType, $this->allowedMimeTypes)) {
throw new InvalidArgumentException('File mime type: '.$mimeType.' is not allowed as response.');
}
// Create Response
$disposition = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_INLINE,
$metadata->getFilename()
);
$response
->setStatusCode(Response::HTTP_OK)
->setContent($this->fileSystem->read($file->getId()));
$response
->headers->set('Content-Type', $mimeType);
$response
->headers->set('Content-Disposition', $disposition);
return $response;
}
|
[
"public",
"function",
"buildGetContentResponse",
"(",
"Response",
"$",
"response",
",",
"FileDocument",
"$",
"file",
")",
"{",
"/** @var FileMetadataBase $metadata */",
"$",
"metadata",
"=",
"$",
"file",
"->",
"getMetadata",
"(",
")",
";",
"if",
"(",
"!",
"$",
"metadata",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Loaded file have no valid metadata'",
")",
";",
"}",
"// We use file's mimeType, just in case none we use DB's.",
"$",
"mimeType",
"=",
"null",
";",
"if",
"(",
"$",
"this",
"->",
"readFileSystemMimeType",
")",
"{",
"$",
"mimeType",
"=",
"$",
"this",
"->",
"fileSystem",
"->",
"getMimetype",
"(",
"$",
"file",
"->",
"getId",
"(",
")",
")",
";",
"}",
"if",
"(",
"!",
"$",
"mimeType",
")",
"{",
"$",
"mimeType",
"=",
"$",
"metadata",
"->",
"getMime",
"(",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"allowedMimeTypes",
"&&",
"!",
"in_array",
"(",
"$",
"mimeType",
",",
"$",
"this",
"->",
"allowedMimeTypes",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'File mime type: '",
".",
"$",
"mimeType",
".",
"' is not allowed as response.'",
")",
";",
"}",
"// Create Response",
"$",
"disposition",
"=",
"$",
"response",
"->",
"headers",
"->",
"makeDisposition",
"(",
"ResponseHeaderBag",
"::",
"DISPOSITION_INLINE",
",",
"$",
"metadata",
"->",
"getFilename",
"(",
")",
")",
";",
"$",
"response",
"->",
"setStatusCode",
"(",
"Response",
"::",
"HTTP_OK",
")",
"->",
"setContent",
"(",
"$",
"this",
"->",
"fileSystem",
"->",
"read",
"(",
"$",
"file",
"->",
"getId",
"(",
")",
")",
")",
";",
"$",
"response",
"->",
"headers",
"->",
"set",
"(",
"'Content-Type'",
",",
"$",
"mimeType",
")",
";",
"$",
"response",
"->",
"headers",
"->",
"set",
"(",
"'Content-Disposition'",
",",
"$",
"disposition",
")",
";",
"return",
"$",
"response",
";",
"}"
] |
Will update the response object with provided file data
@param Response $response response
@param DocumentFile $file File document object from DB
@return Response
@throws InvalidArgumentException if invalid info fetched from fileSystem
|
[
"Will",
"update",
"the",
"response",
"object",
"with",
"provided",
"file",
"data"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/FileBundle/Manager/FileManager.php#L100-L135
|
26,462
|
libgraviton/graviton
|
src/Graviton/FileBundle/Manager/FileManager.php
|
FileManager.saveFile
|
public function saveFile($id, $filepath)
{
// will save using a stream
$fp = fopen($filepath, 'r+');
$this->fileSystem->putStream($id, $fp);
// close file
fclose($fp);
}
|
php
|
public function saveFile($id, $filepath)
{
// will save using a stream
$fp = fopen($filepath, 'r+');
$this->fileSystem->putStream($id, $fp);
// close file
fclose($fp);
}
|
[
"public",
"function",
"saveFile",
"(",
"$",
"id",
",",
"$",
"filepath",
")",
"{",
"// will save using a stream",
"$",
"fp",
"=",
"fopen",
"(",
"$",
"filepath",
",",
"'r+'",
")",
";",
"$",
"this",
"->",
"fileSystem",
"->",
"putStream",
"(",
"$",
"id",
",",
"$",
"fp",
")",
";",
"// close file",
"fclose",
"(",
"$",
"fp",
")",
";",
"}"
] |
Save or update a file
@param string $id ID of file
@param String $filepath path to the file to save
@return void
|
[
"Save",
"or",
"update",
"a",
"file"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/FileBundle/Manager/FileManager.php#L146-L155
|
26,463
|
libgraviton/graviton
|
src/Graviton/FileBundle/Manager/FileManager.php
|
FileManager.buildFileDocument
|
private function buildFileDocument(FileDocument $document, $file, $original)
{
$now = new \DateTime();
// If only a file is posted, check if there is a original object and clone it
if ($file && $original && !$document->getMetadata()) {
$document = clone $original;
}
// Basic Metadata update
$metadata = $document->getMetadata() ?: new FileMetadataEmbedded();
// File related, if no file uploaded we keep original file info.
if ($file) {
$hash = $metadata->getHash();
if (!$hash || strlen($hash)>64) {
$hash = hash('sha256', file_get_contents($file->getRealPath()));
} else {
$hash = preg_replace('/[^a-z0-9_-]/i', '-', $hash);
}
$metadata->setHash($hash);
$metadata->setMime($file->getMimeType());
$metadata->setSize($file->getSize());
if (!$metadata->getFilename()) {
$fileName = $file->getClientOriginalName() ? $file->getClientOriginalName() : $file->getFilename();
$fileName = preg_replace("/[^a-zA-Z0-9.]/", "-", $fileName);
$metadata->setFilename($fileName);
}
} elseif ($original && ($originalMetadata = $original->getMetadata())) {
if (!$metadata->getFilename()) {
$metadata->setFilename($originalMetadata->getFilename());
}
$metadata->setHash($originalMetadata->getHash());
$metadata->setMime($originalMetadata->getMime());
$metadata->setSize($originalMetadata->getSize());
}
// Creation date. keep original if available
if ($original && $original->getMetadata() && $original->getMetadata()->getCreatedate()) {
$metadata->setCreatedate($original->getMetadata()->getCreatedate());
} else {
$metadata->setCreatedate($now);
}
$metadata->setModificationdate($now);
$document->setMetadata($metadata);
return $document;
}
|
php
|
private function buildFileDocument(FileDocument $document, $file, $original)
{
$now = new \DateTime();
// If only a file is posted, check if there is a original object and clone it
if ($file && $original && !$document->getMetadata()) {
$document = clone $original;
}
// Basic Metadata update
$metadata = $document->getMetadata() ?: new FileMetadataEmbedded();
// File related, if no file uploaded we keep original file info.
if ($file) {
$hash = $metadata->getHash();
if (!$hash || strlen($hash)>64) {
$hash = hash('sha256', file_get_contents($file->getRealPath()));
} else {
$hash = preg_replace('/[^a-z0-9_-]/i', '-', $hash);
}
$metadata->setHash($hash);
$metadata->setMime($file->getMimeType());
$metadata->setSize($file->getSize());
if (!$metadata->getFilename()) {
$fileName = $file->getClientOriginalName() ? $file->getClientOriginalName() : $file->getFilename();
$fileName = preg_replace("/[^a-zA-Z0-9.]/", "-", $fileName);
$metadata->setFilename($fileName);
}
} elseif ($original && ($originalMetadata = $original->getMetadata())) {
if (!$metadata->getFilename()) {
$metadata->setFilename($originalMetadata->getFilename());
}
$metadata->setHash($originalMetadata->getHash());
$metadata->setMime($originalMetadata->getMime());
$metadata->setSize($originalMetadata->getSize());
}
// Creation date. keep original if available
if ($original && $original->getMetadata() && $original->getMetadata()->getCreatedate()) {
$metadata->setCreatedate($original->getMetadata()->getCreatedate());
} else {
$metadata->setCreatedate($now);
}
$metadata->setModificationdate($now);
$document->setMetadata($metadata);
return $document;
}
|
[
"private",
"function",
"buildFileDocument",
"(",
"FileDocument",
"$",
"document",
",",
"$",
"file",
",",
"$",
"original",
")",
"{",
"$",
"now",
"=",
"new",
"\\",
"DateTime",
"(",
")",
";",
"// If only a file is posted, check if there is a original object and clone it",
"if",
"(",
"$",
"file",
"&&",
"$",
"original",
"&&",
"!",
"$",
"document",
"->",
"getMetadata",
"(",
")",
")",
"{",
"$",
"document",
"=",
"clone",
"$",
"original",
";",
"}",
"// Basic Metadata update",
"$",
"metadata",
"=",
"$",
"document",
"->",
"getMetadata",
"(",
")",
"?",
":",
"new",
"FileMetadataEmbedded",
"(",
")",
";",
"// File related, if no file uploaded we keep original file info.",
"if",
"(",
"$",
"file",
")",
"{",
"$",
"hash",
"=",
"$",
"metadata",
"->",
"getHash",
"(",
")",
";",
"if",
"(",
"!",
"$",
"hash",
"||",
"strlen",
"(",
"$",
"hash",
")",
">",
"64",
")",
"{",
"$",
"hash",
"=",
"hash",
"(",
"'sha256'",
",",
"file_get_contents",
"(",
"$",
"file",
"->",
"getRealPath",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"$",
"hash",
"=",
"preg_replace",
"(",
"'/[^a-z0-9_-]/i'",
",",
"'-'",
",",
"$",
"hash",
")",
";",
"}",
"$",
"metadata",
"->",
"setHash",
"(",
"$",
"hash",
")",
";",
"$",
"metadata",
"->",
"setMime",
"(",
"$",
"file",
"->",
"getMimeType",
"(",
")",
")",
";",
"$",
"metadata",
"->",
"setSize",
"(",
"$",
"file",
"->",
"getSize",
"(",
")",
")",
";",
"if",
"(",
"!",
"$",
"metadata",
"->",
"getFilename",
"(",
")",
")",
"{",
"$",
"fileName",
"=",
"$",
"file",
"->",
"getClientOriginalName",
"(",
")",
"?",
"$",
"file",
"->",
"getClientOriginalName",
"(",
")",
":",
"$",
"file",
"->",
"getFilename",
"(",
")",
";",
"$",
"fileName",
"=",
"preg_replace",
"(",
"\"/[^a-zA-Z0-9.]/\"",
",",
"\"-\"",
",",
"$",
"fileName",
")",
";",
"$",
"metadata",
"->",
"setFilename",
"(",
"$",
"fileName",
")",
";",
"}",
"}",
"elseif",
"(",
"$",
"original",
"&&",
"(",
"$",
"originalMetadata",
"=",
"$",
"original",
"->",
"getMetadata",
"(",
")",
")",
")",
"{",
"if",
"(",
"!",
"$",
"metadata",
"->",
"getFilename",
"(",
")",
")",
"{",
"$",
"metadata",
"->",
"setFilename",
"(",
"$",
"originalMetadata",
"->",
"getFilename",
"(",
")",
")",
";",
"}",
"$",
"metadata",
"->",
"setHash",
"(",
"$",
"originalMetadata",
"->",
"getHash",
"(",
")",
")",
";",
"$",
"metadata",
"->",
"setMime",
"(",
"$",
"originalMetadata",
"->",
"getMime",
"(",
")",
")",
";",
"$",
"metadata",
"->",
"setSize",
"(",
"$",
"originalMetadata",
"->",
"getSize",
"(",
")",
")",
";",
"}",
"// Creation date. keep original if available",
"if",
"(",
"$",
"original",
"&&",
"$",
"original",
"->",
"getMetadata",
"(",
")",
"&&",
"$",
"original",
"->",
"getMetadata",
"(",
")",
"->",
"getCreatedate",
"(",
")",
")",
"{",
"$",
"metadata",
"->",
"setCreatedate",
"(",
"$",
"original",
"->",
"getMetadata",
"(",
")",
"->",
"getCreatedate",
"(",
")",
")",
";",
"}",
"else",
"{",
"$",
"metadata",
"->",
"setCreatedate",
"(",
"$",
"now",
")",
";",
"}",
"$",
"metadata",
"->",
"setModificationdate",
"(",
"$",
"now",
")",
";",
"$",
"document",
"->",
"setMetadata",
"(",
"$",
"metadata",
")",
";",
"return",
"$",
"document",
";",
"}"
] |
Create the basic needs for a file
@param DocumentFile $document Post or Put file document
@param UploadedFile $file To be used in set metadata
@param DocumentFile $original If there is a original document
@return DocumentFile
@throws InvalidArgumentException
|
[
"Create",
"the",
"basic",
"needs",
"for",
"a",
"file"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/FileBundle/Manager/FileManager.php#L237-L285
|
26,464
|
libgraviton/graviton
|
src/Graviton/FileBundle/Manager/FileManager.php
|
FileManager.remove
|
public function remove($id)
{
if ($this->fileSystem->has($id)) {
$this->fileSystem->delete($id);
}
}
|
php
|
public function remove($id)
{
if ($this->fileSystem->has($id)) {
$this->fileSystem->delete($id);
}
}
|
[
"public",
"function",
"remove",
"(",
"$",
"id",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"fileSystem",
"->",
"has",
"(",
"$",
"id",
")",
")",
"{",
"$",
"this",
"->",
"fileSystem",
"->",
"delete",
"(",
"$",
"id",
")",
";",
"}",
"}"
] |
Simple delete item from file system
@param string $id ID of file to be deleted
@return void
|
[
"Simple",
"delete",
"item",
"from",
"file",
"system"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/FileBundle/Manager/FileManager.php#L312-L317
|
26,465
|
libgraviton/graviton
|
src/Graviton/FileBundle/Manager/FileManager.php
|
FileManager.getUploadedFileFromRequest
|
private function getUploadedFileFromRequest(Request $request)
{
$file = false;
if ($request->files instanceof FileBag && $request->files->count() > 0) {
if ($request->files->count() > 1) {
throw new InvalidArgumentException('Only 1 file upload per requests allowed.');
}
$files = $request->files->all();
$file = reset($files);
if ($this->allowedMimeTypes && !in_array($file->getMimeType(), $this->allowedMimeTypes)) {
throw new InvalidArgumentException('File mime type: '.$file->getMimeType().' is not allowed.');
}
}
return $file;
}
|
php
|
private function getUploadedFileFromRequest(Request $request)
{
$file = false;
if ($request->files instanceof FileBag && $request->files->count() > 0) {
if ($request->files->count() > 1) {
throw new InvalidArgumentException('Only 1 file upload per requests allowed.');
}
$files = $request->files->all();
$file = reset($files);
if ($this->allowedMimeTypes && !in_array($file->getMimeType(), $this->allowedMimeTypes)) {
throw new InvalidArgumentException('File mime type: '.$file->getMimeType().' is not allowed.');
}
}
return $file;
}
|
[
"private",
"function",
"getUploadedFileFromRequest",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"file",
"=",
"false",
";",
"if",
"(",
"$",
"request",
"->",
"files",
"instanceof",
"FileBag",
"&&",
"$",
"request",
"->",
"files",
"->",
"count",
"(",
")",
">",
"0",
")",
"{",
"if",
"(",
"$",
"request",
"->",
"files",
"->",
"count",
"(",
")",
">",
"1",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Only 1 file upload per requests allowed.'",
")",
";",
"}",
"$",
"files",
"=",
"$",
"request",
"->",
"files",
"->",
"all",
"(",
")",
";",
"$",
"file",
"=",
"reset",
"(",
"$",
"files",
")",
";",
"if",
"(",
"$",
"this",
"->",
"allowedMimeTypes",
"&&",
"!",
"in_array",
"(",
"$",
"file",
"->",
"getMimeType",
"(",
")",
",",
"$",
"this",
"->",
"allowedMimeTypes",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'File mime type: '",
".",
"$",
"file",
"->",
"getMimeType",
"(",
")",
".",
"' is not allowed.'",
")",
";",
"}",
"}",
"return",
"$",
"file",
";",
"}"
] |
Set global uploaded file.
Only ONE file allowed per upload.
@param Request $request service request
@return UploadedFile if file was uploaded
@throws InvalidArgumentException
|
[
"Set",
"global",
"uploaded",
"file",
".",
"Only",
"ONE",
"file",
"allowed",
"per",
"upload",
"."
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/FileBundle/Manager/FileManager.php#L327-L343
|
26,466
|
libgraviton/graviton
|
src/Graviton/RestBundle/Controller/RestController.php
|
RestController.getAction
|
public function getAction(Request $request, $id)
{
$document = $this->getModel()->getSerialised($id, $request);
$response = $this->getResponse()
->setStatusCode(Response::HTTP_OK)
->setContent($document);
return $response;
}
|
php
|
public function getAction(Request $request, $id)
{
$document = $this->getModel()->getSerialised($id, $request);
$response = $this->getResponse()
->setStatusCode(Response::HTTP_OK)
->setContent($document);
return $response;
}
|
[
"public",
"function",
"getAction",
"(",
"Request",
"$",
"request",
",",
"$",
"id",
")",
"{",
"$",
"document",
"=",
"$",
"this",
"->",
"getModel",
"(",
")",
"->",
"getSerialised",
"(",
"$",
"id",
",",
"$",
"request",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"getResponse",
"(",
")",
"->",
"setStatusCode",
"(",
"Response",
"::",
"HTTP_OK",
")",
"->",
"setContent",
"(",
"$",
"document",
")",
";",
"return",
"$",
"response",
";",
"}"
] |
Returns a single record
@param Request $request Current http request
@param string $id ID of record
@return \Symfony\Component\HttpFoundation\Response $response Response with result or error
|
[
"Returns",
"a",
"single",
"record"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Controller/RestController.php#L131-L140
|
26,467
|
libgraviton/graviton
|
src/Graviton/RestBundle/Controller/RestController.php
|
RestController.allAction
|
public function allAction(Request $request)
{
$model = $this->getModel();
$content = $this->restUtils->serialize($model->findAll($request));
$response = $this->getResponse()
->setStatusCode(Response::HTTP_OK)
->setContent($content);
return $response;
}
|
php
|
public function allAction(Request $request)
{
$model = $this->getModel();
$content = $this->restUtils->serialize($model->findAll($request));
$response = $this->getResponse()
->setStatusCode(Response::HTTP_OK)
->setContent($content);
return $response;
}
|
[
"public",
"function",
"allAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"getModel",
"(",
")",
";",
"$",
"content",
"=",
"$",
"this",
"->",
"restUtils",
"->",
"serialize",
"(",
"$",
"model",
"->",
"findAll",
"(",
"$",
"request",
")",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"getResponse",
"(",
")",
"->",
"setStatusCode",
"(",
"Response",
"::",
"HTTP_OK",
")",
"->",
"setContent",
"(",
"$",
"content",
")",
";",
"return",
"$",
"response",
";",
"}"
] |
Returns all records
@param Request $request Current http request
@return \Symfony\Component\HttpFoundation\Response $response Response with result or error
|
[
"Returns",
"all",
"records"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Controller/RestController.php#L189-L200
|
26,468
|
libgraviton/graviton
|
src/Graviton/RestBundle/Controller/RestController.php
|
RestController.postAction
|
public function postAction(Request $request)
{
// Get the response object from container
$response = $this->getResponse();
$model = $this->getModel();
$this->restUtils->checkJsonRequest($request, $response, $this->getModel());
$record = $this->restUtils->validateRequest($request->getContent(), $model);
// Insert the new record
$record = $model->insertRecord($record);
// store id of new record so we dont need to reparse body later when needed
$request->attributes->set('id', $record->getId());
// Set status code
$response->setStatusCode(Response::HTTP_CREATED);
$response->headers->set(
'Location',
$this->getRouter()->generate($this->restUtils->getRouteName($request), array('id' => $record->getId()))
);
return $response;
}
|
php
|
public function postAction(Request $request)
{
// Get the response object from container
$response = $this->getResponse();
$model = $this->getModel();
$this->restUtils->checkJsonRequest($request, $response, $this->getModel());
$record = $this->restUtils->validateRequest($request->getContent(), $model);
// Insert the new record
$record = $model->insertRecord($record);
// store id of new record so we dont need to reparse body later when needed
$request->attributes->set('id', $record->getId());
// Set status code
$response->setStatusCode(Response::HTTP_CREATED);
$response->headers->set(
'Location',
$this->getRouter()->generate($this->restUtils->getRouteName($request), array('id' => $record->getId()))
);
return $response;
}
|
[
"public",
"function",
"postAction",
"(",
"Request",
"$",
"request",
")",
"{",
"// Get the response object from container",
"$",
"response",
"=",
"$",
"this",
"->",
"getResponse",
"(",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"getModel",
"(",
")",
";",
"$",
"this",
"->",
"restUtils",
"->",
"checkJsonRequest",
"(",
"$",
"request",
",",
"$",
"response",
",",
"$",
"this",
"->",
"getModel",
"(",
")",
")",
";",
"$",
"record",
"=",
"$",
"this",
"->",
"restUtils",
"->",
"validateRequest",
"(",
"$",
"request",
"->",
"getContent",
"(",
")",
",",
"$",
"model",
")",
";",
"// Insert the new record",
"$",
"record",
"=",
"$",
"model",
"->",
"insertRecord",
"(",
"$",
"record",
")",
";",
"// store id of new record so we dont need to reparse body later when needed",
"$",
"request",
"->",
"attributes",
"->",
"set",
"(",
"'id'",
",",
"$",
"record",
"->",
"getId",
"(",
")",
")",
";",
"// Set status code",
"$",
"response",
"->",
"setStatusCode",
"(",
"Response",
"::",
"HTTP_CREATED",
")",
";",
"$",
"response",
"->",
"headers",
"->",
"set",
"(",
"'Location'",
",",
"$",
"this",
"->",
"getRouter",
"(",
")",
"->",
"generate",
"(",
"$",
"this",
"->",
"restUtils",
"->",
"getRouteName",
"(",
"$",
"request",
")",
",",
"array",
"(",
"'id'",
"=>",
"$",
"record",
"->",
"getId",
"(",
")",
")",
")",
")",
";",
"return",
"$",
"response",
";",
"}"
] |
Writes a new Entry to the database
@param Request $request Current http request
@return \Symfony\Component\HttpFoundation\Response $response Result of action with data (if successful)
|
[
"Writes",
"a",
"new",
"Entry",
"to",
"the",
"database"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Controller/RestController.php#L209-L234
|
26,469
|
libgraviton/graviton
|
src/Graviton/RestBundle/Controller/RestController.php
|
RestController.patchAction
|
public function patchAction($id, Request $request)
{
$response = $this->getResponse();
$model = $this->getModel();
// Validate received data. On failure release the lock.
try {
// Check JSON Patch request
$this->restUtils->checkJsonRequest($request, $response, $model);
$this->restUtils->checkJsonPatchRequest(json_decode($request->getContent(), 1));
// Find record && apply $ref converter
$jsonDocument = $model->getSerialised($id, null);
try {
// Check if valid
$this->jsonPatchValidator->validate($jsonDocument, $request->getContent());
// Apply JSON patches
$patch = new Patch($jsonDocument, $request->getContent());
$patchedDocument = $patch->apply();
} catch (\Exception $e) {
throw new InvalidJsonPatchException($e->getMessage());
}
} catch (\Exception $e) {
throw $e;
}
// if document hasn't changed, pass HTTP_NOT_MODIFIED and exit
if ($jsonDocument == $patchedDocument) {
$response->setStatusCode(Response::HTTP_NOT_MODIFIED);
return $response;
}
// Validate result object
$record = $this->restUtils->validateRequest($patchedDocument, $model);
// Update object
$this->getModel()->updateRecord($id, $record);
// Set status response code
$response->setStatusCode(Response::HTTP_OK);
$response->headers->set(
'Content-Location',
$this->getRouter()->generate($this->restUtils->getRouteName($request), array('id' => $record->getId()))
);
return $response;
}
|
php
|
public function patchAction($id, Request $request)
{
$response = $this->getResponse();
$model = $this->getModel();
// Validate received data. On failure release the lock.
try {
// Check JSON Patch request
$this->restUtils->checkJsonRequest($request, $response, $model);
$this->restUtils->checkJsonPatchRequest(json_decode($request->getContent(), 1));
// Find record && apply $ref converter
$jsonDocument = $model->getSerialised($id, null);
try {
// Check if valid
$this->jsonPatchValidator->validate($jsonDocument, $request->getContent());
// Apply JSON patches
$patch = new Patch($jsonDocument, $request->getContent());
$patchedDocument = $patch->apply();
} catch (\Exception $e) {
throw new InvalidJsonPatchException($e->getMessage());
}
} catch (\Exception $e) {
throw $e;
}
// if document hasn't changed, pass HTTP_NOT_MODIFIED and exit
if ($jsonDocument == $patchedDocument) {
$response->setStatusCode(Response::HTTP_NOT_MODIFIED);
return $response;
}
// Validate result object
$record = $this->restUtils->validateRequest($patchedDocument, $model);
// Update object
$this->getModel()->updateRecord($id, $record);
// Set status response code
$response->setStatusCode(Response::HTTP_OK);
$response->headers->set(
'Content-Location',
$this->getRouter()->generate($this->restUtils->getRouteName($request), array('id' => $record->getId()))
);
return $response;
}
|
[
"public",
"function",
"patchAction",
"(",
"$",
"id",
",",
"Request",
"$",
"request",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"getResponse",
"(",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"getModel",
"(",
")",
";",
"// Validate received data. On failure release the lock.",
"try",
"{",
"// Check JSON Patch request",
"$",
"this",
"->",
"restUtils",
"->",
"checkJsonRequest",
"(",
"$",
"request",
",",
"$",
"response",
",",
"$",
"model",
")",
";",
"$",
"this",
"->",
"restUtils",
"->",
"checkJsonPatchRequest",
"(",
"json_decode",
"(",
"$",
"request",
"->",
"getContent",
"(",
")",
",",
"1",
")",
")",
";",
"// Find record && apply $ref converter",
"$",
"jsonDocument",
"=",
"$",
"model",
"->",
"getSerialised",
"(",
"$",
"id",
",",
"null",
")",
";",
"try",
"{",
"// Check if valid",
"$",
"this",
"->",
"jsonPatchValidator",
"->",
"validate",
"(",
"$",
"jsonDocument",
",",
"$",
"request",
"->",
"getContent",
"(",
")",
")",
";",
"// Apply JSON patches",
"$",
"patch",
"=",
"new",
"Patch",
"(",
"$",
"jsonDocument",
",",
"$",
"request",
"->",
"getContent",
"(",
")",
")",
";",
"$",
"patchedDocument",
"=",
"$",
"patch",
"->",
"apply",
"(",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"throw",
"new",
"InvalidJsonPatchException",
"(",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"throw",
"$",
"e",
";",
"}",
"// if document hasn't changed, pass HTTP_NOT_MODIFIED and exit",
"if",
"(",
"$",
"jsonDocument",
"==",
"$",
"patchedDocument",
")",
"{",
"$",
"response",
"->",
"setStatusCode",
"(",
"Response",
"::",
"HTTP_NOT_MODIFIED",
")",
";",
"return",
"$",
"response",
";",
"}",
"// Validate result object",
"$",
"record",
"=",
"$",
"this",
"->",
"restUtils",
"->",
"validateRequest",
"(",
"$",
"patchedDocument",
",",
"$",
"model",
")",
";",
"// Update object",
"$",
"this",
"->",
"getModel",
"(",
")",
"->",
"updateRecord",
"(",
"$",
"id",
",",
"$",
"record",
")",
";",
"// Set status response code",
"$",
"response",
"->",
"setStatusCode",
"(",
"Response",
"::",
"HTTP_OK",
")",
";",
"$",
"response",
"->",
"headers",
"->",
"set",
"(",
"'Content-Location'",
",",
"$",
"this",
"->",
"getRouter",
"(",
")",
"->",
"generate",
"(",
"$",
"this",
"->",
"restUtils",
"->",
"getRouteName",
"(",
"$",
"request",
")",
",",
"array",
"(",
"'id'",
"=>",
"$",
"record",
"->",
"getId",
"(",
")",
")",
")",
")",
";",
"return",
"$",
"response",
";",
"}"
] |
Patch a record
@param Number $id ID of record
@param Request $request Current http request
@throws MalformedInputException
@return Response $response Result of action with data (if successful)
|
[
"Patch",
"a",
"record"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Controller/RestController.php#L301-L348
|
26,470
|
libgraviton/graviton
|
src/Graviton/RestBundle/Controller/RestController.php
|
RestController.schemaAction
|
public function schemaAction(Request $request, $id = null)
{
$request->attributes->set('schemaRequest', true);
list($app, $module, , $modelName, $schemaType) = explode('.', $request->attributes->get('_route'));
$response = $this->response;
$response->setStatusCode(Response::HTTP_OK);
$response->setVary(['Origin', 'Accept-Encoding']);
$response->setPublic();
if (!$id && $schemaType != 'canonicalIdSchema') {
$schema = $this->schemaUtils->getCollectionSchema($modelName, $this->getModel());
} else {
$schema = $this->schemaUtils->getModelSchema($modelName, $this->getModel());
}
// enabled methods for CorsListener
$corsMethods = 'GET, POST, PUT, PATCH, DELETE, OPTIONS';
try {
$router = $this->getRouter();
// if post route is available we assume everything is readable
$router->generate(implode('.', array($app, $module, 'rest', $modelName, 'post')));
} catch (RouteNotFoundException $exception) {
// only allow read methods
$corsMethods = 'GET, OPTIONS';
}
$request->attributes->set('corsMethods', $corsMethods);
$response->setContent($this->restUtils->serialize($schema));
return $response;
}
|
php
|
public function schemaAction(Request $request, $id = null)
{
$request->attributes->set('schemaRequest', true);
list($app, $module, , $modelName, $schemaType) = explode('.', $request->attributes->get('_route'));
$response = $this->response;
$response->setStatusCode(Response::HTTP_OK);
$response->setVary(['Origin', 'Accept-Encoding']);
$response->setPublic();
if (!$id && $schemaType != 'canonicalIdSchema') {
$schema = $this->schemaUtils->getCollectionSchema($modelName, $this->getModel());
} else {
$schema = $this->schemaUtils->getModelSchema($modelName, $this->getModel());
}
// enabled methods for CorsListener
$corsMethods = 'GET, POST, PUT, PATCH, DELETE, OPTIONS';
try {
$router = $this->getRouter();
// if post route is available we assume everything is readable
$router->generate(implode('.', array($app, $module, 'rest', $modelName, 'post')));
} catch (RouteNotFoundException $exception) {
// only allow read methods
$corsMethods = 'GET, OPTIONS';
}
$request->attributes->set('corsMethods', $corsMethods);
$response->setContent($this->restUtils->serialize($schema));
return $response;
}
|
[
"public",
"function",
"schemaAction",
"(",
"Request",
"$",
"request",
",",
"$",
"id",
"=",
"null",
")",
"{",
"$",
"request",
"->",
"attributes",
"->",
"set",
"(",
"'schemaRequest'",
",",
"true",
")",
";",
"list",
"(",
"$",
"app",
",",
"$",
"module",
",",
",",
"$",
"modelName",
",",
"$",
"schemaType",
")",
"=",
"explode",
"(",
"'.'",
",",
"$",
"request",
"->",
"attributes",
"->",
"get",
"(",
"'_route'",
")",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"response",
";",
"$",
"response",
"->",
"setStatusCode",
"(",
"Response",
"::",
"HTTP_OK",
")",
";",
"$",
"response",
"->",
"setVary",
"(",
"[",
"'Origin'",
",",
"'Accept-Encoding'",
"]",
")",
";",
"$",
"response",
"->",
"setPublic",
"(",
")",
";",
"if",
"(",
"!",
"$",
"id",
"&&",
"$",
"schemaType",
"!=",
"'canonicalIdSchema'",
")",
"{",
"$",
"schema",
"=",
"$",
"this",
"->",
"schemaUtils",
"->",
"getCollectionSchema",
"(",
"$",
"modelName",
",",
"$",
"this",
"->",
"getModel",
"(",
")",
")",
";",
"}",
"else",
"{",
"$",
"schema",
"=",
"$",
"this",
"->",
"schemaUtils",
"->",
"getModelSchema",
"(",
"$",
"modelName",
",",
"$",
"this",
"->",
"getModel",
"(",
")",
")",
";",
"}",
"// enabled methods for CorsListener",
"$",
"corsMethods",
"=",
"'GET, POST, PUT, PATCH, DELETE, OPTIONS'",
";",
"try",
"{",
"$",
"router",
"=",
"$",
"this",
"->",
"getRouter",
"(",
")",
";",
"// if post route is available we assume everything is readable",
"$",
"router",
"->",
"generate",
"(",
"implode",
"(",
"'.'",
",",
"array",
"(",
"$",
"app",
",",
"$",
"module",
",",
"'rest'",
",",
"$",
"modelName",
",",
"'post'",
")",
")",
")",
";",
"}",
"catch",
"(",
"RouteNotFoundException",
"$",
"exception",
")",
"{",
"// only allow read methods",
"$",
"corsMethods",
"=",
"'GET, OPTIONS'",
";",
"}",
"$",
"request",
"->",
"attributes",
"->",
"set",
"(",
"'corsMethods'",
",",
"$",
"corsMethods",
")",
";",
"$",
"response",
"->",
"setContent",
"(",
"$",
"this",
"->",
"restUtils",
"->",
"serialize",
"(",
"$",
"schema",
")",
")",
";",
"return",
"$",
"response",
";",
"}"
] |
Return schema GET results.
@param Request $request Current http request
@param string $id ID of record
@throws SerializationException
@return \Symfony\Component\HttpFoundation\Response $response Result of the action
|
[
"Return",
"schema",
"GET",
"results",
"."
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Controller/RestController.php#L406-L438
|
26,471
|
libgraviton/graviton
|
src/Graviton/RestBundle/DependencyInjection/Compiler/RqlQueryRoutesCompilerPass.php
|
RqlQueryRoutesCompilerPass.process
|
public function process(ContainerBuilder $container)
{
$routes = [];
foreach ($container->getParameter('graviton.rest.services') as $service => $params) {
list($app, $bundle, , $entity) = explode('.', $service);
$routes[] = implode('.', [$app, $bundle, 'rest', $entity, 'all']);
$routes[] = implode('.', [$app, $bundle, 'rest', $entity, 'get']);
}
$container->setParameter('graviton.rest.listener.rqlqueryrequestlistener.allowedroutes', $routes);
}
|
php
|
public function process(ContainerBuilder $container)
{
$routes = [];
foreach ($container->getParameter('graviton.rest.services') as $service => $params) {
list($app, $bundle, , $entity) = explode('.', $service);
$routes[] = implode('.', [$app, $bundle, 'rest', $entity, 'all']);
$routes[] = implode('.', [$app, $bundle, 'rest', $entity, 'get']);
}
$container->setParameter('graviton.rest.listener.rqlqueryrequestlistener.allowedroutes', $routes);
}
|
[
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"routes",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"container",
"->",
"getParameter",
"(",
"'graviton.rest.services'",
")",
"as",
"$",
"service",
"=>",
"$",
"params",
")",
"{",
"list",
"(",
"$",
"app",
",",
"$",
"bundle",
",",
",",
"$",
"entity",
")",
"=",
"explode",
"(",
"'.'",
",",
"$",
"service",
")",
";",
"$",
"routes",
"[",
"]",
"=",
"implode",
"(",
"'.'",
",",
"[",
"$",
"app",
",",
"$",
"bundle",
",",
"'rest'",
",",
"$",
"entity",
",",
"'all'",
"]",
")",
";",
"$",
"routes",
"[",
"]",
"=",
"implode",
"(",
"'.'",
",",
"[",
"$",
"app",
",",
"$",
"bundle",
",",
"'rest'",
",",
"$",
"entity",
",",
"'get'",
"]",
")",
";",
"}",
"$",
"container",
"->",
"setParameter",
"(",
"'graviton.rest.listener.rqlqueryrequestlistener.allowedroutes'",
",",
"$",
"routes",
")",
";",
"}"
] |
Find "allAction" routes and set it to allowed routes for RQL parsing
@param ContainerBuilder $container Container builder
@return void
|
[
"Find",
"allAction",
"routes",
"and",
"set",
"it",
"to",
"allowed",
"routes",
"for",
"RQL",
"parsing"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/DependencyInjection/Compiler/RqlQueryRoutesCompilerPass.php#L24-L34
|
26,472
|
libgraviton/graviton
|
src/Graviton/AnalyticsBundle/Listener/HomepageRenderListener.php
|
HomepageRenderListener.onRender
|
public function onRender(HomepageRenderEvent $event)
{
$services = $this->serviceManager->getServices();
foreach ($services as $service) {
$event->addRoute($service['$ref'], $service['profile']);
}
}
|
php
|
public function onRender(HomepageRenderEvent $event)
{
$services = $this->serviceManager->getServices();
foreach ($services as $service) {
$event->addRoute($service['$ref'], $service['profile']);
}
}
|
[
"public",
"function",
"onRender",
"(",
"HomepageRenderEvent",
"$",
"event",
")",
"{",
"$",
"services",
"=",
"$",
"this",
"->",
"serviceManager",
"->",
"getServices",
"(",
")",
";",
"foreach",
"(",
"$",
"services",
"as",
"$",
"service",
")",
"{",
"$",
"event",
"->",
"addRoute",
"(",
"$",
"service",
"[",
"'$ref'",
"]",
",",
"$",
"service",
"[",
"'profile'",
"]",
")",
";",
"}",
"}"
] |
Add our links to the homepage
@param HomepageRenderEvent $event event
@return void
|
[
"Add",
"our",
"links",
"to",
"the",
"homepage"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/AnalyticsBundle/Listener/HomepageRenderListener.php#L42-L48
|
26,473
|
libgraviton/graviton
|
src/Graviton/CoreBundle/Controller/FaviconController.php
|
FaviconController.iconAction
|
public function iconAction()
{
header('Content-Type: image/x-icon');
// open our file
$fp = fopen(__DIR__.'/../Resources/assets/favicon.ico', 'r');
fpassthru($fp);
fclose($fp);
exit;
}
|
php
|
public function iconAction()
{
header('Content-Type: image/x-icon');
// open our file
$fp = fopen(__DIR__.'/../Resources/assets/favicon.ico', 'r');
fpassthru($fp);
fclose($fp);
exit;
}
|
[
"public",
"function",
"iconAction",
"(",
")",
"{",
"header",
"(",
"'Content-Type: image/x-icon'",
")",
";",
"// open our file",
"$",
"fp",
"=",
"fopen",
"(",
"__DIR__",
".",
"'/../Resources/assets/favicon.ico'",
",",
"'r'",
")",
";",
"fpassthru",
"(",
"$",
"fp",
")",
";",
"fclose",
"(",
"$",
"fp",
")",
";",
"exit",
";",
"}"
] |
renders a favicon
@return \Symfony\Component\HttpFoundation\Response $response Response with result or error
|
[
"renders",
"a",
"favicon"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Controller/FaviconController.php#L21-L29
|
26,474
|
libgraviton/graviton
|
src/Graviton/RestBundle/Listener/XVersionResponseListener.php
|
XVersionResponseListener.onKernelResponse
|
public function onKernelResponse(FilterResponseEvent $event)
{
if (!$event->isMasterRequest()) {
// don't do anything if it's not the master request
return;
}
$event->getResponse()->headers->set(
'X-Version',
$this->versionHeader
);
}
|
php
|
public function onKernelResponse(FilterResponseEvent $event)
{
if (!$event->isMasterRequest()) {
// don't do anything if it's not the master request
return;
}
$event->getResponse()->headers->set(
'X-Version',
$this->versionHeader
);
}
|
[
"public",
"function",
"onKernelResponse",
"(",
"FilterResponseEvent",
"$",
"event",
")",
"{",
"if",
"(",
"!",
"$",
"event",
"->",
"isMasterRequest",
"(",
")",
")",
"{",
"// don't do anything if it's not the master request",
"return",
";",
"}",
"$",
"event",
"->",
"getResponse",
"(",
")",
"->",
"headers",
"->",
"set",
"(",
"'X-Version'",
",",
"$",
"this",
"->",
"versionHeader",
")",
";",
"}"
] |
Adds a X-Version header to the response.
@param FilterResponseEvent $event Current emitted event.
@return void
|
[
"Adds",
"a",
"X",
"-",
"Version",
"header",
"to",
"the",
"response",
"."
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RestBundle/Listener/XVersionResponseListener.php#L40-L51
|
26,475
|
libgraviton/graviton
|
src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/ArrayField.php
|
ArrayField.getItemType
|
public function getItemType()
{
if (!preg_match('/array\<(.+)\>/i', $this->serializerType, $matches)) {
return $this->serializerType;
}
$map = [
'DateTime' => 'date',
'integer' => 'int',
'float' => 'float',
'double' => 'float',
'boolean' => 'boolean',
'extref' => 'extref',
];
return isset($map[$matches[1]]) ? $map[$matches[1]] : $matches[1];
}
|
php
|
public function getItemType()
{
if (!preg_match('/array\<(.+)\>/i', $this->serializerType, $matches)) {
return $this->serializerType;
}
$map = [
'DateTime' => 'date',
'integer' => 'int',
'float' => 'float',
'double' => 'float',
'boolean' => 'boolean',
'extref' => 'extref',
];
return isset($map[$matches[1]]) ? $map[$matches[1]] : $matches[1];
}
|
[
"public",
"function",
"getItemType",
"(",
")",
"{",
"if",
"(",
"!",
"preg_match",
"(",
"'/array\\<(.+)\\>/i'",
",",
"$",
"this",
"->",
"serializerType",
",",
"$",
"matches",
")",
")",
"{",
"return",
"$",
"this",
"->",
"serializerType",
";",
"}",
"$",
"map",
"=",
"[",
"'DateTime'",
"=>",
"'date'",
",",
"'integer'",
"=>",
"'int'",
",",
"'float'",
"=>",
"'float'",
",",
"'double'",
"=>",
"'float'",
",",
"'boolean'",
"=>",
"'boolean'",
",",
"'extref'",
"=>",
"'extref'",
",",
"]",
";",
"return",
"isset",
"(",
"$",
"map",
"[",
"$",
"matches",
"[",
"1",
"]",
"]",
")",
"?",
"$",
"map",
"[",
"$",
"matches",
"[",
"1",
"]",
"]",
":",
"$",
"matches",
"[",
"1",
"]",
";",
"}"
] |
Get item type
@return string
|
[
"Get",
"item",
"type"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/ArrayField.php#L59-L74
|
26,476
|
libgraviton/graviton
|
src/Graviton/SchemaBundle/Constraint/VersionServiceConstraint.php
|
VersionServiceConstraint.isVersioningService
|
public function isVersioningService()
{
$schema = $this->utils->getCurrentSchema();
if (isset($schema->{'x-versioning'}) && $schema->{'x-versioning'} === true) {
return true;
}
return false;
}
|
php
|
public function isVersioningService()
{
$schema = $this->utils->getCurrentSchema();
if (isset($schema->{'x-versioning'}) && $schema->{'x-versioning'} === true) {
return true;
}
return false;
}
|
[
"public",
"function",
"isVersioningService",
"(",
")",
"{",
"$",
"schema",
"=",
"$",
"this",
"->",
"utils",
"->",
"getCurrentSchema",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"schema",
"->",
"{",
"'x-versioning'",
"}",
")",
"&&",
"$",
"schema",
"->",
"{",
"'x-versioning'",
"}",
"===",
"true",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
tells whether the current service has versioning activated or not
@return bool true if yes, false otherwise
|
[
"tells",
"whether",
"the",
"current",
"service",
"has",
"versioning",
"activated",
"or",
"not"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/VersionServiceConstraint.php#L85-L92
|
26,477
|
libgraviton/graviton
|
src/Graviton/SchemaBundle/Constraint/VersionServiceConstraint.php
|
VersionServiceConstraint.getVersionFromObject
|
private function getVersionFromObject($object)
{
$version = null;
if ($this->accessor->isReadable($object, self::FIELD_NAME)) {
$version = $this->accessor->getValue($object, self::FIELD_NAME);
}
return $version;
}
|
php
|
private function getVersionFromObject($object)
{
$version = null;
if ($this->accessor->isReadable($object, self::FIELD_NAME)) {
$version = $this->accessor->getValue($object, self::FIELD_NAME);
}
return $version;
}
|
[
"private",
"function",
"getVersionFromObject",
"(",
"$",
"object",
")",
"{",
"$",
"version",
"=",
"null",
";",
"if",
"(",
"$",
"this",
"->",
"accessor",
"->",
"isReadable",
"(",
"$",
"object",
",",
"self",
"::",
"FIELD_NAME",
")",
")",
"{",
"$",
"version",
"=",
"$",
"this",
"->",
"accessor",
"->",
"getValue",
"(",
"$",
"object",
",",
"self",
"::",
"FIELD_NAME",
")",
";",
"}",
"return",
"$",
"version",
";",
"}"
] |
returns the version from a given object
@param object $object object
@return int|null null or the specified version
|
[
"returns",
"the",
"version",
"from",
"a",
"given",
"object"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/VersionServiceConstraint.php#L101-L109
|
26,478
|
libgraviton/graviton
|
src/Graviton/SchemaBundle/Constraint/VersionServiceConstraint.php
|
VersionServiceConstraint.getUserVersion
|
private function getUserVersion($object)
{
if ($this->utils->getCurrentRequestMethod() == 'PATCH') {
$content = json_decode($this->utils->getCurrentRequestContent(), true);
$hasVersion = array_filter(
$content,
function ($val) {
if ($val['path'] == '/'.self::FIELD_NAME) {
return true;
}
return false;
}
);
if (empty($hasVersion)) {
return -1;
}
}
return $this->getVersionFromObject($object);
}
|
php
|
private function getUserVersion($object)
{
if ($this->utils->getCurrentRequestMethod() == 'PATCH') {
$content = json_decode($this->utils->getCurrentRequestContent(), true);
$hasVersion = array_filter(
$content,
function ($val) {
if ($val['path'] == '/'.self::FIELD_NAME) {
return true;
}
return false;
}
);
if (empty($hasVersion)) {
return -1;
}
}
return $this->getVersionFromObject($object);
}
|
[
"private",
"function",
"getUserVersion",
"(",
"$",
"object",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"utils",
"->",
"getCurrentRequestMethod",
"(",
")",
"==",
"'PATCH'",
")",
"{",
"$",
"content",
"=",
"json_decode",
"(",
"$",
"this",
"->",
"utils",
"->",
"getCurrentRequestContent",
"(",
")",
",",
"true",
")",
";",
"$",
"hasVersion",
"=",
"array_filter",
"(",
"$",
"content",
",",
"function",
"(",
"$",
"val",
")",
"{",
"if",
"(",
"$",
"val",
"[",
"'path'",
"]",
"==",
"'/'",
".",
"self",
"::",
"FIELD_NAME",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"hasVersion",
")",
")",
"{",
"return",
"-",
"1",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"getVersionFromObject",
"(",
"$",
"object",
")",
";",
"}"
] |
Gets the user provided version, handling different scenarios
@param object $object object
@return int|null null or the specified version
|
[
"Gets",
"the",
"user",
"provided",
"version",
"handling",
"different",
"scenarios"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/VersionServiceConstraint.php#L118-L139
|
26,479
|
libgraviton/graviton
|
src/Graviton/SchemaBundle/Constraint/VersionServiceConstraint.php
|
VersionServiceConstraint.setCurrentVersionHeader
|
public function setCurrentVersionHeader(FilterResponseEvent $event)
{
if ($this->version) {
$event->getResponse()->headers->set(self::HEADER_NAME, $this->version);
}
}
|
php
|
public function setCurrentVersionHeader(FilterResponseEvent $event)
{
if ($this->version) {
$event->getResponse()->headers->set(self::HEADER_NAME, $this->version);
}
}
|
[
"public",
"function",
"setCurrentVersionHeader",
"(",
"FilterResponseEvent",
"$",
"event",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"version",
")",
"{",
"$",
"event",
"->",
"getResponse",
"(",
")",
"->",
"headers",
"->",
"set",
"(",
"self",
"::",
"HEADER_NAME",
",",
"$",
"this",
"->",
"version",
")",
";",
"}",
"}"
] |
Setting if needed the headers to let user know what was the new version.
@param FilterResponseEvent $event SF response event
@return void
|
[
"Setting",
"if",
"needed",
"the",
"headers",
"to",
"let",
"user",
"know",
"what",
"was",
"the",
"new",
"version",
"."
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/VersionServiceConstraint.php#L147-L152
|
26,480
|
libgraviton/graviton
|
src/Graviton/SchemaBundle/Constraint/ConstraintBuilder.php
|
ConstraintBuilder.addConstraints
|
public function addConstraints($fieldName, Schema $property, DocumentModel $model)
{
$constraints = $model->getConstraints($fieldName);
if (!is_array($constraints)) {
return $property;
}
foreach ($constraints as $constraint) {
$isSupported = false;
foreach ($this->builders as $builder) {
if ($builder->supportsConstraint($constraint->name, $constraint->options)) {
$property = $builder->buildConstraint($fieldName, $property, $model, $constraint->options);
$isSupported = true;
}
}
if (!$isSupported) {
/**
* unknown/not supported constraints will be added to the 'x-constraints' schema property.
* this allows others (possibly schema constraints) to pick it up and implement more advanced logic.
*/
$property->addConstraint($constraint->name);
}
}
return $property;
}
|
php
|
public function addConstraints($fieldName, Schema $property, DocumentModel $model)
{
$constraints = $model->getConstraints($fieldName);
if (!is_array($constraints)) {
return $property;
}
foreach ($constraints as $constraint) {
$isSupported = false;
foreach ($this->builders as $builder) {
if ($builder->supportsConstraint($constraint->name, $constraint->options)) {
$property = $builder->buildConstraint($fieldName, $property, $model, $constraint->options);
$isSupported = true;
}
}
if (!$isSupported) {
/**
* unknown/not supported constraints will be added to the 'x-constraints' schema property.
* this allows others (possibly schema constraints) to pick it up and implement more advanced logic.
*/
$property->addConstraint($constraint->name);
}
}
return $property;
}
|
[
"public",
"function",
"addConstraints",
"(",
"$",
"fieldName",
",",
"Schema",
"$",
"property",
",",
"DocumentModel",
"$",
"model",
")",
"{",
"$",
"constraints",
"=",
"$",
"model",
"->",
"getConstraints",
"(",
"$",
"fieldName",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"constraints",
")",
")",
"{",
"return",
"$",
"property",
";",
"}",
"foreach",
"(",
"$",
"constraints",
"as",
"$",
"constraint",
")",
"{",
"$",
"isSupported",
"=",
"false",
";",
"foreach",
"(",
"$",
"this",
"->",
"builders",
"as",
"$",
"builder",
")",
"{",
"if",
"(",
"$",
"builder",
"->",
"supportsConstraint",
"(",
"$",
"constraint",
"->",
"name",
",",
"$",
"constraint",
"->",
"options",
")",
")",
"{",
"$",
"property",
"=",
"$",
"builder",
"->",
"buildConstraint",
"(",
"$",
"fieldName",
",",
"$",
"property",
",",
"$",
"model",
",",
"$",
"constraint",
"->",
"options",
")",
";",
"$",
"isSupported",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"!",
"$",
"isSupported",
")",
"{",
"/**\n * unknown/not supported constraints will be added to the 'x-constraints' schema property.\n * this allows others (possibly schema constraints) to pick it up and implement more advanced logic.\n */",
"$",
"property",
"->",
"addConstraint",
"(",
"$",
"constraint",
"->",
"name",
")",
";",
"}",
"}",
"return",
"$",
"property",
";",
"}"
] |
Go through the constraints and call the builders to do their job
@param string $fieldName field name
@param Schema $property the property
@param DocumentModel $model the parent model
@return Schema
|
[
"Go",
"through",
"the",
"constraints",
"and",
"call",
"the",
"builders",
"to",
"do",
"their",
"job"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SchemaBundle/Constraint/ConstraintBuilder.php#L45-L72
|
26,481
|
konduto/php-sdk
|
src/Models/Payment.php
|
Payment.build
|
public static function build(array $array) {
if (array_key_exists("type", $array) && in_array($array["type"], self::$availableTypes)) {
switch ($array["type"]) {
case Payment::TYPE_CREDIT:
return new CreditCard($array);
break;
case Payment::TYPE_BOLETO:
return new Boleto($array);
break;
case Payment::TYPE_DEBIT:
case Payment::TYPE_TRANSFER:
case Payment::TYPE_VOUCHER:
return new Payment($array);
break;
default: // Exception
}
}
throw new \InvalidArgumentException("Array must contain a valid 'type' field");
}
|
php
|
public static function build(array $array) {
if (array_key_exists("type", $array) && in_array($array["type"], self::$availableTypes)) {
switch ($array["type"]) {
case Payment::TYPE_CREDIT:
return new CreditCard($array);
break;
case Payment::TYPE_BOLETO:
return new Boleto($array);
break;
case Payment::TYPE_DEBIT:
case Payment::TYPE_TRANSFER:
case Payment::TYPE_VOUCHER:
return new Payment($array);
break;
default: // Exception
}
}
throw new \InvalidArgumentException("Array must contain a valid 'type' field");
}
|
[
"public",
"static",
"function",
"build",
"(",
"array",
"$",
"array",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"\"type\"",
",",
"$",
"array",
")",
"&&",
"in_array",
"(",
"$",
"array",
"[",
"\"type\"",
"]",
",",
"self",
"::",
"$",
"availableTypes",
")",
")",
"{",
"switch",
"(",
"$",
"array",
"[",
"\"type\"",
"]",
")",
"{",
"case",
"Payment",
"::",
"TYPE_CREDIT",
":",
"return",
"new",
"CreditCard",
"(",
"$",
"array",
")",
";",
"break",
";",
"case",
"Payment",
"::",
"TYPE_BOLETO",
":",
"return",
"new",
"Boleto",
"(",
"$",
"array",
")",
";",
"break",
";",
"case",
"Payment",
"::",
"TYPE_DEBIT",
":",
"case",
"Payment",
"::",
"TYPE_TRANSFER",
":",
"case",
"Payment",
"::",
"TYPE_VOUCHER",
":",
"return",
"new",
"Payment",
"(",
"$",
"array",
")",
";",
"break",
";",
"default",
":",
"// Exception",
"}",
"}",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Array must contain a valid 'type' field\"",
")",
";",
"}"
] |
Given an array, instantiates a payment among the possible
types of payments. The decision of what Model to use is made
by field 'type'
@param $array: array containing fields of the Payment
@return Payment CreditCard or Boleto object
|
[
"Given",
"an",
"array",
"instantiates",
"a",
"payment",
"among",
"the",
"possible",
"types",
"of",
"payments",
".",
"The",
"decision",
"of",
"what",
"Model",
"to",
"use",
"is",
"made",
"by",
"field",
"type"
] |
ff095590c30307897c557f980845f613ff351585
|
https://github.com/konduto/php-sdk/blob/ff095590c30307897c557f980845f613ff351585/src/Models/Payment.php#L32-L53
|
26,482
|
libgraviton/graviton
|
src/Graviton/RabbitMqBundle/Service/DumpConsumer.php
|
DumpConsumer.execute
|
public function execute(AMQPMessage $msg)
{
echo str_repeat('-', 60).PHP_EOL;
echo '[RECV ' . date('c') . ']' . PHP_EOL .'<content>' .
PHP_EOL . $msg->body . PHP_EOL . '</content>'.PHP_EOL.PHP_EOL;
echo "*" . ' INFO ' . PHP_EOL;
foreach ($msg->{'delivery_info'} as $key => $value) {
if (is_scalar($value)) {
echo "** " . $key . ' = ' . $value . PHP_EOL;
}
}
echo "*" . ' PROPERTIES ' . PHP_EOL;
foreach ($msg->get_properties() as $property => $value) {
if (is_scalar($value)) {
echo "** " . $property . ' = ' . $value . PHP_EOL;
}
}
}
|
php
|
public function execute(AMQPMessage $msg)
{
echo str_repeat('-', 60).PHP_EOL;
echo '[RECV ' . date('c') . ']' . PHP_EOL .'<content>' .
PHP_EOL . $msg->body . PHP_EOL . '</content>'.PHP_EOL.PHP_EOL;
echo "*" . ' INFO ' . PHP_EOL;
foreach ($msg->{'delivery_info'} as $key => $value) {
if (is_scalar($value)) {
echo "** " . $key . ' = ' . $value . PHP_EOL;
}
}
echo "*" . ' PROPERTIES ' . PHP_EOL;
foreach ($msg->get_properties() as $property => $value) {
if (is_scalar($value)) {
echo "** " . $property . ' = ' . $value . PHP_EOL;
}
}
}
|
[
"public",
"function",
"execute",
"(",
"AMQPMessage",
"$",
"msg",
")",
"{",
"echo",
"str_repeat",
"(",
"'-'",
",",
"60",
")",
".",
"PHP_EOL",
";",
"echo",
"'[RECV '",
".",
"date",
"(",
"'c'",
")",
".",
"']'",
".",
"PHP_EOL",
".",
"'<content>'",
".",
"PHP_EOL",
".",
"$",
"msg",
"->",
"body",
".",
"PHP_EOL",
".",
"'</content>'",
".",
"PHP_EOL",
".",
"PHP_EOL",
";",
"echo",
"\"*\"",
".",
"' INFO '",
".",
"PHP_EOL",
";",
"foreach",
"(",
"$",
"msg",
"->",
"{",
"'delivery_info'",
"}",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"is_scalar",
"(",
"$",
"value",
")",
")",
"{",
"echo",
"\"** \"",
".",
"$",
"key",
".",
"' = '",
".",
"$",
"value",
".",
"PHP_EOL",
";",
"}",
"}",
"echo",
"\"*\"",
".",
"' PROPERTIES '",
".",
"PHP_EOL",
";",
"foreach",
"(",
"$",
"msg",
"->",
"get_properties",
"(",
")",
"as",
"$",
"property",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"is_scalar",
"(",
"$",
"value",
")",
")",
"{",
"echo",
"\"** \"",
".",
"$",
"property",
".",
"' = '",
".",
"$",
"value",
".",
"PHP_EOL",
";",
"}",
"}",
"}"
] |
Callback executed when a message is received. Dumps the message body, delivery_info and properties.
@param AMQPMessage $msg The received message.
@return void
|
[
"Callback",
"executed",
"when",
"a",
"message",
"is",
"received",
".",
"Dumps",
"the",
"message",
"body",
"delivery_info",
"and",
"properties",
"."
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/RabbitMqBundle/Service/DumpConsumer.php#L29-L48
|
26,483
|
konduto/php-sdk
|
src/Models/Travel.php
|
Travel.build
|
public static function build(array $args) {
if (is_array($args) && array_key_exists("type", $args)) {
switch ($args["type"]) {
case Travel::TYPE_BUS:
return new BusTravel($args);
case Travel::TYPE_FLIGHT:
return new Flight($args);
}
}
throw new \InvalidArgumentException("Array must contain a valid 'type' field");
}
|
php
|
public static function build(array $args) {
if (is_array($args) && array_key_exists("type", $args)) {
switch ($args["type"]) {
case Travel::TYPE_BUS:
return new BusTravel($args);
case Travel::TYPE_FLIGHT:
return new Flight($args);
}
}
throw new \InvalidArgumentException("Array must contain a valid 'type' field");
}
|
[
"public",
"static",
"function",
"build",
"(",
"array",
"$",
"args",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"args",
")",
"&&",
"array_key_exists",
"(",
"\"type\"",
",",
"$",
"args",
")",
")",
"{",
"switch",
"(",
"$",
"args",
"[",
"\"type\"",
"]",
")",
"{",
"case",
"Travel",
"::",
"TYPE_BUS",
":",
"return",
"new",
"BusTravel",
"(",
"$",
"args",
")",
";",
"case",
"Travel",
"::",
"TYPE_FLIGHT",
":",
"return",
"new",
"Flight",
"(",
"$",
"args",
")",
";",
"}",
"}",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Array must contain a valid 'type' field\"",
")",
";",
"}"
] |
Given an array, instantiates a travel among the possible
types of travel. The decision of what Model to use is made
by the field 'type'
@param array $args: array containing fields of the Travel
@return Travel BusTravel or Flight object
|
[
"Given",
"an",
"array",
"instantiates",
"a",
"travel",
"among",
"the",
"possible",
"types",
"of",
"travel",
".",
"The",
"decision",
"of",
"what",
"Model",
"to",
"use",
"is",
"made",
"by",
"the",
"field",
"type"
] |
ff095590c30307897c557f980845f613ff351585
|
https://github.com/konduto/php-sdk/blob/ff095590c30307897c557f980845f613ff351585/src/Models/Travel.php#L35-L45
|
26,484
|
libgraviton/graviton
|
src/Graviton/SecurityBundle/Controller/WhoAmIController.php
|
WhoAmIController.whoAmIAction
|
public function whoAmIAction()
{
/** @var SecurityUser $securityUser */
$securityUser = $this->getSecurityUser();
/** @var Response $response */
$response = $this->getResponse();
$response->headers->set('Content-Type', 'application/json');
if (!$securityUser) {
$response->setContent(json_encode(['Security is not enabled']));
$response->setStatusCode(Response::HTTP_METHOD_NOT_ALLOWED);
return $response;
}
$response->setContent($this->restUtils->serialize($securityUser->getUser()));
$response->setStatusCode(Response::HTTP_OK);
return $response;
}
|
php
|
public function whoAmIAction()
{
/** @var SecurityUser $securityUser */
$securityUser = $this->getSecurityUser();
/** @var Response $response */
$response = $this->getResponse();
$response->headers->set('Content-Type', 'application/json');
if (!$securityUser) {
$response->setContent(json_encode(['Security is not enabled']));
$response->setStatusCode(Response::HTTP_METHOD_NOT_ALLOWED);
return $response;
}
$response->setContent($this->restUtils->serialize($securityUser->getUser()));
$response->setStatusCode(Response::HTTP_OK);
return $response;
}
|
[
"public",
"function",
"whoAmIAction",
"(",
")",
"{",
"/** @var SecurityUser $securityUser */",
"$",
"securityUser",
"=",
"$",
"this",
"->",
"getSecurityUser",
"(",
")",
";",
"/** @var Response $response */",
"$",
"response",
"=",
"$",
"this",
"->",
"getResponse",
"(",
")",
";",
"$",
"response",
"->",
"headers",
"->",
"set",
"(",
"'Content-Type'",
",",
"'application/json'",
")",
";",
"if",
"(",
"!",
"$",
"securityUser",
")",
"{",
"$",
"response",
"->",
"setContent",
"(",
"json_encode",
"(",
"[",
"'Security is not enabled'",
"]",
")",
")",
";",
"$",
"response",
"->",
"setStatusCode",
"(",
"Response",
"::",
"HTTP_METHOD_NOT_ALLOWED",
")",
";",
"return",
"$",
"response",
";",
"}",
"$",
"response",
"->",
"setContent",
"(",
"$",
"this",
"->",
"restUtils",
"->",
"serialize",
"(",
"$",
"securityUser",
"->",
"getUser",
"(",
")",
")",
")",
";",
"$",
"response",
"->",
"setStatusCode",
"(",
"Response",
"::",
"HTTP_OK",
")",
";",
"return",
"$",
"response",
";",
"}"
] |
Currently authenticated user information.
If security is not enabled then header will be Not Allowed.
If User not found using correct header Anonymous user
Serialised Object transformer
@return Response $response Response with result or error
|
[
"Currently",
"authenticated",
"user",
"information",
".",
"If",
"security",
"is",
"not",
"enabled",
"then",
"header",
"will",
"be",
"Not",
"Allowed",
".",
"If",
"User",
"not",
"found",
"using",
"correct",
"header",
"Anonymous",
"user",
"Serialised",
"Object",
"transformer"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/SecurityBundle/Controller/WhoAmIController.php#L28-L47
|
26,485
|
libgraviton/graviton
|
src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php
|
GenerateDynamicBundleCommand.getExistingBundleHashes
|
private function getExistingBundleHashes($baseDir)
{
$existingBundles = [];
$fs = new Filesystem();
$bundleBaseDir = $baseDir.self::BUNDLE_NAMESPACE;
if (!$fs->exists($bundleBaseDir)) {
return $existingBundles;
}
$bundleFinder = $this->getBundleFinder($baseDir);
foreach ($bundleFinder as $bundleDir) {
$genHash = '';
$hashFileFinder = new Finder();
$hashFileIterator = $hashFileFinder
->files()
->in($bundleDir->getPathname())
->name(self::GENERATION_HASHFILE_FILENAME)
->depth('== 0')
->getIterator();
$hashFileIterator->rewind();
$hashFile = $hashFileIterator->current();
if ($hashFile instanceof SplFileInfo) {
$genHash = $hashFile->getContents();
}
$existingBundles[$bundleDir->getPathname()] = $genHash;
}
return $existingBundles;
}
|
php
|
private function getExistingBundleHashes($baseDir)
{
$existingBundles = [];
$fs = new Filesystem();
$bundleBaseDir = $baseDir.self::BUNDLE_NAMESPACE;
if (!$fs->exists($bundleBaseDir)) {
return $existingBundles;
}
$bundleFinder = $this->getBundleFinder($baseDir);
foreach ($bundleFinder as $bundleDir) {
$genHash = '';
$hashFileFinder = new Finder();
$hashFileIterator = $hashFileFinder
->files()
->in($bundleDir->getPathname())
->name(self::GENERATION_HASHFILE_FILENAME)
->depth('== 0')
->getIterator();
$hashFileIterator->rewind();
$hashFile = $hashFileIterator->current();
if ($hashFile instanceof SplFileInfo) {
$genHash = $hashFile->getContents();
}
$existingBundles[$bundleDir->getPathname()] = $genHash;
}
return $existingBundles;
}
|
[
"private",
"function",
"getExistingBundleHashes",
"(",
"$",
"baseDir",
")",
"{",
"$",
"existingBundles",
"=",
"[",
"]",
";",
"$",
"fs",
"=",
"new",
"Filesystem",
"(",
")",
";",
"$",
"bundleBaseDir",
"=",
"$",
"baseDir",
".",
"self",
"::",
"BUNDLE_NAMESPACE",
";",
"if",
"(",
"!",
"$",
"fs",
"->",
"exists",
"(",
"$",
"bundleBaseDir",
")",
")",
"{",
"return",
"$",
"existingBundles",
";",
"}",
"$",
"bundleFinder",
"=",
"$",
"this",
"->",
"getBundleFinder",
"(",
"$",
"baseDir",
")",
";",
"foreach",
"(",
"$",
"bundleFinder",
"as",
"$",
"bundleDir",
")",
"{",
"$",
"genHash",
"=",
"''",
";",
"$",
"hashFileFinder",
"=",
"new",
"Finder",
"(",
")",
";",
"$",
"hashFileIterator",
"=",
"$",
"hashFileFinder",
"->",
"files",
"(",
")",
"->",
"in",
"(",
"$",
"bundleDir",
"->",
"getPathname",
"(",
")",
")",
"->",
"name",
"(",
"self",
"::",
"GENERATION_HASHFILE_FILENAME",
")",
"->",
"depth",
"(",
"'== 0'",
")",
"->",
"getIterator",
"(",
")",
";",
"$",
"hashFileIterator",
"->",
"rewind",
"(",
")",
";",
"$",
"hashFile",
"=",
"$",
"hashFileIterator",
"->",
"current",
"(",
")",
";",
"if",
"(",
"$",
"hashFile",
"instanceof",
"SplFileInfo",
")",
"{",
"$",
"genHash",
"=",
"$",
"hashFile",
"->",
"getContents",
"(",
")",
";",
"}",
"$",
"existingBundles",
"[",
"$",
"bundleDir",
"->",
"getPathname",
"(",
")",
"]",
"=",
"$",
"genHash",
";",
"}",
"return",
"$",
"existingBundles",
";",
"}"
] |
scans through all existing dynamic bundles, checks if there is a generation hash and collect that
all in an array that can be used for fast checking.
@param string $baseDir base directory of dynamic bundles
@return array key is bundlepath, value is the current hash
|
[
"scans",
"through",
"all",
"existing",
"dynamic",
"bundles",
"checks",
"if",
"there",
"is",
"a",
"generation",
"hash",
"and",
"collect",
"that",
"all",
"in",
"an",
"array",
"that",
"can",
"be",
"used",
"for",
"fast",
"checking",
"."
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L290-L323
|
26,486
|
libgraviton/graviton
|
src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php
|
GenerateDynamicBundleCommand.getBundleClassnameFromFolder
|
private function getBundleClassnameFromFolder($folderName)
{
if (substr($folderName, -6) == 'Bundle') {
$folderName = substr($folderName, 0, -6);
}
return sprintf(self::BUNDLE_NAME_MASK, $folderName);
}
|
php
|
private function getBundleClassnameFromFolder($folderName)
{
if (substr($folderName, -6) == 'Bundle') {
$folderName = substr($folderName, 0, -6);
}
return sprintf(self::BUNDLE_NAME_MASK, $folderName);
}
|
[
"private",
"function",
"getBundleClassnameFromFolder",
"(",
"$",
"folderName",
")",
"{",
"if",
"(",
"substr",
"(",
"$",
"folderName",
",",
"-",
"6",
")",
"==",
"'Bundle'",
")",
"{",
"$",
"folderName",
"=",
"substr",
"(",
"$",
"folderName",
",",
"0",
",",
"-",
"6",
")",
";",
"}",
"return",
"sprintf",
"(",
"self",
"::",
"BUNDLE_NAME_MASK",
",",
"$",
"folderName",
")",
";",
"}"
] |
from a name of a folder of a bundle, this function returns the corresponding class name
@param string $folderName folder name
@return string
|
[
"from",
"a",
"name",
"of",
"a",
"folder",
"of",
"a",
"bundle",
"this",
"function",
"returns",
"the",
"corresponding",
"class",
"name"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L332-L339
|
26,487
|
libgraviton/graviton
|
src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php
|
GenerateDynamicBundleCommand.getBundleFinder
|
private function getBundleFinder($baseDir)
{
$bundleBaseDir = $baseDir.self::BUNDLE_NAMESPACE;
if (!(new Filesystem())->exists($bundleBaseDir)) {
return null;
}
$bundleFinder = new Finder();
$bundleFinder->directories()->in($bundleBaseDir)->depth('== 0')->notName('BundleBundle');
return $bundleFinder;
}
|
php
|
private function getBundleFinder($baseDir)
{
$bundleBaseDir = $baseDir.self::BUNDLE_NAMESPACE;
if (!(new Filesystem())->exists($bundleBaseDir)) {
return null;
}
$bundleFinder = new Finder();
$bundleFinder->directories()->in($bundleBaseDir)->depth('== 0')->notName('BundleBundle');
return $bundleFinder;
}
|
[
"private",
"function",
"getBundleFinder",
"(",
"$",
"baseDir",
")",
"{",
"$",
"bundleBaseDir",
"=",
"$",
"baseDir",
".",
"self",
"::",
"BUNDLE_NAMESPACE",
";",
"if",
"(",
"!",
"(",
"new",
"Filesystem",
"(",
")",
")",
"->",
"exists",
"(",
"$",
"bundleBaseDir",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"bundleFinder",
"=",
"new",
"Finder",
"(",
")",
";",
"$",
"bundleFinder",
"->",
"directories",
"(",
")",
"->",
"in",
"(",
"$",
"bundleBaseDir",
")",
"->",
"depth",
"(",
"'== 0'",
")",
"->",
"notName",
"(",
"'BundleBundle'",
")",
";",
"return",
"$",
"bundleFinder",
";",
"}"
] |
returns a finder that iterates all bundle directories
@param string $baseDir the base dir to search
@return Finder|null finder or null if basedir does not exist
|
[
"returns",
"a",
"finder",
"that",
"iterates",
"all",
"bundle",
"directories"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L348-L360
|
26,488
|
libgraviton/graviton
|
src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php
|
GenerateDynamicBundleCommand.getTemplateHash
|
private function getTemplateHash()
{
$templateDir = __DIR__ . '/../Resources/skeleton';
$resourceFinder = new Finder();
$resourceFinder->in($templateDir)->files()->sortByName();
$templateTimes = '';
foreach ($resourceFinder as $file) {
$templateTimes .= PATH_SEPARATOR . sha1_file($file->getPathname());
}
return sha1($templateTimes);
}
|
php
|
private function getTemplateHash()
{
$templateDir = __DIR__ . '/../Resources/skeleton';
$resourceFinder = new Finder();
$resourceFinder->in($templateDir)->files()->sortByName();
$templateTimes = '';
foreach ($resourceFinder as $file) {
$templateTimes .= PATH_SEPARATOR . sha1_file($file->getPathname());
}
return sha1($templateTimes);
}
|
[
"private",
"function",
"getTemplateHash",
"(",
")",
"{",
"$",
"templateDir",
"=",
"__DIR__",
".",
"'/../Resources/skeleton'",
";",
"$",
"resourceFinder",
"=",
"new",
"Finder",
"(",
")",
";",
"$",
"resourceFinder",
"->",
"in",
"(",
"$",
"templateDir",
")",
"->",
"files",
"(",
")",
"->",
"sortByName",
"(",
")",
";",
"$",
"templateTimes",
"=",
"''",
";",
"foreach",
"(",
"$",
"resourceFinder",
"as",
"$",
"file",
")",
"{",
"$",
"templateTimes",
".=",
"PATH_SEPARATOR",
".",
"sha1_file",
"(",
"$",
"file",
"->",
"getPathname",
"(",
")",
")",
";",
"}",
"return",
"sha1",
"(",
"$",
"templateTimes",
")",
";",
"}"
] |
Calculates a hash of all templates that generator uses to output it's file.
That way a regeneration will be triggered when one of them changes..
@return string hash
|
[
"Calculates",
"a",
"hash",
"of",
"all",
"templates",
"that",
"generator",
"uses",
"to",
"output",
"it",
"s",
"file",
".",
"That",
"way",
"a",
"regeneration",
"will",
"be",
"triggered",
"when",
"one",
"of",
"them",
"changes",
".."
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L368-L378
|
26,489
|
libgraviton/graviton
|
src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php
|
GenerateDynamicBundleCommand.generateSubResources
|
protected function generateSubResources(
OutputInterface $output,
JsonDefinition $jsonDef,
$bundleName,
$bundleClassName
) {
foreach ($this->getSubResources($jsonDef) as $subRecource) {
$arguments = [
'graviton:generate:resource',
'--no-debug' => null,
'--entity' => $bundleName . ':' . $subRecource->getId(),
'--bundleClassName' => $bundleClassName,
'--json' => $this->serializer->serialize($subRecource->getDef(), 'json'),
'--no-controller' => 'true',
];
$this->generateResource($arguments, $output, $jsonDef);
}
}
|
php
|
protected function generateSubResources(
OutputInterface $output,
JsonDefinition $jsonDef,
$bundleName,
$bundleClassName
) {
foreach ($this->getSubResources($jsonDef) as $subRecource) {
$arguments = [
'graviton:generate:resource',
'--no-debug' => null,
'--entity' => $bundleName . ':' . $subRecource->getId(),
'--bundleClassName' => $bundleClassName,
'--json' => $this->serializer->serialize($subRecource->getDef(), 'json'),
'--no-controller' => 'true',
];
$this->generateResource($arguments, $output, $jsonDef);
}
}
|
[
"protected",
"function",
"generateSubResources",
"(",
"OutputInterface",
"$",
"output",
",",
"JsonDefinition",
"$",
"jsonDef",
",",
"$",
"bundleName",
",",
"$",
"bundleClassName",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getSubResources",
"(",
"$",
"jsonDef",
")",
"as",
"$",
"subRecource",
")",
"{",
"$",
"arguments",
"=",
"[",
"'graviton:generate:resource'",
",",
"'--no-debug'",
"=>",
"null",
",",
"'--entity'",
"=>",
"$",
"bundleName",
".",
"':'",
".",
"$",
"subRecource",
"->",
"getId",
"(",
")",
",",
"'--bundleClassName'",
"=>",
"$",
"bundleClassName",
",",
"'--json'",
"=>",
"$",
"this",
"->",
"serializer",
"->",
"serialize",
"(",
"$",
"subRecource",
"->",
"getDef",
"(",
")",
",",
"'json'",
")",
",",
"'--no-controller'",
"=>",
"'true'",
",",
"]",
";",
"$",
"this",
"->",
"generateResource",
"(",
"$",
"arguments",
",",
"$",
"output",
",",
"$",
"jsonDef",
")",
";",
"}",
"}"
] |
Generate Bundle entities
@param OutputInterface $output Instance to sent text to be displayed on stout.
@param JsonDefinition $jsonDef Configuration to be generated the entity from.
@param string $bundleName Name of the bundle the entity shall be generated for.
@param string $bundleClassName class name
@return void
@throws \Exception
|
[
"Generate",
"Bundle",
"entities"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L391-L408
|
26,490
|
libgraviton/graviton
|
src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php
|
GenerateDynamicBundleCommand.generateResources
|
protected function generateResources(
JsonDefinition $jsonDef,
$bundleName,
$bundleDir,
$bundleNamespace
) {
/** @var ResourceGenerator $generator */
$generator = $this->resourceGenerator;
$generator->setGenerateController(false);
foreach ($this->getSubResources($jsonDef) as $subRecource) {
$generator->setJson(new JsonDefinition($subRecource->getDef()->setIsSubDocument(true)));
$generator->generate(
$bundleDir,
$bundleNamespace,
$bundleName,
$subRecource->getId()
);
}
// main resources
if (!empty($jsonDef->getFields())) {
$generator->setGenerateController(true);
$routerBase = $jsonDef->getRouterBase();
if ($routerBase === false || $this->isNotWhitelistedController($routerBase)) {
$generator->setGenerateController(false);
}
$generator->setJson(new JsonDefinition($jsonDef->getDef()));
$generator->generate(
$bundleDir,
$bundleNamespace,
$bundleName,
$jsonDef->getId()
);
}
}
|
php
|
protected function generateResources(
JsonDefinition $jsonDef,
$bundleName,
$bundleDir,
$bundleNamespace
) {
/** @var ResourceGenerator $generator */
$generator = $this->resourceGenerator;
$generator->setGenerateController(false);
foreach ($this->getSubResources($jsonDef) as $subRecource) {
$generator->setJson(new JsonDefinition($subRecource->getDef()->setIsSubDocument(true)));
$generator->generate(
$bundleDir,
$bundleNamespace,
$bundleName,
$subRecource->getId()
);
}
// main resources
if (!empty($jsonDef->getFields())) {
$generator->setGenerateController(true);
$routerBase = $jsonDef->getRouterBase();
if ($routerBase === false || $this->isNotWhitelistedController($routerBase)) {
$generator->setGenerateController(false);
}
$generator->setJson(new JsonDefinition($jsonDef->getDef()));
$generator->generate(
$bundleDir,
$bundleNamespace,
$bundleName,
$jsonDef->getId()
);
}
}
|
[
"protected",
"function",
"generateResources",
"(",
"JsonDefinition",
"$",
"jsonDef",
",",
"$",
"bundleName",
",",
"$",
"bundleDir",
",",
"$",
"bundleNamespace",
")",
"{",
"/** @var ResourceGenerator $generator */",
"$",
"generator",
"=",
"$",
"this",
"->",
"resourceGenerator",
";",
"$",
"generator",
"->",
"setGenerateController",
"(",
"false",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getSubResources",
"(",
"$",
"jsonDef",
")",
"as",
"$",
"subRecource",
")",
"{",
"$",
"generator",
"->",
"setJson",
"(",
"new",
"JsonDefinition",
"(",
"$",
"subRecource",
"->",
"getDef",
"(",
")",
"->",
"setIsSubDocument",
"(",
"true",
")",
")",
")",
";",
"$",
"generator",
"->",
"generate",
"(",
"$",
"bundleDir",
",",
"$",
"bundleNamespace",
",",
"$",
"bundleName",
",",
"$",
"subRecource",
"->",
"getId",
"(",
")",
")",
";",
"}",
"// main resources",
"if",
"(",
"!",
"empty",
"(",
"$",
"jsonDef",
"->",
"getFields",
"(",
")",
")",
")",
"{",
"$",
"generator",
"->",
"setGenerateController",
"(",
"true",
")",
";",
"$",
"routerBase",
"=",
"$",
"jsonDef",
"->",
"getRouterBase",
"(",
")",
";",
"if",
"(",
"$",
"routerBase",
"===",
"false",
"||",
"$",
"this",
"->",
"isNotWhitelistedController",
"(",
"$",
"routerBase",
")",
")",
"{",
"$",
"generator",
"->",
"setGenerateController",
"(",
"false",
")",
";",
"}",
"$",
"generator",
"->",
"setJson",
"(",
"new",
"JsonDefinition",
"(",
"$",
"jsonDef",
"->",
"getDef",
"(",
")",
")",
")",
";",
"$",
"generator",
"->",
"generate",
"(",
"$",
"bundleDir",
",",
"$",
"bundleNamespace",
",",
"$",
"bundleName",
",",
"$",
"jsonDef",
"->",
"getId",
"(",
")",
")",
";",
"}",
"}"
] |
generates the resources of a bundle
@param JsonDefinition $jsonDef definition
@param string $bundleName name
@param string $bundleDir dir
@param string $bundleNamespace namespace
@return void
|
[
"generates",
"the",
"resources",
"of",
"a",
"bundle"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L420-L458
|
26,491
|
libgraviton/graviton
|
src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php
|
GenerateDynamicBundleCommand.getSubResources
|
protected function getSubResources(JsonDefinition $definition)
{
$resources = [];
foreach ($definition->getFields() as $field) {
while ($field instanceof JsonDefinitionArray) {
$field = $field->getElement();
}
if (!$field instanceof JsonDefinitionHash) {
continue;
}
$subDefiniton = $field->getJsonDefinition();
$resources = array_merge($this->getSubResources($subDefiniton), $resources);
$resources[] = $subDefiniton;
}
return $resources;
}
|
php
|
protected function getSubResources(JsonDefinition $definition)
{
$resources = [];
foreach ($definition->getFields() as $field) {
while ($field instanceof JsonDefinitionArray) {
$field = $field->getElement();
}
if (!$field instanceof JsonDefinitionHash) {
continue;
}
$subDefiniton = $field->getJsonDefinition();
$resources = array_merge($this->getSubResources($subDefiniton), $resources);
$resources[] = $subDefiniton;
}
return $resources;
}
|
[
"protected",
"function",
"getSubResources",
"(",
"JsonDefinition",
"$",
"definition",
")",
"{",
"$",
"resources",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"definition",
"->",
"getFields",
"(",
")",
"as",
"$",
"field",
")",
"{",
"while",
"(",
"$",
"field",
"instanceof",
"JsonDefinitionArray",
")",
"{",
"$",
"field",
"=",
"$",
"field",
"->",
"getElement",
"(",
")",
";",
"}",
"if",
"(",
"!",
"$",
"field",
"instanceof",
"JsonDefinitionHash",
")",
"{",
"continue",
";",
"}",
"$",
"subDefiniton",
"=",
"$",
"field",
"->",
"getJsonDefinition",
"(",
")",
";",
"$",
"resources",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"getSubResources",
"(",
"$",
"subDefiniton",
")",
",",
"$",
"resources",
")",
";",
"$",
"resources",
"[",
"]",
"=",
"$",
"subDefiniton",
";",
"}",
"return",
"$",
"resources",
";",
"}"
] |
Get all sub hashes
@param JsonDefinition $definition Main JSON definition
@return JsonDefinition[]
|
[
"Get",
"all",
"sub",
"hashes"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L466-L484
|
26,492
|
libgraviton/graviton
|
src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php
|
GenerateDynamicBundleCommand.generateResource
|
private function generateResource(array $arguments, OutputInterface $output, JsonDefinition $jsonDef)
{
// controller?
$routerBase = $jsonDef->getRouterBase();
if ($routerBase === false || $this->isNotWhitelistedController($routerBase)) {
$arguments['--no-controller'] = 'true';
}
$this->runner->executeCommand($arguments, $output, 'Create resource call failed, see above. Exiting.');
}
|
php
|
private function generateResource(array $arguments, OutputInterface $output, JsonDefinition $jsonDef)
{
// controller?
$routerBase = $jsonDef->getRouterBase();
if ($routerBase === false || $this->isNotWhitelistedController($routerBase)) {
$arguments['--no-controller'] = 'true';
}
$this->runner->executeCommand($arguments, $output, 'Create resource call failed, see above. Exiting.');
}
|
[
"private",
"function",
"generateResource",
"(",
"array",
"$",
"arguments",
",",
"OutputInterface",
"$",
"output",
",",
"JsonDefinition",
"$",
"jsonDef",
")",
"{",
"// controller?",
"$",
"routerBase",
"=",
"$",
"jsonDef",
"->",
"getRouterBase",
"(",
")",
";",
"if",
"(",
"$",
"routerBase",
"===",
"false",
"||",
"$",
"this",
"->",
"isNotWhitelistedController",
"(",
"$",
"routerBase",
")",
")",
"{",
"$",
"arguments",
"[",
"'--no-controller'",
"]",
"=",
"'true'",
";",
"}",
"$",
"this",
"->",
"runner",
"->",
"executeCommand",
"(",
"$",
"arguments",
",",
"$",
"output",
",",
"'Create resource call failed, see above. Exiting.'",
")",
";",
"}"
] |
Gathers data for the command to run.
@param array $arguments Set of cli arguments passed to the command
@param OutputInterface $output Output channel to send messages to.
@param JsonDefinition $jsonDef Configuration of the service
@return void
@throws \LogicException
|
[
"Gathers",
"data",
"for",
"the",
"command",
"to",
"run",
"."
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L496-L505
|
26,493
|
libgraviton/graviton
|
src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php
|
GenerateDynamicBundleCommand.generateBundleBundleClass
|
private function generateBundleBundleClass()
{
// add optional bundles if defined by parameter.
if ($this->bundleAdditions !== null) {
$this->bundleBundleGenerator->setAdditions($this->bundleAdditions);
} else {
$this->bundleBundleGenerator->setAdditions([]);
}
$this->bundleBundleGenerator->generate(
$this->bundleBundleList,
$this->bundleBundleNamespace,
$this->bundleBundleClassname,
$this->bundleBundleClassfile
);
}
|
php
|
private function generateBundleBundleClass()
{
// add optional bundles if defined by parameter.
if ($this->bundleAdditions !== null) {
$this->bundleBundleGenerator->setAdditions($this->bundleAdditions);
} else {
$this->bundleBundleGenerator->setAdditions([]);
}
$this->bundleBundleGenerator->generate(
$this->bundleBundleList,
$this->bundleBundleNamespace,
$this->bundleBundleClassname,
$this->bundleBundleClassfile
);
}
|
[
"private",
"function",
"generateBundleBundleClass",
"(",
")",
"{",
"// add optional bundles if defined by parameter.",
"if",
"(",
"$",
"this",
"->",
"bundleAdditions",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"bundleBundleGenerator",
"->",
"setAdditions",
"(",
"$",
"this",
"->",
"bundleAdditions",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"bundleBundleGenerator",
"->",
"setAdditions",
"(",
"[",
"]",
")",
";",
"}",
"$",
"this",
"->",
"bundleBundleGenerator",
"->",
"generate",
"(",
"$",
"this",
"->",
"bundleBundleList",
",",
"$",
"this",
"->",
"bundleBundleNamespace",
",",
"$",
"this",
"->",
"bundleBundleClassname",
",",
"$",
"this",
"->",
"bundleBundleClassfile",
")",
";",
"}"
] |
Generates our BundleBundle for dynamic bundles.
It basically replaces the Bundle main class that got generated
by the Sensio bundle task and it includes all of our bundles there.
@return void
|
[
"Generates",
"our",
"BundleBundle",
"for",
"dynamic",
"bundles",
".",
"It",
"basically",
"replaces",
"the",
"Bundle",
"main",
"class",
"that",
"got",
"generated",
"by",
"the",
"Sensio",
"bundle",
"task",
"and",
"it",
"includes",
"all",
"of",
"our",
"bundles",
"there",
"."
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L538-L553
|
26,494
|
libgraviton/graviton
|
src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php
|
GenerateDynamicBundleCommand.generateGenerationHashFile
|
private function generateGenerationHashFile($bundleDir, $hash)
{
$fs = new Filesystem();
if ($fs->exists($bundleDir)) {
$fs->dumpFile($bundleDir.DIRECTORY_SEPARATOR.self::GENERATION_HASHFILE_FILENAME, $hash);
}
}
|
php
|
private function generateGenerationHashFile($bundleDir, $hash)
{
$fs = new Filesystem();
if ($fs->exists($bundleDir)) {
$fs->dumpFile($bundleDir.DIRECTORY_SEPARATOR.self::GENERATION_HASHFILE_FILENAME, $hash);
}
}
|
[
"private",
"function",
"generateGenerationHashFile",
"(",
"$",
"bundleDir",
",",
"$",
"hash",
")",
"{",
"$",
"fs",
"=",
"new",
"Filesystem",
"(",
")",
";",
"if",
"(",
"$",
"fs",
"->",
"exists",
"(",
"$",
"bundleDir",
")",
")",
"{",
"$",
"fs",
"->",
"dumpFile",
"(",
"$",
"bundleDir",
".",
"DIRECTORY_SEPARATOR",
".",
"self",
"::",
"GENERATION_HASHFILE_FILENAME",
",",
"$",
"hash",
")",
";",
"}",
"}"
] |
Generates the file containing the hash to determine if this bundle needs regeneration
@param string $bundleDir directory of the bundle
@param string $hash the hash to save
@return void
|
[
"Generates",
"the",
"file",
"containing",
"the",
"hash",
"to",
"determine",
"if",
"this",
"bundle",
"needs",
"regeneration"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Command/GenerateDynamicBundleCommand.php#L582-L588
|
26,495
|
libgraviton/graviton
|
src/Graviton/DocumentBundle/DependencyInjection/Compiler/ExtRefFieldsCompilerPass.php
|
ExtRefFieldsCompilerPass.process
|
public function process(ContainerBuilder $container)
{
$this->documentMap = $container->get('graviton.document.map');
$map = [];
$services = array_keys($container->findTaggedServiceIds('graviton.rest'));
foreach ($services as $id) {
list($ns, $bundle, , $doc) = explode('.', $id);
if (empty($bundle) || empty($doc)) {
continue;
}
if ($bundle === 'core' && $doc === 'main') {
continue;
}
$className = $this->getServiceDocument(
$container->getDefinition($id),
$ns,
$bundle,
$doc
);
$extRefFields = $this->processDocument($this->documentMap->getDocument($className));
$routePrefix = strtolower($ns.'.'.$bundle.'.'.'rest'.'.'.$doc);
$map[$routePrefix.'.get'] = $extRefFields;
$map[$routePrefix.'.all'] = $extRefFields;
}
$container->setParameter('graviton.document.extref.fields', $map);
}
|
php
|
public function process(ContainerBuilder $container)
{
$this->documentMap = $container->get('graviton.document.map');
$map = [];
$services = array_keys($container->findTaggedServiceIds('graviton.rest'));
foreach ($services as $id) {
list($ns, $bundle, , $doc) = explode('.', $id);
if (empty($bundle) || empty($doc)) {
continue;
}
if ($bundle === 'core' && $doc === 'main') {
continue;
}
$className = $this->getServiceDocument(
$container->getDefinition($id),
$ns,
$bundle,
$doc
);
$extRefFields = $this->processDocument($this->documentMap->getDocument($className));
$routePrefix = strtolower($ns.'.'.$bundle.'.'.'rest'.'.'.$doc);
$map[$routePrefix.'.get'] = $extRefFields;
$map[$routePrefix.'.all'] = $extRefFields;
}
$container->setParameter('graviton.document.extref.fields', $map);
}
|
[
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"this",
"->",
"documentMap",
"=",
"$",
"container",
"->",
"get",
"(",
"'graviton.document.map'",
")",
";",
"$",
"map",
"=",
"[",
"]",
";",
"$",
"services",
"=",
"array_keys",
"(",
"$",
"container",
"->",
"findTaggedServiceIds",
"(",
"'graviton.rest'",
")",
")",
";",
"foreach",
"(",
"$",
"services",
"as",
"$",
"id",
")",
"{",
"list",
"(",
"$",
"ns",
",",
"$",
"bundle",
",",
",",
"$",
"doc",
")",
"=",
"explode",
"(",
"'.'",
",",
"$",
"id",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"bundle",
")",
"||",
"empty",
"(",
"$",
"doc",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"$",
"bundle",
"===",
"'core'",
"&&",
"$",
"doc",
"===",
"'main'",
")",
"{",
"continue",
";",
"}",
"$",
"className",
"=",
"$",
"this",
"->",
"getServiceDocument",
"(",
"$",
"container",
"->",
"getDefinition",
"(",
"$",
"id",
")",
",",
"$",
"ns",
",",
"$",
"bundle",
",",
"$",
"doc",
")",
";",
"$",
"extRefFields",
"=",
"$",
"this",
"->",
"processDocument",
"(",
"$",
"this",
"->",
"documentMap",
"->",
"getDocument",
"(",
"$",
"className",
")",
")",
";",
"$",
"routePrefix",
"=",
"strtolower",
"(",
"$",
"ns",
".",
"'.'",
".",
"$",
"bundle",
".",
"'.'",
".",
"'rest'",
".",
"'.'",
".",
"$",
"doc",
")",
";",
"$",
"map",
"[",
"$",
"routePrefix",
".",
"'.get'",
"]",
"=",
"$",
"extRefFields",
";",
"$",
"map",
"[",
"$",
"routePrefix",
".",
"'.all'",
"]",
"=",
"$",
"extRefFields",
";",
"}",
"$",
"container",
"->",
"setParameter",
"(",
"'graviton.document.extref.fields'",
",",
"$",
"map",
")",
";",
"}"
] |
Make extref fields map and set it to parameter
@param ContainerBuilder $container container builder
@return void
|
[
"Make",
"extref",
"fields",
"map",
"and",
"set",
"it",
"to",
"parameter"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/ExtRefFieldsCompilerPass.php#L41-L71
|
26,496
|
libgraviton/graviton
|
src/Graviton/DocumentBundle/DependencyInjection/Compiler/ExtRefFieldsCompilerPass.php
|
ExtRefFieldsCompilerPass.getServiceDocument
|
private function getServiceDocument(Definition $service, $ns, $bundle, $doc)
{
$tags = $service->getTag('graviton.rest');
if (!empty($tags[0]['collection'])) {
$doc = $tags[0]['collection'];
$bundle = $tags[0]['collection'];
}
if (strtolower($ns) === 'gravitondyn') {
$ns = 'GravitonDyn';
}
return sprintf(
'%s\\%s\\Document\\%s',
ucfirst($ns),
ucfirst($bundle).'Bundle',
ucfirst($doc)
);
}
|
php
|
private function getServiceDocument(Definition $service, $ns, $bundle, $doc)
{
$tags = $service->getTag('graviton.rest');
if (!empty($tags[0]['collection'])) {
$doc = $tags[0]['collection'];
$bundle = $tags[0]['collection'];
}
if (strtolower($ns) === 'gravitondyn') {
$ns = 'GravitonDyn';
}
return sprintf(
'%s\\%s\\Document\\%s',
ucfirst($ns),
ucfirst($bundle).'Bundle',
ucfirst($doc)
);
}
|
[
"private",
"function",
"getServiceDocument",
"(",
"Definition",
"$",
"service",
",",
"$",
"ns",
",",
"$",
"bundle",
",",
"$",
"doc",
")",
"{",
"$",
"tags",
"=",
"$",
"service",
"->",
"getTag",
"(",
"'graviton.rest'",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"tags",
"[",
"0",
"]",
"[",
"'collection'",
"]",
")",
")",
"{",
"$",
"doc",
"=",
"$",
"tags",
"[",
"0",
"]",
"[",
"'collection'",
"]",
";",
"$",
"bundle",
"=",
"$",
"tags",
"[",
"0",
"]",
"[",
"'collection'",
"]",
";",
"}",
"if",
"(",
"strtolower",
"(",
"$",
"ns",
")",
"===",
"'gravitondyn'",
")",
"{",
"$",
"ns",
"=",
"'GravitonDyn'",
";",
"}",
"return",
"sprintf",
"(",
"'%s\\\\%s\\\\Document\\\\%s'",
",",
"ucfirst",
"(",
"$",
"ns",
")",
",",
"ucfirst",
"(",
"$",
"bundle",
")",
".",
"'Bundle'",
",",
"ucfirst",
"(",
"$",
"doc",
")",
")",
";",
"}"
] |
Get document class name from service
@param Definition $service Service definition
@param string $ns Bundle namespace
@param string $bundle Bundle name
@param string $doc Document name
@return string
|
[
"Get",
"document",
"class",
"name",
"from",
"service"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/ExtRefFieldsCompilerPass.php#L83-L101
|
26,497
|
libgraviton/graviton
|
src/Graviton/DocumentBundle/DependencyInjection/Compiler/ExtRefFieldsCompilerPass.php
|
ExtRefFieldsCompilerPass.processDocument
|
private function processDocument(Document $document, $exposedPrefix = '')
{
$result = [];
foreach ($document->getFields() as $field) {
if ($field instanceof Field) {
if ($field->getType() === 'extref') {
$result[] = $exposedPrefix.$field->getExposedName();
}
} elseif ($field instanceof ArrayField) {
if ($field->getItemType() === 'extref') {
$result[] = $exposedPrefix.$field->getExposedName().'.0';
}
} elseif ($field instanceof EmbedOne) {
$result = array_merge(
$result,
$this->processDocument(
$field->getDocument(),
$exposedPrefix.$field->getExposedName().'.'
)
);
} elseif ($field instanceof EmbedMany) {
$result = array_merge(
$result,
$this->processDocument(
$field->getDocument(),
$exposedPrefix.$field->getExposedName().'.0.'
)
);
}
}
return $result;
}
|
php
|
private function processDocument(Document $document, $exposedPrefix = '')
{
$result = [];
foreach ($document->getFields() as $field) {
if ($field instanceof Field) {
if ($field->getType() === 'extref') {
$result[] = $exposedPrefix.$field->getExposedName();
}
} elseif ($field instanceof ArrayField) {
if ($field->getItemType() === 'extref') {
$result[] = $exposedPrefix.$field->getExposedName().'.0';
}
} elseif ($field instanceof EmbedOne) {
$result = array_merge(
$result,
$this->processDocument(
$field->getDocument(),
$exposedPrefix.$field->getExposedName().'.'
)
);
} elseif ($field instanceof EmbedMany) {
$result = array_merge(
$result,
$this->processDocument(
$field->getDocument(),
$exposedPrefix.$field->getExposedName().'.0.'
)
);
}
}
return $result;
}
|
[
"private",
"function",
"processDocument",
"(",
"Document",
"$",
"document",
",",
"$",
"exposedPrefix",
"=",
"''",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"document",
"->",
"getFields",
"(",
")",
"as",
"$",
"field",
")",
"{",
"if",
"(",
"$",
"field",
"instanceof",
"Field",
")",
"{",
"if",
"(",
"$",
"field",
"->",
"getType",
"(",
")",
"===",
"'extref'",
")",
"{",
"$",
"result",
"[",
"]",
"=",
"$",
"exposedPrefix",
".",
"$",
"field",
"->",
"getExposedName",
"(",
")",
";",
"}",
"}",
"elseif",
"(",
"$",
"field",
"instanceof",
"ArrayField",
")",
"{",
"if",
"(",
"$",
"field",
"->",
"getItemType",
"(",
")",
"===",
"'extref'",
")",
"{",
"$",
"result",
"[",
"]",
"=",
"$",
"exposedPrefix",
".",
"$",
"field",
"->",
"getExposedName",
"(",
")",
".",
"'.0'",
";",
"}",
"}",
"elseif",
"(",
"$",
"field",
"instanceof",
"EmbedOne",
")",
"{",
"$",
"result",
"=",
"array_merge",
"(",
"$",
"result",
",",
"$",
"this",
"->",
"processDocument",
"(",
"$",
"field",
"->",
"getDocument",
"(",
")",
",",
"$",
"exposedPrefix",
".",
"$",
"field",
"->",
"getExposedName",
"(",
")",
".",
"'.'",
")",
")",
";",
"}",
"elseif",
"(",
"$",
"field",
"instanceof",
"EmbedMany",
")",
"{",
"$",
"result",
"=",
"array_merge",
"(",
"$",
"result",
",",
"$",
"this",
"->",
"processDocument",
"(",
"$",
"field",
"->",
"getDocument",
"(",
")",
",",
"$",
"exposedPrefix",
".",
"$",
"field",
"->",
"getExposedName",
"(",
")",
".",
"'.0.'",
")",
")",
";",
"}",
"}",
"return",
"$",
"result",
";",
"}"
] |
Recursive doctrine document processing
@param Document $document Document
@param string $exposedPrefix Exposed field prefix
@return array
|
[
"Recursive",
"doctrine",
"document",
"processing"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/ExtRefFieldsCompilerPass.php#L110-L142
|
26,498
|
libgraviton/graviton
|
src/Graviton/ProxyBundle/Definition/Loader/HttpLoader.php
|
HttpLoader.supports
|
public function supports($url)
{
$error = $this->validator->validate($url, [new Url()]);
return 0 === count($error);
}
|
php
|
public function supports($url)
{
$error = $this->validator->validate($url, [new Url()]);
return 0 === count($error);
}
|
[
"public",
"function",
"supports",
"(",
"$",
"url",
")",
"{",
"$",
"error",
"=",
"$",
"this",
"->",
"validator",
"->",
"validate",
"(",
"$",
"url",
",",
"[",
"new",
"Url",
"(",
")",
"]",
")",
";",
"return",
"0",
"===",
"count",
"(",
"$",
"error",
")",
";",
"}"
] |
check if the url is valid
@param string $url url
@return boolean
|
[
"check",
"if",
"the",
"url",
"is",
"valid"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Definition/Loader/HttpLoader.php#L136-L141
|
26,499
|
libgraviton/graviton
|
src/Graviton/ProxyBundle/Definition/Loader/HttpLoader.php
|
HttpLoader.fetchFile
|
private function fetchFile(RequestInterface $request)
{
$content = "{}";
try {
$response = $this->client->send($request);
$content = (string) $response->getBody();
if (isset($this->cache)) {
$this->cache->save($this->options['storeKey'], $content, $this->cacheLifetime);
}
} catch (RequestException $e) {
$this->logger->info(
"Unable to fetch File!",
[
"message" => $e->getMessage(),
"url" => $request->getRequestTarget(),
"code" => (!empty($e->getResponse())? $e->getResponse()->getStatusCode() : 500)
]
);
}
return $content;
}
|
php
|
private function fetchFile(RequestInterface $request)
{
$content = "{}";
try {
$response = $this->client->send($request);
$content = (string) $response->getBody();
if (isset($this->cache)) {
$this->cache->save($this->options['storeKey'], $content, $this->cacheLifetime);
}
} catch (RequestException $e) {
$this->logger->info(
"Unable to fetch File!",
[
"message" => $e->getMessage(),
"url" => $request->getRequestTarget(),
"code" => (!empty($e->getResponse())? $e->getResponse()->getStatusCode() : 500)
]
);
}
return $content;
}
|
[
"private",
"function",
"fetchFile",
"(",
"RequestInterface",
"$",
"request",
")",
"{",
"$",
"content",
"=",
"\"{}\"",
";",
"try",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"$",
"request",
")",
";",
"$",
"content",
"=",
"(",
"string",
")",
"$",
"response",
"->",
"getBody",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"cache",
")",
")",
"{",
"$",
"this",
"->",
"cache",
"->",
"save",
"(",
"$",
"this",
"->",
"options",
"[",
"'storeKey'",
"]",
",",
"$",
"content",
",",
"$",
"this",
"->",
"cacheLifetime",
")",
";",
"}",
"}",
"catch",
"(",
"RequestException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"\"Unable to fetch File!\"",
",",
"[",
"\"message\"",
"=>",
"$",
"e",
"->",
"getMessage",
"(",
")",
",",
"\"url\"",
"=>",
"$",
"request",
"->",
"getRequestTarget",
"(",
")",
",",
"\"code\"",
"=>",
"(",
"!",
"empty",
"(",
"$",
"e",
"->",
"getResponse",
"(",
")",
")",
"?",
"$",
"e",
"->",
"getResponse",
"(",
")",
"->",
"getStatusCode",
"(",
")",
":",
"500",
")",
"]",
")",
";",
"}",
"return",
"$",
"content",
";",
"}"
] |
fetch file from remote destination
@param RequestInterface $request request
@return string
|
[
"fetch",
"file",
"from",
"remote",
"destination"
] |
5eccfb2fba31dadf659f0f55edeb1ebca403563e
|
https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/Definition/Loader/HttpLoader.php#L196-L217
|
Subsets and Splits
Yii Code Samples
Gathers all records from test, train, and validation sets that contain the word 'yii', providing a basic filtered view of the dataset relevant to Yii-related content.