repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1 value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
silverstripe/silverstripe-versioned | src/VersionedGridFieldItemRequest.php | VersionedGridFieldItemRequest.saveFormIntoRecord | public function saveFormIntoRecord($data, $form)
{
$record = parent::saveFormIntoRecord($data, $form);
// Note: Don't publish if versioned, since that's a separate action
$ownerIsVersioned = $record && $record->hasExtension(Versioned::class);
$ownerIsPublishable = $record && $record->hasExtension(RecursivePublishable::class);
if ($ownerIsPublishable && !$ownerIsVersioned) {
/** @var RecursivePublishable $record */
$record->publishRecursive();
}
return $record;
} | php | public function saveFormIntoRecord($data, $form)
{
$record = parent::saveFormIntoRecord($data, $form);
// Note: Don't publish if versioned, since that's a separate action
$ownerIsVersioned = $record && $record->hasExtension(Versioned::class);
$ownerIsPublishable = $record && $record->hasExtension(RecursivePublishable::class);
if ($ownerIsPublishable && !$ownerIsVersioned) {
/** @var RecursivePublishable $record */
$record->publishRecursive();
}
return $record;
} | [
"public",
"function",
"saveFormIntoRecord",
"(",
"$",
"data",
",",
"$",
"form",
")",
"{",
"$",
"record",
"=",
"parent",
"::",
"saveFormIntoRecord",
"(",
"$",
"data",
",",
"$",
"form",
")",
";",
"// Note: Don't publish if versioned, since that's a separate action",
... | If a record is recursive publishable, but not versioned, all saves should trigger a recursive publish.
@param array $data
@param Form $form
@return DataObject $record | [
"If",
"a",
"record",
"is",
"recursive",
"publishable",
"but",
"not",
"versioned",
"all",
"saves",
"should",
"trigger",
"a",
"recursive",
"publish",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/VersionedGridFieldItemRequest.php#L96-L109 | train |
silverstripe/silverstripe-versioned | src/VersionedGridFieldItemRequest.php | VersionedGridFieldItemRequest.doArchive | public function doArchive($data, $form)
{
/** @var Versioned|DataObject $record */
$record = $this->getRecord();
if (!$record->canArchive()) {
return $this->httpError(403);
}
// Record name before it's deleted
$title = $record->Title;
$record->doArchive();
$message = _t(
__CLASS__ . '.Archived',
'Archived {name} {title}',
[
'name' => $record->i18n_singular_name(),
'title' => Convert::raw2xml($title)
]
);
$this->setFormMessage($form, $message);
//when an item is deleted, redirect to the parent controller
$controller = $this->getToplevelController();
$controller->getRequest()->addHeader('X-Pjax', 'Content'); // Force a content refresh
return $controller->redirect($this->getBackLink(), 302); //redirect back to admin section
} | php | public function doArchive($data, $form)
{
/** @var Versioned|DataObject $record */
$record = $this->getRecord();
if (!$record->canArchive()) {
return $this->httpError(403);
}
// Record name before it's deleted
$title = $record->Title;
$record->doArchive();
$message = _t(
__CLASS__ . '.Archived',
'Archived {name} {title}',
[
'name' => $record->i18n_singular_name(),
'title' => Convert::raw2xml($title)
]
);
$this->setFormMessage($form, $message);
//when an item is deleted, redirect to the parent controller
$controller = $this->getToplevelController();
$controller->getRequest()->addHeader('X-Pjax', 'Content'); // Force a content refresh
return $controller->redirect($this->getBackLink(), 302); //redirect back to admin section
} | [
"public",
"function",
"doArchive",
"(",
"$",
"data",
",",
"$",
"form",
")",
"{",
"/** @var Versioned|DataObject $record */",
"$",
"record",
"=",
"$",
"this",
"->",
"getRecord",
"(",
")",
";",
"if",
"(",
"!",
"$",
"record",
"->",
"canArchive",
"(",
")",
"... | Archive this versioned record
@param array $data
@param Form $form
@return HTTPResponse | [
"Archive",
"this",
"versioned",
"record"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/VersionedGridFieldItemRequest.php#L118-L145 | train |
silverstripe/silverstripe-versioned | src/VersionedGridFieldItemRequest.php | VersionedGridFieldItemRequest.doPublish | public function doPublish($data, $form)
{
/** @var Versioned|RecursivePublishable|DataObject $record */
$record = $this->getRecord();
$isNewRecord = $record->ID == 0;
// Check permission
if (!$record->canPublish()) {
return $this->httpError(403);
}
// Initial save and reload
$record = $this->saveFormIntoRecord($data, $form);
$record->publishRecursive();
$editURL = $this->Link('edit');
$xmlTitle = Convert::raw2xml($record->Title);
$link = "<a href=\"{$editURL}\">{$xmlTitle}</a>";
$message = _t(
__CLASS__ . '.Published',
'Published {name} {link}',
[
'name' => $record->i18n_singular_name(),
'link' => $link
]
);
$this->setFormMessage($form, $message);
return $this->redirectAfterSave($isNewRecord);
} | php | public function doPublish($data, $form)
{
/** @var Versioned|RecursivePublishable|DataObject $record */
$record = $this->getRecord();
$isNewRecord = $record->ID == 0;
// Check permission
if (!$record->canPublish()) {
return $this->httpError(403);
}
// Initial save and reload
$record = $this->saveFormIntoRecord($data, $form);
$record->publishRecursive();
$editURL = $this->Link('edit');
$xmlTitle = Convert::raw2xml($record->Title);
$link = "<a href=\"{$editURL}\">{$xmlTitle}</a>";
$message = _t(
__CLASS__ . '.Published',
'Published {name} {link}',
[
'name' => $record->i18n_singular_name(),
'link' => $link
]
);
$this->setFormMessage($form, $message);
return $this->redirectAfterSave($isNewRecord);
} | [
"public",
"function",
"doPublish",
"(",
"$",
"data",
",",
"$",
"form",
")",
"{",
"/** @var Versioned|RecursivePublishable|DataObject $record */",
"$",
"record",
"=",
"$",
"this",
"->",
"getRecord",
"(",
")",
";",
"$",
"isNewRecord",
"=",
"$",
"record",
"->",
"... | Publish this versioned record
@param array $data
@param Form $form
@return HTTPResponse | [
"Publish",
"this",
"versioned",
"record"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/VersionedGridFieldItemRequest.php#L154-L183 | train |
silverstripe/silverstripe-versioned | src/VersionedGridFieldItemRequest.php | VersionedGridFieldItemRequest.doUnpublish | public function doUnpublish($data, $form)
{
/** @var Versioned|DataObject $record */
$record = $this->getRecord();
if (!$record->canUnpublish()) {
return $this->httpError(403);
}
// Record name before it's deleted
$title = $record->Title;
$record->doUnpublish();
$message = _t(
__CLASS__ . '.Unpublished',
'Unpublished {name} {title}',
[
'name' => $record->i18n_singular_name(),
'title' => Convert::raw2xml($title)
]
);
$this->setFormMessage($form, $message);
// Redirect back to edit
return $this->redirectAfterSave(false);
} | php | public function doUnpublish($data, $form)
{
/** @var Versioned|DataObject $record */
$record = $this->getRecord();
if (!$record->canUnpublish()) {
return $this->httpError(403);
}
// Record name before it's deleted
$title = $record->Title;
$record->doUnpublish();
$message = _t(
__CLASS__ . '.Unpublished',
'Unpublished {name} {title}',
[
'name' => $record->i18n_singular_name(),
'title' => Convert::raw2xml($title)
]
);
$this->setFormMessage($form, $message);
// Redirect back to edit
return $this->redirectAfterSave(false);
} | [
"public",
"function",
"doUnpublish",
"(",
"$",
"data",
",",
"$",
"form",
")",
"{",
"/** @var Versioned|DataObject $record */",
"$",
"record",
"=",
"$",
"this",
"->",
"getRecord",
"(",
")",
";",
"if",
"(",
"!",
"$",
"record",
"->",
"canUnpublish",
"(",
")",... | Delete this record from the live site
@param array $data
@param Form $form
@return HTTPResponse | [
"Delete",
"this",
"record",
"from",
"the",
"live",
"site"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/VersionedGridFieldItemRequest.php#L192-L216 | train |
silverstripe/silverstripe-versioned | src/VersionedGridFieldItemRequest.php | VersionedGridFieldItemRequest.addVersionedButtons | protected function addVersionedButtons(DataObject $record, FieldList $actions)
{
// Save & Publish action
if ($record->canPublish()) {
// "publish", as with "save", it supports an alternate state to show when action is needed.
$publish = FormAction::create(
'doPublish',
_t(__CLASS__ . '.BUTTONPUBLISH', 'Publish')
)
->setUseButtonTag(true)
->addExtraClass('btn btn-primary font-icon-rocket');
// Insert after save
if ($actions->fieldByName('action_doSave')) {
$actions->insertAfter('action_doSave', $publish);
} else {
$actions->push($publish);
}
}
// Unpublish action
if ($record->isInDB() && $record->canUnpublish()) {
/** @var DataObject|Versioned|RecursivePublishable $liveRecord */
$liveRecord = Versioned::get_by_stage($record->baseClass(), Versioned::LIVE)
->byID($record->ID);
if ($liveRecord) {
$liveOwners = $liveRecord->findOwners(false)->count();
$actions->push(
FormAction::create(
'doUnpublish',
_t(__CLASS__ . '.BUTTONUNPUBLISH', 'Unpublish')
)
->setUseButtonTag(true)
->setDescription(_t(
__CLASS__ . '.BUTTONUNPUBLISHDESC',
'Remove this record from the published site'
))
->addExtraClass('btn-secondary')
->setAttribute('data-owners', $liveOwners)
);
}
}
// Archive action
if ($record->isInDB() && $record->canArchive()) {
// Replace "delete" action
$actions->removeByName('action_doDelete');
// "archive"
$actions->push(
FormAction::create('doArchive', _t(__CLASS__ . '.ARCHIVE', 'Archive'))
->setUseButtonTag(true)
->setDescription(_t(
__CLASS__ . '.BUTTONARCHIVEDESC',
'Unpublish and send to archive'
))
->addExtraClass('btn-secondary action--archive font-icon-box')
);
}
} | php | protected function addVersionedButtons(DataObject $record, FieldList $actions)
{
// Save & Publish action
if ($record->canPublish()) {
// "publish", as with "save", it supports an alternate state to show when action is needed.
$publish = FormAction::create(
'doPublish',
_t(__CLASS__ . '.BUTTONPUBLISH', 'Publish')
)
->setUseButtonTag(true)
->addExtraClass('btn btn-primary font-icon-rocket');
// Insert after save
if ($actions->fieldByName('action_doSave')) {
$actions->insertAfter('action_doSave', $publish);
} else {
$actions->push($publish);
}
}
// Unpublish action
if ($record->isInDB() && $record->canUnpublish()) {
/** @var DataObject|Versioned|RecursivePublishable $liveRecord */
$liveRecord = Versioned::get_by_stage($record->baseClass(), Versioned::LIVE)
->byID($record->ID);
if ($liveRecord) {
$liveOwners = $liveRecord->findOwners(false)->count();
$actions->push(
FormAction::create(
'doUnpublish',
_t(__CLASS__ . '.BUTTONUNPUBLISH', 'Unpublish')
)
->setUseButtonTag(true)
->setDescription(_t(
__CLASS__ . '.BUTTONUNPUBLISHDESC',
'Remove this record from the published site'
))
->addExtraClass('btn-secondary')
->setAttribute('data-owners', $liveOwners)
);
}
}
// Archive action
if ($record->isInDB() && $record->canArchive()) {
// Replace "delete" action
$actions->removeByName('action_doDelete');
// "archive"
$actions->push(
FormAction::create('doArchive', _t(__CLASS__ . '.ARCHIVE', 'Archive'))
->setUseButtonTag(true)
->setDescription(_t(
__CLASS__ . '.BUTTONARCHIVEDESC',
'Unpublish and send to archive'
))
->addExtraClass('btn-secondary action--archive font-icon-box')
);
}
} | [
"protected",
"function",
"addVersionedButtons",
"(",
"DataObject",
"$",
"record",
",",
"FieldList",
"$",
"actions",
")",
"{",
"// Save & Publish action",
"if",
"(",
"$",
"record",
"->",
"canPublish",
"(",
")",
")",
"{",
"// \"publish\", as with \"save\", it supports a... | Getting buttons that are for versioned objects
@param DataObject|Versioned|RecursivePublishable $record
@param FieldList $actions | [
"Getting",
"buttons",
"that",
"are",
"for",
"versioned",
"objects"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/VersionedGridFieldItemRequest.php#L271-L330 | train |
silverstripe/silverstripe-versioned | src/VersionedGridFieldItemRequest.php | VersionedGridFieldItemRequest.addUnversionedButtons | protected function addUnversionedButtons(DataObject $record, FieldList $actions)
{
if (!$record->canEdit()) {
return;
}
$saveAction = $actions->fieldByName('action_doSave');
if (!$saveAction) {
return;
}
if (!$this->record->ID) {
return;
}
$saveAction->setTitle(_t(
__CLASS__ . '.BUTTONAPPLYCHANGES',
'Apply changes'
))->addExtraClass('btn-primary font-icon-save');
} | php | protected function addUnversionedButtons(DataObject $record, FieldList $actions)
{
if (!$record->canEdit()) {
return;
}
$saveAction = $actions->fieldByName('action_doSave');
if (!$saveAction) {
return;
}
if (!$this->record->ID) {
return;
}
$saveAction->setTitle(_t(
__CLASS__ . '.BUTTONAPPLYCHANGES',
'Apply changes'
))->addExtraClass('btn-primary font-icon-save');
} | [
"protected",
"function",
"addUnversionedButtons",
"(",
"DataObject",
"$",
"record",
",",
"FieldList",
"$",
"actions",
")",
"{",
"if",
"(",
"!",
"$",
"record",
"->",
"canEdit",
"(",
")",
")",
"{",
"return",
";",
"}",
"$",
"saveAction",
"=",
"$",
"actions"... | Getting buttons that are for unversioned objects
@param DataObject $record
@param FieldList $actions | [
"Getting",
"buttons",
"that",
"are",
"for",
"unversioned",
"objects"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/VersionedGridFieldItemRequest.php#L338-L354 | train |
silverstripe/silverstripe-versioned | src/DataDifferencer.php | DataDifferencer.ignoreFields | public function ignoreFields($ignoredFields)
{
if (!is_array($ignoredFields)) {
$ignoredFields = func_get_args();
}
$this->ignoredFields = array_merge($this->ignoredFields, $ignoredFields);
return $this;
} | php | public function ignoreFields($ignoredFields)
{
if (!is_array($ignoredFields)) {
$ignoredFields = func_get_args();
}
$this->ignoredFields = array_merge($this->ignoredFields, $ignoredFields);
return $this;
} | [
"public",
"function",
"ignoreFields",
"(",
"$",
"ignoredFields",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"ignoredFields",
")",
")",
"{",
"$",
"ignoredFields",
"=",
"func_get_args",
"(",
")",
";",
"}",
"$",
"this",
"->",
"ignoredFields",
"=",
"arr... | Specify some fields to ignore changes from. Repeated calls are cumulative.
@param array $ignoredFields An array of field names to ignore. Alternatively, pass the field names as
separate args.
@return $this | [
"Specify",
"some",
"fields",
"to",
"ignore",
"changes",
"from",
".",
"Repeated",
"calls",
"are",
"cumulative",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/DataDifferencer.php#L74-L82 | train |
silverstripe/silverstripe-versioned | src/DataDifferencer.php | DataDifferencer.getObjectDisplay | protected function getObjectDisplay($object = null)
{
if (!$object || !$object->isInDB()) {
return '';
}
// Use image tag
// TODO Use CMSThumbnail instead to limit max size, blocked by DataDifferencerTest and GC
// not playing nice with mocked images
if ($object instanceof Image) {
return $object->getTag();
}
// Format title
return $object->obj('Title')->forTemplate();
} | php | protected function getObjectDisplay($object = null)
{
if (!$object || !$object->isInDB()) {
return '';
}
// Use image tag
// TODO Use CMSThumbnail instead to limit max size, blocked by DataDifferencerTest and GC
// not playing nice with mocked images
if ($object instanceof Image) {
return $object->getTag();
}
// Format title
return $object->obj('Title')->forTemplate();
} | [
"protected",
"function",
"getObjectDisplay",
"(",
"$",
"object",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"object",
"||",
"!",
"$",
"object",
"->",
"isInDB",
"(",
")",
")",
"{",
"return",
"''",
";",
"}",
"// Use image tag",
"// TODO Use CMSThumbnail ins... | Get HTML to display for a dataobject
@param DataObject $object
@return string HTML output | [
"Get",
"HTML",
"to",
"display",
"for",
"a",
"dataobject"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/DataDifferencer.php#L183-L198 | train |
silverstripe/silverstripe-versioned | src/ChangeSetItem.php | ChangeSetItem.ThumbnailURL | public function ThumbnailURL($width, $height)
{
$object = $this->getObjectLatestVersion();
if ($object instanceof Thumbnail) {
return $object->ThumbnailURL($width, $height);
}
return null;
} | php | public function ThumbnailURL($width, $height)
{
$object = $this->getObjectLatestVersion();
if ($object instanceof Thumbnail) {
return $object->ThumbnailURL($width, $height);
}
return null;
} | [
"public",
"function",
"ThumbnailURL",
"(",
"$",
"width",
",",
"$",
"height",
")",
"{",
"$",
"object",
"=",
"$",
"this",
"->",
"getObjectLatestVersion",
"(",
")",
";",
"if",
"(",
"$",
"object",
"instanceof",
"Thumbnail",
")",
"{",
"return",
"$",
"object",... | Get a thumbnail for this object
@param int $width Preferred width of the thumbnail
@param int $height Preferred height of the thumbnail
@return string URL to the thumbnail, if available | [
"Get",
"a",
"thumbnail",
"for",
"this",
"object"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L110-L117 | train |
silverstripe/silverstripe-versioned | src/ChangeSetItem.php | ChangeSetItem.getObjectInStage | protected function getObjectInStage($stage)
{
if (!class_exists($this->ObjectClass)) {
throw new UnexpectedDataException("Invalid Class '{$this->ObjectClass}' in ChangeSetItem #{$this->ID}");
}
// Ignore stage for unversioned objects
if (!$this->isVersioned()) {
return DataObject::get_by_id($this->ObjectClass, $this->ObjectID);
}
// Get versioned object
return Versioned::get_by_stage($this->ObjectClass, $stage)->byID($this->ObjectID);
} | php | protected function getObjectInStage($stage)
{
if (!class_exists($this->ObjectClass)) {
throw new UnexpectedDataException("Invalid Class '{$this->ObjectClass}' in ChangeSetItem #{$this->ID}");
}
// Ignore stage for unversioned objects
if (!$this->isVersioned()) {
return DataObject::get_by_id($this->ObjectClass, $this->ObjectID);
}
// Get versioned object
return Versioned::get_by_stage($this->ObjectClass, $stage)->byID($this->ObjectID);
} | [
"protected",
"function",
"getObjectInStage",
"(",
"$",
"stage",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"this",
"->",
"ObjectClass",
")",
")",
"{",
"throw",
"new",
"UnexpectedDataException",
"(",
"\"Invalid Class '{$this->ObjectClass}' in ChangeSetItem #{$... | Find version of this object in the given stage.
If the object isn't versioned it will return the normal record.
@param string $stage
@return DataObject|Versioned|RecursivePublishable Object in this stage (may not be Versioned)
@throws UnexpectedDataException | [
"Find",
"version",
"of",
"this",
"object",
"in",
"the",
"given",
"stage",
".",
"If",
"the",
"object",
"isn",
"t",
"versioned",
"it",
"will",
"return",
"the",
"normal",
"record",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L176-L189 | train |
silverstripe/silverstripe-versioned | src/ChangeSetItem.php | ChangeSetItem.findReferenced | public function findReferenced()
{
$liveRecord = $this->getObjectInStage(Versioned::LIVE);
// For unversioned objects, simply return all owned objects
if (!$this->isVersioned()) {
return $liveRecord->findOwned();
}
// If we have deleted this record, recursively delete live objects on publish
if ($this->getChangeType() === ChangeSetItem::CHANGE_DELETED) {
if (!$liveRecord) {
return ArrayList::create();
}
return $liveRecord->findCascadeDeletes(true);
}
// If changed on stage, include all owned objects for publish
/** @var DataObject|RecursivePublishable $draftRecord */
$draftRecord = $this->getObjectInStage(Versioned::DRAFT);
if (!$draftRecord) {
return ArrayList::create();
}
$references = $draftRecord->findOwned();
// When publishing, use cascade_deletes to partially unpublished sets
if ($liveRecord) {
foreach ($liveRecord->findCascadeDeletes(true) as $next) {
/** @var Versioned|DataObject $next */
if ($next->hasExtension(Versioned::class) && $next->hasStages() && $next->isOnLiveOnly()) {
$this->mergeRelatedObject($references, ArrayList::create(), $next);
}
}
}
return $references;
} | php | public function findReferenced()
{
$liveRecord = $this->getObjectInStage(Versioned::LIVE);
// For unversioned objects, simply return all owned objects
if (!$this->isVersioned()) {
return $liveRecord->findOwned();
}
// If we have deleted this record, recursively delete live objects on publish
if ($this->getChangeType() === ChangeSetItem::CHANGE_DELETED) {
if (!$liveRecord) {
return ArrayList::create();
}
return $liveRecord->findCascadeDeletes(true);
}
// If changed on stage, include all owned objects for publish
/** @var DataObject|RecursivePublishable $draftRecord */
$draftRecord = $this->getObjectInStage(Versioned::DRAFT);
if (!$draftRecord) {
return ArrayList::create();
}
$references = $draftRecord->findOwned();
// When publishing, use cascade_deletes to partially unpublished sets
if ($liveRecord) {
foreach ($liveRecord->findCascadeDeletes(true) as $next) {
/** @var Versioned|DataObject $next */
if ($next->hasExtension(Versioned::class) && $next->hasStages() && $next->isOnLiveOnly()) {
$this->mergeRelatedObject($references, ArrayList::create(), $next);
}
}
}
return $references;
} | [
"public",
"function",
"findReferenced",
"(",
")",
"{",
"$",
"liveRecord",
"=",
"$",
"this",
"->",
"getObjectInStage",
"(",
"Versioned",
"::",
"LIVE",
")",
";",
"// For unversioned objects, simply return all owned objects",
"if",
"(",
"!",
"$",
"this",
"->",
"isVer... | Get all implicit objects for this change
@return SS_List | [
"Get",
"all",
"implicit",
"objects",
"for",
"this",
"change"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L216-L251 | train |
silverstripe/silverstripe-versioned | src/ChangeSetItem.php | ChangeSetItem.publish | public function publish()
{
if (!class_exists($this->ObjectClass)) {
throw new UnexpectedDataException("Invalid Class '{$this->ObjectClass}' in ChangeSetItem #{$this->ID}");
}
// Logical checks prior to publish
if ($this->VersionBefore || $this->VersionAfter) {
throw new BadMethodCallException("This ChangeSetItem has already been published");
}
// Skip unversioned records
if (!$this->isVersioned()) {
$this->VersionBefore = 0;
$this->VersionAfter = 0;
$this->write();
return;
}
// Record state changed
$this->VersionAfter = Versioned::get_versionnumber_by_stage(
$this->ObjectClass,
Versioned::DRAFT,
$this->ObjectID,
false
);
$this->VersionBefore = Versioned::get_versionnumber_by_stage(
$this->ObjectClass,
Versioned::LIVE,
$this->ObjectID,
false
);
// Enact change
$changeType = $this->getChangeType();
switch ($changeType) {
case static::CHANGE_NONE: {
break;
}
case static::CHANGE_DELETED: {
// Non-recursive delete
$object = $this->getObjectInStage(Versioned::LIVE);
$object->deleteFromStage(Versioned::LIVE);
break;
}
case static::CHANGE_MODIFIED:
case static::CHANGE_CREATED: {
// Non-recursive publish
$object = $this->getObjectInStage(Versioned::DRAFT);
$object->publishSingle();
// Point after version to the published version actually created, not the
// version copied from draft.
$this->VersionAfter = Versioned::get_versionnumber_by_stage(
$this->ObjectClass,
Versioned::LIVE,
$this->ObjectID,
false
);
break;
}
default:
throw new LogicException("Invalid change type: {$changeType}");
}
$this->write();
} | php | public function publish()
{
if (!class_exists($this->ObjectClass)) {
throw new UnexpectedDataException("Invalid Class '{$this->ObjectClass}' in ChangeSetItem #{$this->ID}");
}
// Logical checks prior to publish
if ($this->VersionBefore || $this->VersionAfter) {
throw new BadMethodCallException("This ChangeSetItem has already been published");
}
// Skip unversioned records
if (!$this->isVersioned()) {
$this->VersionBefore = 0;
$this->VersionAfter = 0;
$this->write();
return;
}
// Record state changed
$this->VersionAfter = Versioned::get_versionnumber_by_stage(
$this->ObjectClass,
Versioned::DRAFT,
$this->ObjectID,
false
);
$this->VersionBefore = Versioned::get_versionnumber_by_stage(
$this->ObjectClass,
Versioned::LIVE,
$this->ObjectID,
false
);
// Enact change
$changeType = $this->getChangeType();
switch ($changeType) {
case static::CHANGE_NONE: {
break;
}
case static::CHANGE_DELETED: {
// Non-recursive delete
$object = $this->getObjectInStage(Versioned::LIVE);
$object->deleteFromStage(Versioned::LIVE);
break;
}
case static::CHANGE_MODIFIED:
case static::CHANGE_CREATED: {
// Non-recursive publish
$object = $this->getObjectInStage(Versioned::DRAFT);
$object->publishSingle();
// Point after version to the published version actually created, not the
// version copied from draft.
$this->VersionAfter = Versioned::get_versionnumber_by_stage(
$this->ObjectClass,
Versioned::LIVE,
$this->ObjectID,
false
);
break;
}
default:
throw new LogicException("Invalid change type: {$changeType}");
}
$this->write();
} | [
"public",
"function",
"publish",
"(",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"this",
"->",
"ObjectClass",
")",
")",
"{",
"throw",
"new",
"UnexpectedDataException",
"(",
"\"Invalid Class '{$this->ObjectClass}' in ChangeSetItem #{$this->ID}\"",
")",
";",
... | Publish this item, then close it.
Note: Unlike Versioned::doPublish() and Versioned::doUnpublish, this action is not recursive. | [
"Publish",
"this",
"item",
"then",
"close",
"it",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L258-L324 | train |
silverstripe/silverstripe-versioned | src/ChangeSetItem.php | ChangeSetItem.canRevert | public function canRevert($member)
{
// No action for unversiond objects so no action to deny
if (!$this->isVersioned()) {
return true;
}
// Just get the best version as this object may not even exist on either stage anymore.
/** @var Versioned|DataObject $object */
$object = $this->getObjectLatestVersion();
if (!$object) {
return false;
}
// Check change type
switch ($this->getChangeType()) {
case static::CHANGE_CREATED: {
// Revert creation by deleting from stage
return $object->canDelete($member);
}
default: {
// All other actions are typically editing draft stage
return $object->canEdit($member);
}
}
} | php | public function canRevert($member)
{
// No action for unversiond objects so no action to deny
if (!$this->isVersioned()) {
return true;
}
// Just get the best version as this object may not even exist on either stage anymore.
/** @var Versioned|DataObject $object */
$object = $this->getObjectLatestVersion();
if (!$object) {
return false;
}
// Check change type
switch ($this->getChangeType()) {
case static::CHANGE_CREATED: {
// Revert creation by deleting from stage
return $object->canDelete($member);
}
default: {
// All other actions are typically editing draft stage
return $object->canEdit($member);
}
}
} | [
"public",
"function",
"canRevert",
"(",
"$",
"member",
")",
"{",
"// No action for unversiond objects so no action to deny",
"if",
"(",
"!",
"$",
"this",
"->",
"isVersioned",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"// Just get the best version as this object ... | Check if the BeforeVersion of this changeset can be restored to draft
@param Member $member
@return bool | [
"Check",
"if",
"the",
"BeforeVersion",
"of",
"this",
"changeset",
"can",
"be",
"restored",
"to",
"draft"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L370-L395 | train |
silverstripe/silverstripe-versioned | src/ChangeSetItem.php | ChangeSetItem.canPublish | public function canPublish($member = null)
{
// No action for unversiond objects so no action to deny
// Implicitly added items allow publish
if (!$this->isVersioned() || $this->Added === self::IMPLICITLY) {
return true;
}
// Check canMethod to invoke on object
switch ($this->getChangeType()) {
case static::CHANGE_DELETED: {
/** @var Versioned|DataObject $object */
$object = Versioned::get_by_stage($this->ObjectClass, Versioned::LIVE)->byID($this->ObjectID);
if ($object) {
return $object->canUnpublish($member);
}
break;
}
default: {
/** @var Versioned|DataObject $object */
$object = Versioned::get_by_stage($this->ObjectClass, Versioned::DRAFT)->byID($this->ObjectID);
if ($object) {
return $object->canPublish($member);
}
break;
}
}
return true;
} | php | public function canPublish($member = null)
{
// No action for unversiond objects so no action to deny
// Implicitly added items allow publish
if (!$this->isVersioned() || $this->Added === self::IMPLICITLY) {
return true;
}
// Check canMethod to invoke on object
switch ($this->getChangeType()) {
case static::CHANGE_DELETED: {
/** @var Versioned|DataObject $object */
$object = Versioned::get_by_stage($this->ObjectClass, Versioned::LIVE)->byID($this->ObjectID);
if ($object) {
return $object->canUnpublish($member);
}
break;
}
default: {
/** @var Versioned|DataObject $object */
$object = Versioned::get_by_stage($this->ObjectClass, Versioned::DRAFT)->byID($this->ObjectID);
if ($object) {
return $object->canPublish($member);
}
break;
}
}
return true;
} | [
"public",
"function",
"canPublish",
"(",
"$",
"member",
"=",
"null",
")",
"{",
"// No action for unversiond objects so no action to deny",
"// Implicitly added items allow publish",
"if",
"(",
"!",
"$",
"this",
"->",
"isVersioned",
"(",
")",
"||",
"$",
"this",
"->",
... | Check if this ChangeSetItem can be published
@param Member $member
@return bool | [
"Check",
"if",
"this",
"ChangeSetItem",
"can",
"be",
"published"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L403-L432 | train |
silverstripe/silverstripe-versioned | src/ChangeSetItem.php | ChangeSetItem.can | public function can($perm, $member = null, $context = [])
{
if (!$member) {
$member = Security::getCurrentUser();
}
// Allow extensions to bypass default permissions, but only if
// each change can be individually published.
$extended = $this->extendedCan($perm, $member, $context);
if ($extended !== null) {
return $extended;
}
// Default permissions
return (bool)Permission::checkMember($member, ChangeSet::config()->get('required_permission'));
} | php | public function can($perm, $member = null, $context = [])
{
if (!$member) {
$member = Security::getCurrentUser();
}
// Allow extensions to bypass default permissions, but only if
// each change can be individually published.
$extended = $this->extendedCan($perm, $member, $context);
if ($extended !== null) {
return $extended;
}
// Default permissions
return (bool)Permission::checkMember($member, ChangeSet::config()->get('required_permission'));
} | [
"public",
"function",
"can",
"(",
"$",
"perm",
",",
"$",
"member",
"=",
"null",
",",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"member",
")",
"{",
"$",
"member",
"=",
"Security",
"::",
"getCurrentUser",
"(",
")",
";",
"}",
"... | Default permissions for this ChangeSetItem
@param string $perm
@param Member $member
@param array $context
@return bool | [
"Default",
"permissions",
"for",
"this",
"ChangeSetItem"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L452-L467 | train |
silverstripe/silverstripe-versioned | src/ChangeSetItem.php | ChangeSetItem.getPreviewLinks | public function getPreviewLinks()
{
$links = [];
// Preview draft
$stage = $this->getObjectInStage(Versioned::DRAFT);
if ($stage instanceof CMSPreviewable && $stage->canView() && ($link = $stage->PreviewLink())) {
$links[Versioned::DRAFT] = [
'href' => Controller::join_links($link, '?stage=' . Versioned::DRAFT),
'type' => $stage->getMimeType(),
];
}
// Preview live if versioned
if ($this->isVersioned()) {
$live = $this->getObjectInStage(Versioned::LIVE);
if ($live instanceof CMSPreviewable && $live->canView() && ($link = $live->PreviewLink())) {
$links[Versioned::LIVE] = [
'href' => Controller::join_links($link, '?stage=' . Versioned::LIVE),
'type' => $live->getMimeType(),
];
}
}
return $links;
} | php | public function getPreviewLinks()
{
$links = [];
// Preview draft
$stage = $this->getObjectInStage(Versioned::DRAFT);
if ($stage instanceof CMSPreviewable && $stage->canView() && ($link = $stage->PreviewLink())) {
$links[Versioned::DRAFT] = [
'href' => Controller::join_links($link, '?stage=' . Versioned::DRAFT),
'type' => $stage->getMimeType(),
];
}
// Preview live if versioned
if ($this->isVersioned()) {
$live = $this->getObjectInStage(Versioned::LIVE);
if ($live instanceof CMSPreviewable && $live->canView() && ($link = $live->PreviewLink())) {
$links[Versioned::LIVE] = [
'href' => Controller::join_links($link, '?stage=' . Versioned::LIVE),
'type' => $live->getMimeType(),
];
}
}
return $links;
} | [
"public",
"function",
"getPreviewLinks",
"(",
")",
"{",
"$",
"links",
"=",
"[",
"]",
";",
"// Preview draft",
"$",
"stage",
"=",
"$",
"this",
"->",
"getObjectInStage",
"(",
"Versioned",
"::",
"DRAFT",
")",
";",
"if",
"(",
"$",
"stage",
"instanceof",
"CMS... | Gets the list of modes this record can be previewed in.
{@link https://tools.ietf.org/html/draft-kelly-json-hal-07#section-5}
@return array Map of links in acceptable HAL format | [
"Gets",
"the",
"list",
"of",
"modes",
"this",
"record",
"can",
"be",
"previewed",
"in",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L509-L534 | train |
silverstripe/silverstripe-versioned | src/ChangeSetItem.php | ChangeSetItem.CMSEditLink | public function CMSEditLink()
{
$link = $this->getObjectInStage(Versioned::DRAFT);
if ($link instanceof CMSPreviewable) {
return $link->CMSEditLink();
}
return null;
} | php | public function CMSEditLink()
{
$link = $this->getObjectInStage(Versioned::DRAFT);
if ($link instanceof CMSPreviewable) {
return $link->CMSEditLink();
}
return null;
} | [
"public",
"function",
"CMSEditLink",
"(",
")",
"{",
"$",
"link",
"=",
"$",
"this",
"->",
"getObjectInStage",
"(",
"Versioned",
"::",
"DRAFT",
")",
";",
"if",
"(",
"$",
"link",
"instanceof",
"CMSPreviewable",
")",
"{",
"return",
"$",
"link",
"->",
"CMSEdi... | Get edit link for this item
@return string | [
"Get",
"edit",
"link",
"for",
"this",
"item"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L541-L548 | train |
silverstripe/silverstripe-versioned | src/ChangeSetItem.php | ChangeSetItem.isVersioned | public function isVersioned()
{
if (!$this->ObjectClass || !class_exists($this->ObjectClass)) {
return false;
}
/** @var Versioned|DataObject $singleton */
$singleton = DataObject::singleton($this->ObjectClass);
return $singleton->hasExtension(Versioned::class) && $singleton->hasStages();
} | php | public function isVersioned()
{
if (!$this->ObjectClass || !class_exists($this->ObjectClass)) {
return false;
}
/** @var Versioned|DataObject $singleton */
$singleton = DataObject::singleton($this->ObjectClass);
return $singleton->hasExtension(Versioned::class) && $singleton->hasStages();
} | [
"public",
"function",
"isVersioned",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"ObjectClass",
"||",
"!",
"class_exists",
"(",
"$",
"this",
"->",
"ObjectClass",
")",
")",
"{",
"return",
"false",
";",
"}",
"/** @var Versioned|DataObject $singleton */",
... | Check if the object attached to this changesetitem is versionable
@return bool | [
"Check",
"if",
"the",
"object",
"attached",
"to",
"this",
"changesetitem",
"is",
"versionable"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L555-L563 | train |
silverstripe/silverstripe-versioned | src/GraphQL/Extensions/ManagerExtension.php | ManagerExtension.updateConfig | public function updateConfig(&$config)
{
if (!isset($config['types'])) {
$config['types'] = [];
}
$config['types']['VersionedStage'] = VersionedStage::class;
$config['types']['VersionedStatus'] = VersionedStatus::class;
$config['types']['VersionedQueryMode'] = VersionedQueryMode::class;
$config['types']['VersionedInputType'] = VersionedInputType::class;
$config['types']['CopyToStageInputType'] = CopyToStageInputType::class;
} | php | public function updateConfig(&$config)
{
if (!isset($config['types'])) {
$config['types'] = [];
}
$config['types']['VersionedStage'] = VersionedStage::class;
$config['types']['VersionedStatus'] = VersionedStatus::class;
$config['types']['VersionedQueryMode'] = VersionedQueryMode::class;
$config['types']['VersionedInputType'] = VersionedInputType::class;
$config['types']['CopyToStageInputType'] = CopyToStageInputType::class;
} | [
"public",
"function",
"updateConfig",
"(",
"&",
"$",
"config",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"config",
"[",
"'types'",
"]",
")",
")",
"{",
"$",
"config",
"[",
"'types'",
"]",
"=",
"[",
"]",
";",
"}",
"$",
"config",
"[",
"'types'",
... | Adds the versioned types to all schemas
@param $config | [
"Adds",
"the",
"versioned",
"types",
"to",
"all",
"schemas"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/GraphQL/Extensions/ManagerExtension.php#L19-L30 | train |
silverstripe/silverstripe-versioned | src/Caching/ProxyCacheAdapter.php | ProxyCacheAdapter.getKeyIDs | protected function getKeyIDs($keys)
{
// Force iterator to array with simple temp array
$map = [];
foreach ($keys as $key) {
$map[] = $this->getKeyID($key);
}
return $map;
} | php | protected function getKeyIDs($keys)
{
// Force iterator to array with simple temp array
$map = [];
foreach ($keys as $key) {
$map[] = $this->getKeyID($key);
}
return $map;
} | [
"protected",
"function",
"getKeyIDs",
"(",
"$",
"keys",
")",
"{",
"// Force iterator to array with simple temp array",
"$",
"map",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"key",
")",
"{",
"$",
"map",
"[",
"]",
"=",
"$",
"this",
"->",
... | Get key ids
@param iterable $keys
@return array Array where keys are passed in $keys, and values are key IDs | [
"Get",
"key",
"ids"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Caching/ProxyCacheAdapter.php#L163-L171 | train |
silverstripe/silverstripe-versioned | src/Caching/ProxyCacheAdapter.php | ProxyCacheAdapter.iteratorToArray | protected function iteratorToArray($keys)
{
// Already array
if (is_array($keys)) {
return $keys;
}
// Handle iterable
if ($keys instanceof Traversable) {
return iterator_to_array($keys, false);
}
// Error
$keysType = is_object($keys) ? get_class($keys) : gettype($keys);
throw new InvalidArgumentException("Cache keys must be array or Traversable, \"{$keysType}\" given");
} | php | protected function iteratorToArray($keys)
{
// Already array
if (is_array($keys)) {
return $keys;
}
// Handle iterable
if ($keys instanceof Traversable) {
return iterator_to_array($keys, false);
}
// Error
$keysType = is_object($keys) ? get_class($keys) : gettype($keys);
throw new InvalidArgumentException("Cache keys must be array or Traversable, \"{$keysType}\" given");
} | [
"protected",
"function",
"iteratorToArray",
"(",
"$",
"keys",
")",
"{",
"// Already array",
"if",
"(",
"is_array",
"(",
"$",
"keys",
")",
")",
"{",
"return",
"$",
"keys",
";",
"}",
"// Handle iterable",
"if",
"(",
"$",
"keys",
"instanceof",
"Traversable",
... | Ensure that a list is cast to an array
@param iterable $keys
@return array | [
"Ensure",
"that",
"a",
"list",
"is",
"cast",
"to",
"an",
"array"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Caching/ProxyCacheAdapter.php#L179-L194 | train |
silverstripe/silverstripe-versioned | src/GraphQL/Extensions/SchemaScaffolderExtension.php | SchemaScaffolderExtension.onBeforeAddToManager | public function onBeforeAddToManager(Manager $manager)
{
$memberType = StaticSchema::inst()->typeNameForDataObject(Member::class);
if ($manager->hasType($memberType)) {
return;
}
/* @var SchemaScaffolder $owner */
$owner = $this->owner;
foreach ($owner->getTypes() as $scaffold) {
if ($scaffold->getDataObjectInstance()->hasExtension(Versioned::class)) {
$owner->type(Member::class);
break;
}
}
} | php | public function onBeforeAddToManager(Manager $manager)
{
$memberType = StaticSchema::inst()->typeNameForDataObject(Member::class);
if ($manager->hasType($memberType)) {
return;
}
/* @var SchemaScaffolder $owner */
$owner = $this->owner;
foreach ($owner->getTypes() as $scaffold) {
if ($scaffold->getDataObjectInstance()->hasExtension(Versioned::class)) {
$owner->type(Member::class);
break;
}
}
} | [
"public",
"function",
"onBeforeAddToManager",
"(",
"Manager",
"$",
"manager",
")",
"{",
"$",
"memberType",
"=",
"StaticSchema",
"::",
"inst",
"(",
")",
"->",
"typeNameForDataObject",
"(",
"Member",
"::",
"class",
")",
";",
"if",
"(",
"$",
"manager",
"->",
... | If any types are using Versioned, make sure Member is added as a type. Because
the Versioned_Version object is just ViewableData, it has to be added explicitly.
@param Manager $manager | [
"If",
"any",
"types",
"are",
"using",
"Versioned",
"make",
"sure",
"Member",
"is",
"added",
"as",
"a",
"type",
".",
"Because",
"the",
"Versioned_Version",
"object",
"is",
"just",
"ViewableData",
"it",
"has",
"to",
"be",
"added",
"explicitly",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/GraphQL/Extensions/SchemaScaffolderExtension.php#L20-L36 | train |
silverstripe/silverstripe-versioned | src/GridFieldRestoreAction.php | GridFieldRestoreAction.getRestoreAction | public function getRestoreAction($gridField, $record, $columnName)
{
$canRestoreToDraft = $record->canRestoreToDraft();
if ($canRestoreToDraft) {
$restoreToRoot = RestoreAction::shouldRestoreToRoot($record);
$title = $restoreToRoot
? _t('SilverStripe\\Versioned\\RestoreAction.RESTORE_TO_ROOT', 'Restore to draft at top level')
: _t('SilverStripe\\Versioned\\RestoreAction.RESTORE', 'Restore to draft');
$description = $restoreToRoot
? _t('SilverStripe\\Versioned\\RestoreAction.RESTORE_TO_ROOT_DESC', 'Restore the archived version to draft as a top level item')
: _t('SilverStripe\\Versioned\\RestoreAction.RESTORE_DESC', 'Restore the archived version to draft');
$field = GridField_FormAction::create(
$gridField,
'Restore' . $record->ID,
false,
"restore",
['RecordID' => $record->ID]
)
->addExtraClass('btn btn--no-text btn--icon-md font-icon-back-in-time grid-field__icon-action action-menu--handled action-restore')
->setAttribute('classNames', 'font-icon-back-in-time action-restore')
->setAttribute('data-to-root', $restoreToRoot)
->setDescription($description)
->setAttribute('aria-label', $title);
}
return isset($field) ? $field : null;
} | php | public function getRestoreAction($gridField, $record, $columnName)
{
$canRestoreToDraft = $record->canRestoreToDraft();
if ($canRestoreToDraft) {
$restoreToRoot = RestoreAction::shouldRestoreToRoot($record);
$title = $restoreToRoot
? _t('SilverStripe\\Versioned\\RestoreAction.RESTORE_TO_ROOT', 'Restore to draft at top level')
: _t('SilverStripe\\Versioned\\RestoreAction.RESTORE', 'Restore to draft');
$description = $restoreToRoot
? _t('SilverStripe\\Versioned\\RestoreAction.RESTORE_TO_ROOT_DESC', 'Restore the archived version to draft as a top level item')
: _t('SilverStripe\\Versioned\\RestoreAction.RESTORE_DESC', 'Restore the archived version to draft');
$field = GridField_FormAction::create(
$gridField,
'Restore' . $record->ID,
false,
"restore",
['RecordID' => $record->ID]
)
->addExtraClass('btn btn--no-text btn--icon-md font-icon-back-in-time grid-field__icon-action action-menu--handled action-restore')
->setAttribute('classNames', 'font-icon-back-in-time action-restore')
->setAttribute('data-to-root', $restoreToRoot)
->setDescription($description)
->setAttribute('aria-label', $title);
}
return isset($field) ? $field : null;
} | [
"public",
"function",
"getRestoreAction",
"(",
"$",
"gridField",
",",
"$",
"record",
",",
"$",
"columnName",
")",
"{",
"$",
"canRestoreToDraft",
"=",
"$",
"record",
"->",
"canRestoreToDraft",
"(",
")",
";",
"if",
"(",
"$",
"canRestoreToDraft",
")",
"{",
"$... | Creates a restore action if the action is able to be preformed
@param GridField $gridField
@param DataObject $record
@param string $columnName
@return GridField_FormAction|null | [
"Creates",
"a",
"restore",
"action",
"if",
"the",
"action",
"is",
"able",
"to",
"be",
"preformed"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/GridFieldRestoreAction.php#L121-L150 | train |
silverstripe/silverstripe-versioned | src/GridFieldRestoreAction.php | GridFieldRestoreAction.handleAction | public function handleAction(GridField $gridField, $actionName, $arguments, $data)
{
if ($actionName == 'restore') {
/** @var DataObject $item */
$item = $gridField->getList()->byID($arguments['RecordID']);
if (!$item) {
return;
}
$message = RestoreAction::restore($item);
// If this is handled in a form context then show a message
if ($message && $controller = $gridField->form->controller) {
$controller->getResponse()->addHeader('X-Message-Text', $message['text']);
$controller->getResponse()->addHeader('X-Message-Type', $message['type']);
}
$gridField->getList()->remove($item);
}
} | php | public function handleAction(GridField $gridField, $actionName, $arguments, $data)
{
if ($actionName == 'restore') {
/** @var DataObject $item */
$item = $gridField->getList()->byID($arguments['RecordID']);
if (!$item) {
return;
}
$message = RestoreAction::restore($item);
// If this is handled in a form context then show a message
if ($message && $controller = $gridField->form->controller) {
$controller->getResponse()->addHeader('X-Message-Text', $message['text']);
$controller->getResponse()->addHeader('X-Message-Type', $message['type']);
}
$gridField->getList()->remove($item);
}
} | [
"public",
"function",
"handleAction",
"(",
"GridField",
"$",
"gridField",
",",
"$",
"actionName",
",",
"$",
"arguments",
",",
"$",
"data",
")",
"{",
"if",
"(",
"$",
"actionName",
"==",
"'restore'",
")",
"{",
"/** @var DataObject $item */",
"$",
"item",
"=",
... | Handle the actions and apply any changes to the GridField.
@param GridField $gridField
@param string $actionName
@param mixed $arguments
@param array $data - form data
@return void | [
"Handle",
"the",
"actions",
"and",
"apply",
"any",
"changes",
"to",
"the",
"GridField",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/GridFieldRestoreAction.php#L175-L194 | train |
silverstripe/silverstripe-versioned | src/RestoreAction.php | RestoreAction.shouldRestoreToRoot | public static function shouldRestoreToRoot($record)
{
// If the record had a parent and that no longer exists in draft then yes
if ($record->hasExtension(Hierarchy::class) && $record->ParentID != false) {
return $record->getParent() === null;
}
// Otherwise it should be restored normally
return false;
} | php | public static function shouldRestoreToRoot($record)
{
// If the record had a parent and that no longer exists in draft then yes
if ($record->hasExtension(Hierarchy::class) && $record->ParentID != false) {
return $record->getParent() === null;
}
// Otherwise it should be restored normally
return false;
} | [
"public",
"static",
"function",
"shouldRestoreToRoot",
"(",
"$",
"record",
")",
"{",
"// If the record had a parent and that no longer exists in draft then yes",
"if",
"(",
"$",
"record",
"->",
"hasExtension",
"(",
"Hierarchy",
"::",
"class",
")",
"&&",
"$",
"record",
... | Determines whether this record can be restored to it's original location
@param $record
@return bool | [
"Determines",
"whether",
"this",
"record",
"can",
"be",
"restored",
"to",
"it",
"s",
"original",
"location"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/RestoreAction.php#L157-L166 | train |
silverstripe/silverstripe-versioned | src/GraphQL/Resolvers/ApplyVersionFilters.php | ApplyVersionFilters.isValidDate | protected function isValidDate($date)
{
$dt = DateTime::createFromFormat('Y-m-d', $date);
return ($dt !== false && !array_sum($dt->getLastErrors()));
} | php | protected function isValidDate($date)
{
$dt = DateTime::createFromFormat('Y-m-d', $date);
return ($dt !== false && !array_sum($dt->getLastErrors()));
} | [
"protected",
"function",
"isValidDate",
"(",
"$",
"date",
")",
"{",
"$",
"dt",
"=",
"DateTime",
"::",
"createFromFormat",
"(",
"'Y-m-d'",
",",
"$",
"date",
")",
";",
"return",
"(",
"$",
"dt",
"!==",
"false",
"&&",
"!",
"array_sum",
"(",
"$",
"dt",
"-... | Returns true if date is in proper YYYY-MM-DD format
@param string $date
@return bool | [
"Returns",
"true",
"if",
"date",
"is",
"in",
"proper",
"YYYY",
"-",
"MM",
"-",
"DD",
"format"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/GraphQL/Resolvers/ApplyVersionFilters.php#L144-L149 | train |
silverstripe/silverstripe-versioned | src/RecursivePublishable.php | RecursivePublishable.publishRecursive | public function publishRecursive()
{
// Create a new changeset for this item and publish it
$changeset = ChangeSet::create();
$changeset->IsInferred = true;
$changeset->Name = _t(
__CLASS__ . '.INFERRED_TITLE',
"Generated by publish of '{title}' at {created}",
[
'title' => $this->owner->Title,
'created' => DBDatetime::now()->Nice()
]
);
$changeset->write();
$changeset->addObject($this->owner);
return $changeset->publish(true);
} | php | public function publishRecursive()
{
// Create a new changeset for this item and publish it
$changeset = ChangeSet::create();
$changeset->IsInferred = true;
$changeset->Name = _t(
__CLASS__ . '.INFERRED_TITLE',
"Generated by publish of '{title}' at {created}",
[
'title' => $this->owner->Title,
'created' => DBDatetime::now()->Nice()
]
);
$changeset->write();
$changeset->addObject($this->owner);
return $changeset->publish(true);
} | [
"public",
"function",
"publishRecursive",
"(",
")",
"{",
"// Create a new changeset for this item and publish it",
"$",
"changeset",
"=",
"ChangeSet",
"::",
"create",
"(",
")",
";",
"$",
"changeset",
"->",
"IsInferred",
"=",
"true",
";",
"$",
"changeset",
"->",
"N... | Publish this object and all owned objects to Live
@return bool | [
"Publish",
"this",
"object",
"and",
"all",
"owned",
"objects",
"to",
"Live"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/RecursivePublishable.php#L58-L74 | train |
silverstripe/silverstripe-versioned | src/RecursivePublishable.php | RecursivePublishable.rollbackRelations | public function rollbackRelations($version)
{
$owner = $this->owner;
// Rollback recursively
foreach ($owner->findOwned(false) as $object) {
if ($object->hasExtension(Versioned::class)) {
// Pass in null to rollback to self version
/** @var Versioned $object */
$object->rollbackRecursive(null);
} else {
// Rollback unversioned record (inherits parent query parameters)
$object->rollbackRelations($version);
}
}
} | php | public function rollbackRelations($version)
{
$owner = $this->owner;
// Rollback recursively
foreach ($owner->findOwned(false) as $object) {
if ($object->hasExtension(Versioned::class)) {
// Pass in null to rollback to self version
/** @var Versioned $object */
$object->rollbackRecursive(null);
} else {
// Rollback unversioned record (inherits parent query parameters)
$object->rollbackRelations($version);
}
}
} | [
"public",
"function",
"rollbackRelations",
"(",
"$",
"version",
")",
"{",
"$",
"owner",
"=",
"$",
"this",
"->",
"owner",
";",
"// Rollback recursively",
"foreach",
"(",
"$",
"owner",
"->",
"findOwned",
"(",
"false",
")",
"as",
"$",
"object",
")",
"{",
"i... | Rollback all related objects on this stage.
Note: This method should be called on the source object queried in the appropriate "from"
for this rollback, as it will rely on the parent object's query parameters to return
nested objects.
@internal Do not call this directly! This should only be invoked by Versioned::rollbackRecursive()
@param int|string $version Parent version / stage to rollback from | [
"Rollback",
"all",
"related",
"objects",
"on",
"this",
"stage",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/RecursivePublishable.php#L86-L100 | train |
silverstripe/silverstripe-versioned | src/RecursivePublishable.php | RecursivePublishable.deleteFromChangeSets | public function deleteFromChangeSets()
{
$changeSetIDs = [];
// Remove all ChangeSetItems matching this record
/** @var ChangeSetItem $changeSetItem */
foreach (ChangeSetItem::get_for_object($this->owner) as $changeSetItem) {
$changeSetIDs[$changeSetItem->ChangeSetID] = $changeSetItem->ChangeSetID;
$changeSetItem->delete();
}
// Sync all affected changesets
if ($changeSetIDs) {
/** @var ChangeSet $changeSet */
foreach (ChangeSet::get()->byIDs($changeSetIDs) as $changeSet) {
$changeSet->sync();
}
}
return true;
} | php | public function deleteFromChangeSets()
{
$changeSetIDs = [];
// Remove all ChangeSetItems matching this record
/** @var ChangeSetItem $changeSetItem */
foreach (ChangeSetItem::get_for_object($this->owner) as $changeSetItem) {
$changeSetIDs[$changeSetItem->ChangeSetID] = $changeSetItem->ChangeSetID;
$changeSetItem->delete();
}
// Sync all affected changesets
if ($changeSetIDs) {
/** @var ChangeSet $changeSet */
foreach (ChangeSet::get()->byIDs($changeSetIDs) as $changeSet) {
$changeSet->sync();
}
}
return true;
} | [
"public",
"function",
"deleteFromChangeSets",
"(",
")",
"{",
"$",
"changeSetIDs",
"=",
"[",
"]",
";",
"// Remove all ChangeSetItems matching this record",
"/** @var ChangeSetItem $changeSetItem */",
"foreach",
"(",
"ChangeSetItem",
"::",
"get_for_object",
"(",
"$",
"this",
... | Remove this item from any changesets
@return bool | [
"Remove",
"this",
"item",
"from",
"any",
"changesets"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/RecursivePublishable.php#L107-L126 | train |
silverstripe/silverstripe-versioned | src/RecursivePublishable.php | RecursivePublishable.findOwned | public function findOwned($recursive = true, $list = null)
{
// Find objects in these relationships
return $this->owner->findRelatedObjects('owns', $recursive, $list);
} | php | public function findOwned($recursive = true, $list = null)
{
// Find objects in these relationships
return $this->owner->findRelatedObjects('owns', $recursive, $list);
} | [
"public",
"function",
"findOwned",
"(",
"$",
"recursive",
"=",
"true",
",",
"$",
"list",
"=",
"null",
")",
"{",
"// Find objects in these relationships",
"return",
"$",
"this",
"->",
"owner",
"->",
"findRelatedObjects",
"(",
"'owns'",
",",
"$",
"recursive",
",... | Find all objects owned by the current object.
Note that objects will only be searched in the same stage as the given record.
@param bool $recursive True if recursive
@param ArrayList $list Optional list to add items to
@return ArrayList list of objects | [
"Find",
"all",
"objects",
"owned",
"by",
"the",
"current",
"object",
".",
"Note",
"that",
"objects",
"will",
"only",
"be",
"searched",
"in",
"the",
"same",
"stage",
"as",
"the",
"given",
"record",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/RecursivePublishable.php#L136-L140 | train |
silverstripe/silverstripe-versioned | src/RecursivePublishable.php | RecursivePublishable.hasOwned | public function hasOwned()
{
if (!$this->owner->isInDB()) {
return false;
}
$ownedRelationships = $this->owner->config()->get('owns') ?: [];
foreach ($ownedRelationships as $relationship) {
/* @var DataObject|SS_List $result */
$result = $this->owner->{$relationship}();
if ($result->exists()) {
return true;
}
}
return false;
} | php | public function hasOwned()
{
if (!$this->owner->isInDB()) {
return false;
}
$ownedRelationships = $this->owner->config()->get('owns') ?: [];
foreach ($ownedRelationships as $relationship) {
/* @var DataObject|SS_List $result */
$result = $this->owner->{$relationship}();
if ($result->exists()) {
return true;
}
}
return false;
} | [
"public",
"function",
"hasOwned",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"owner",
"->",
"isInDB",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"ownedRelationships",
"=",
"$",
"this",
"->",
"owner",
"->",
"config",
"(",
")",
"->"... | Returns true if the record has any owned relationships that exist
@return bool | [
"Returns",
"true",
"if",
"the",
"record",
"has",
"any",
"owned",
"relationships",
"that",
"exist"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/RecursivePublishable.php#L146-L162 | train |
silverstripe/silverstripe-versioned | src/RecursivePublishable.php | RecursivePublishable.lookupReverseOwners | protected function lookupReverseOwners()
{
// Find all classes with 'owns' config
$lookup = [];
$classes = ClassInfo::subclassesFor(DataObject::class);
array_shift($classes); // skip DataObject
foreach ($classes as $class) {
// Ensure this class is RecursivePublishable
if (!DataObject::has_extension($class, static::class)) {
continue;
}
// Check owned objects for this class
$owns = Config::inst()->get($class, 'owns', Config::UNINHERITED);
if (empty($owns)) {
continue;
}
$instance = DataObject::singleton($class);
foreach ($owns as $owned) {
// Find owned class
$ownedClass = $instance->getRelationClass($owned);
// Skip custom methods that don't have db relations, or cannot be inferred
if (!$ownedClass || $ownedClass === DataObject::class) {
continue;
}
// Add lookup for owned class
if (!isset($lookup[$ownedClass])) {
$lookup[$ownedClass] = [];
}
$lookup[$ownedClass][] = [
'class' => $class,
'relation' => $owned
];
}
}
return $lookup;
} | php | protected function lookupReverseOwners()
{
// Find all classes with 'owns' config
$lookup = [];
$classes = ClassInfo::subclassesFor(DataObject::class);
array_shift($classes); // skip DataObject
foreach ($classes as $class) {
// Ensure this class is RecursivePublishable
if (!DataObject::has_extension($class, static::class)) {
continue;
}
// Check owned objects for this class
$owns = Config::inst()->get($class, 'owns', Config::UNINHERITED);
if (empty($owns)) {
continue;
}
$instance = DataObject::singleton($class);
foreach ($owns as $owned) {
// Find owned class
$ownedClass = $instance->getRelationClass($owned);
// Skip custom methods that don't have db relations, or cannot be inferred
if (!$ownedClass || $ownedClass === DataObject::class) {
continue;
}
// Add lookup for owned class
if (!isset($lookup[$ownedClass])) {
$lookup[$ownedClass] = [];
}
$lookup[$ownedClass][] = [
'class' => $class,
'relation' => $owned
];
}
}
return $lookup;
} | [
"protected",
"function",
"lookupReverseOwners",
"(",
")",
"{",
"// Find all classes with 'owns' config",
"$",
"lookup",
"=",
"[",
"]",
";",
"$",
"classes",
"=",
"ClassInfo",
"::",
"subclassesFor",
"(",
"DataObject",
"::",
"class",
")",
";",
"array_shift",
"(",
"... | Find a list of classes, each of which with a list of methods to invoke
to lookup owners.
@return array | [
"Find",
"a",
"list",
"of",
"classes",
"each",
"of",
"which",
"with",
"a",
"list",
"of",
"methods",
"to",
"invoke",
"to",
"lookup",
"owners",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/RecursivePublishable.php#L239-L277 | train |
silverstripe/silverstripe-versioned | src/RecursivePublishable.php | RecursivePublishable.onBeforeDuplicate | public function onBeforeDuplicate($original, &$doWrite, &$relations)
{
// If relations to duplicate are declared (or forced off) don't rewrite
if ($relations || $relations === false) {
return;
}
// Only duplicate owned relationships that are either exclusively owned,
// or require additional writes. Also exclude any custom non-relation ownerships.
$allowed = array_merge(
array_keys($this->owner->manyMany()), // Require mapping table duplications
array_keys($this->owner->belongsTo()), // Exclusive record must be duplicated
array_keys($this->owner->hasMany()) // Exclusive records should be duplicated
);
// Note: don't assume that owned has_one needs duplication, as these can be
// shared non-exclusively by both clone and original.
// Get candidates from ownership and intersect
$owns = $this->owner->config()->get('owns');
$relations = array_intersect($allowed, $owns);
} | php | public function onBeforeDuplicate($original, &$doWrite, &$relations)
{
// If relations to duplicate are declared (or forced off) don't rewrite
if ($relations || $relations === false) {
return;
}
// Only duplicate owned relationships that are either exclusively owned,
// or require additional writes. Also exclude any custom non-relation ownerships.
$allowed = array_merge(
array_keys($this->owner->manyMany()), // Require mapping table duplications
array_keys($this->owner->belongsTo()), // Exclusive record must be duplicated
array_keys($this->owner->hasMany()) // Exclusive records should be duplicated
);
// Note: don't assume that owned has_one needs duplication, as these can be
// shared non-exclusively by both clone and original.
// Get candidates from ownership and intersect
$owns = $this->owner->config()->get('owns');
$relations = array_intersect($allowed, $owns);
} | [
"public",
"function",
"onBeforeDuplicate",
"(",
"$",
"original",
",",
"&",
"$",
"doWrite",
",",
"&",
"$",
"relations",
")",
"{",
"// If relations to duplicate are declared (or forced off) don't rewrite",
"if",
"(",
"$",
"relations",
"||",
"$",
"relations",
"===",
"f... | If `cascade_duplications` is empty, default to `owns` config
@param DataObject $original
@param bool $doWrite
@param array|null|false $relations | [
"If",
"cascade_duplications",
"is",
"empty",
"default",
"to",
"owns",
"config"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/RecursivePublishable.php#L404-L423 | train |
silverstripe/silverstripe-versioned | src/GridFieldArchiveAction.php | GridFieldArchiveAction.augmentColumns | public function augmentColumns($gridField, &$columns)
{
$model = $gridField->getModelClass();
$isModelVersioned = $model::has_extension(Versioned::class);
if ($isModelVersioned) {
$gridField->getConfig()->removeComponentsByType(GridFieldDeleteAction::class);
}
if (!in_array('Actions', $columns)) {
$columns[] = 'Actions';
}
} | php | public function augmentColumns($gridField, &$columns)
{
$model = $gridField->getModelClass();
$isModelVersioned = $model::has_extension(Versioned::class);
if ($isModelVersioned) {
$gridField->getConfig()->removeComponentsByType(GridFieldDeleteAction::class);
}
if (!in_array('Actions', $columns)) {
$columns[] = 'Actions';
}
} | [
"public",
"function",
"augmentColumns",
"(",
"$",
"gridField",
",",
"&",
"$",
"columns",
")",
"{",
"$",
"model",
"=",
"$",
"gridField",
"->",
"getModelClass",
"(",
")",
";",
"$",
"isModelVersioned",
"=",
"$",
"model",
"::",
"has_extension",
"(",
"Versioned... | Add a column 'Actions'
@param GridField $gridField
@param array $columns | [
"Add",
"a",
"column",
"Actions"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/GridFieldArchiveAction.php#L71-L81 | train |
silverstripe/silverstripe-versioned | src/GridFieldArchiveAction.php | GridFieldArchiveAction.getArchiveAction | public function getArchiveAction($gridField, $record)
{
/* @var DataObject|Versioned $record */
if (!$record->hasMethod('canArchive') || !$record->canArchive()) {
return null;
}
$title = _t(__CLASS__ . '.Archive', "Archive");
$field = GridField_FormAction::create(
$gridField,
'ArchiveRecord' . $record->ID,
false,
"archiverecord",
['RecordID' => $record->ID]
)
->addExtraClass('action--archive btn--icon-md font-icon-box btn--no-text grid-field__icon-action action-menu--handled')
->setAttribute('classNames', 'action--archive font-icon-box')
->setDescription($title)
->setAttribute('aria-label', $title);
return $field;
} | php | public function getArchiveAction($gridField, $record)
{
/* @var DataObject|Versioned $record */
if (!$record->hasMethod('canArchive') || !$record->canArchive()) {
return null;
}
$title = _t(__CLASS__ . '.Archive', "Archive");
$field = GridField_FormAction::create(
$gridField,
'ArchiveRecord' . $record->ID,
false,
"archiverecord",
['RecordID' => $record->ID]
)
->addExtraClass('action--archive btn--icon-md font-icon-box btn--no-text grid-field__icon-action action-menu--handled')
->setAttribute('classNames', 'action--archive font-icon-box')
->setDescription($title)
->setAttribute('aria-label', $title);
return $field;
} | [
"public",
"function",
"getArchiveAction",
"(",
"$",
"gridField",
",",
"$",
"record",
")",
"{",
"/* @var DataObject|Versioned $record */",
"if",
"(",
"!",
"$",
"record",
"->",
"hasMethod",
"(",
"'canArchive'",
")",
"||",
"!",
"$",
"record",
"->",
"canArchive",
... | Returns the GridField_FormAction if archive can be performed
@param GridField $gridField
@param DataObject $record
@return GridField_FormAction|null | [
"Returns",
"the",
"GridField_FormAction",
"if",
"archive",
"can",
"be",
"performed"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/GridFieldArchiveAction.php#L187-L209 | train |
silverstripe/silverstripe-versioned | src/GraphQL/Extensions/DataObjectScaffolderExtension.php | DataObjectScaffolderExtension.onBeforeAddToManager | public function onBeforeAddToManager(Manager $manager)
{
/* @var DataObjectScaffolder $owner */
$owner = $this->owner;
$memberType = StaticSchema::inst()->typeNameForDataObject(Member::class);
$instance = $owner->getDataObjectInstance();
$class = $owner->getDataObjectClass();
if (!$instance->hasExtension(Versioned::class)) {
return;
}
/* @var ObjectType $rawType */
$rawType = $owner->scaffold($manager);
$versionName = $this->createVersionedTypeName($class);
$coreFieldsFn = $rawType->config['fields'];
// Create the "version" type for this dataobject. Takes the original fields
// and augments them with the Versioned_Version specific fields
$versionType = new ObjectType([
'name' => $versionName,
'fields' => function () use ($coreFieldsFn, $manager, $memberType) {
$coreFields = $coreFieldsFn();
$versionFields = [
'Author' => [
'type' => $manager->getType($memberType),
'resolve' => function ($obj) {
return $obj->Author();
}
],
'Publisher' => [
'type' => $manager->getType($memberType),
'resolve' => function ($obj) {
return $obj->Publisher();
}
],
'Published' => [
'type' => Type::boolean(),
'resolve' => function ($obj) {
return $obj->WasPublished;
}
],
'LiveVersion' => [
'type' => Type::boolean(),
'resolve' => function ($obj) {
return $obj->isLiveVersion();
}
],
'LatestDraftVersion' => [
'type' => Type::boolean(),
'resolve' => function ($obj) {
return $obj->isLatestDraftVersion();
}
],
];
// Remove this recursive madness.
unset($coreFields['Versions']);
return array_merge($coreFields, $versionFields);
}
]);
$manager->addType($versionType, $versionName);
// With the version type in the manager now, add the versioning fields to the dataobject type
$owner
->addFields(['Version'])
->nestedQuery('Versions', new ReadVersions($class, $versionName));
} | php | public function onBeforeAddToManager(Manager $manager)
{
/* @var DataObjectScaffolder $owner */
$owner = $this->owner;
$memberType = StaticSchema::inst()->typeNameForDataObject(Member::class);
$instance = $owner->getDataObjectInstance();
$class = $owner->getDataObjectClass();
if (!$instance->hasExtension(Versioned::class)) {
return;
}
/* @var ObjectType $rawType */
$rawType = $owner->scaffold($manager);
$versionName = $this->createVersionedTypeName($class);
$coreFieldsFn = $rawType->config['fields'];
// Create the "version" type for this dataobject. Takes the original fields
// and augments them with the Versioned_Version specific fields
$versionType = new ObjectType([
'name' => $versionName,
'fields' => function () use ($coreFieldsFn, $manager, $memberType) {
$coreFields = $coreFieldsFn();
$versionFields = [
'Author' => [
'type' => $manager->getType($memberType),
'resolve' => function ($obj) {
return $obj->Author();
}
],
'Publisher' => [
'type' => $manager->getType($memberType),
'resolve' => function ($obj) {
return $obj->Publisher();
}
],
'Published' => [
'type' => Type::boolean(),
'resolve' => function ($obj) {
return $obj->WasPublished;
}
],
'LiveVersion' => [
'type' => Type::boolean(),
'resolve' => function ($obj) {
return $obj->isLiveVersion();
}
],
'LatestDraftVersion' => [
'type' => Type::boolean(),
'resolve' => function ($obj) {
return $obj->isLatestDraftVersion();
}
],
];
// Remove this recursive madness.
unset($coreFields['Versions']);
return array_merge($coreFields, $versionFields);
}
]);
$manager->addType($versionType, $versionName);
// With the version type in the manager now, add the versioning fields to the dataobject type
$owner
->addFields(['Version'])
->nestedQuery('Versions', new ReadVersions($class, $versionName));
} | [
"public",
"function",
"onBeforeAddToManager",
"(",
"Manager",
"$",
"manager",
")",
"{",
"/* @var DataObjectScaffolder $owner */",
"$",
"owner",
"=",
"$",
"this",
"->",
"owner",
";",
"$",
"memberType",
"=",
"StaticSchema",
"::",
"inst",
"(",
")",
"->",
"typeNameF... | Adds the "Version" and "Versions" fields to any dataobject that has the Versioned extension.
@param Manager $manager | [
"Adds",
"the",
"Version",
"and",
"Versions",
"fields",
"to",
"any",
"dataobject",
"that",
"has",
"the",
"Versioned",
"extension",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/GraphQL/Extensions/DataObjectScaffolderExtension.php#L21-L87 | train |
silverstripe/silverstripe-versioned | src/Caching/VersionedCacheAdapter.php | VersionedCacheAdapter.getKeyID | protected function getKeyID($key)
{
$state = Versioned::get_reading_mode();
if ($state) {
return $key . '_' . md5($state);
}
return $key;
} | php | protected function getKeyID($key)
{
$state = Versioned::get_reading_mode();
if ($state) {
return $key . '_' . md5($state);
}
return $key;
} | [
"protected",
"function",
"getKeyID",
"(",
"$",
"key",
")",
"{",
"$",
"state",
"=",
"Versioned",
"::",
"get_reading_mode",
"(",
")",
";",
"if",
"(",
"$",
"state",
")",
"{",
"return",
"$",
"key",
".",
"'_'",
".",
"md5",
"(",
"$",
"state",
")",
";",
... | Ensure keys are segmented based on reading mode
@param string $key
@return string | [
"Ensure",
"keys",
"are",
"segmented",
"based",
"on",
"reading",
"mode"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Caching/VersionedCacheAdapter.php#L16-L23 | train |
silverstripe/silverstripe-versioned | src/VersionedStateExtension.php | VersionedStateExtension.updateLink | public function updateLink(&$link)
{
// Skip if link already contains reading mode
if ($this->hasVersionedQuery($link)) {
return;
}
// Skip if current mode matches default mode
// See LeftAndMain::init() for example of this being overridden.
$readingMode = $this->getReadingmode();
if ($readingMode === Versioned::get_default_reading_mode()) {
return;
}
// Determine if query args are supported for the current mode
$queryargs = ReadingMode::toQueryString($readingMode);
if (!$queryargs) {
return;
}
// Don't touch Admin/CMS links
if (class_exists(LeftAndMain::class) && $this->getOwner() instanceof LeftAndMain) {
return;
}
// Decorate
$link = Controller::join_links(
$link,
'?' . http_build_query($queryargs)
);
} | php | public function updateLink(&$link)
{
// Skip if link already contains reading mode
if ($this->hasVersionedQuery($link)) {
return;
}
// Skip if current mode matches default mode
// See LeftAndMain::init() for example of this being overridden.
$readingMode = $this->getReadingmode();
if ($readingMode === Versioned::get_default_reading_mode()) {
return;
}
// Determine if query args are supported for the current mode
$queryargs = ReadingMode::toQueryString($readingMode);
if (!$queryargs) {
return;
}
// Don't touch Admin/CMS links
if (class_exists(LeftAndMain::class) && $this->getOwner() instanceof LeftAndMain) {
return;
}
// Decorate
$link = Controller::join_links(
$link,
'?' . http_build_query($queryargs)
);
} | [
"public",
"function",
"updateLink",
"(",
"&",
"$",
"link",
")",
"{",
"// Skip if link already contains reading mode",
"if",
"(",
"$",
"this",
"->",
"hasVersionedQuery",
"(",
"$",
"link",
")",
")",
"{",
"return",
";",
"}",
"// Skip if current mode matches default mod... | Auto-append current stage if we're in draft,
to avoid relying on session state for this,
and the related potential of showing draft content
without varying the URL itself.
Assumes that if the user has access to view the current
record in draft stage, they can also view other draft records.
Does not concern itself with verifying permissions for performance reasons.
This should also pull through to form actions.
@param string $link | [
"Auto",
"-",
"append",
"current",
"stage",
"if",
"we",
"re",
"in",
"draft",
"to",
"avoid",
"relying",
"on",
"session",
"state",
"for",
"this",
"and",
"the",
"related",
"potential",
"of",
"showing",
"draft",
"content",
"without",
"varying",
"the",
"URL",
"i... | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/VersionedStateExtension.php#L32-L62 | train |
silverstripe/silverstripe-versioned | src/VersionedStateExtension.php | VersionedStateExtension.hasVersionedQuery | protected function hasVersionedQuery($link)
{
// Find querystrings
$parts = explode('?', $link, 2);
if (count($parts) < 2) {
return false;
}
// Parse args
$readingMode = ReadingMode::fromQueryString($parts[1]);
return !empty($readingMode);
} | php | protected function hasVersionedQuery($link)
{
// Find querystrings
$parts = explode('?', $link, 2);
if (count($parts) < 2) {
return false;
}
// Parse args
$readingMode = ReadingMode::fromQueryString($parts[1]);
return !empty($readingMode);
} | [
"protected",
"function",
"hasVersionedQuery",
"(",
"$",
"link",
")",
"{",
"// Find querystrings",
"$",
"parts",
"=",
"explode",
"(",
"'?'",
",",
"$",
"link",
",",
"2",
")",
";",
"if",
"(",
"count",
"(",
"$",
"parts",
")",
"<",
"2",
")",
"{",
"return"... | Check if link contains versioned queryargs
@param string $link
@return bool | [
"Check",
"if",
"link",
"contains",
"versioned",
"queryargs"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/VersionedStateExtension.php#L70-L81 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.augmentDataQueryCreation | public function augmentDataQueryCreation(SQLSelect &$query, DataQuery &$dataQuery)
{
// Convert reading mode to dataquery params and assign
$args = ReadingMode::toDataQueryParams(Versioned::get_reading_mode());
if ($args) {
foreach ($args as $key => $value) {
$dataQuery->setQueryParam($key, $value);
}
}
} | php | public function augmentDataQueryCreation(SQLSelect &$query, DataQuery &$dataQuery)
{
// Convert reading mode to dataquery params and assign
$args = ReadingMode::toDataQueryParams(Versioned::get_reading_mode());
if ($args) {
foreach ($args as $key => $value) {
$dataQuery->setQueryParam($key, $value);
}
}
} | [
"public",
"function",
"augmentDataQueryCreation",
"(",
"SQLSelect",
"&",
"$",
"query",
",",
"DataQuery",
"&",
"$",
"dataQuery",
")",
"{",
"// Convert reading mode to dataquery params and assign",
"$",
"args",
"=",
"ReadingMode",
"::",
"toDataQueryParams",
"(",
"Versione... | Amend freshly created DataQuery objects with versioned-specific
information.
@param SQLSelect $query
@param DataQuery $dataQuery | [
"Amend",
"freshly",
"created",
"DataQuery",
"objects",
"with",
"versioned",
"-",
"specific",
"information",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L304-L313 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.getAtVersion | public function getAtVersion($from)
{
// Null implies return current version
if (is_null($from)) {
return $this->owner;
}
$baseClass = $this->owner->baseClass();
$id = $this->owner->ID ?: $this->owner->OldID;
// By version number
if (is_numeric($from)) {
return Versioned::get_version($baseClass, $id, $from);
}
// By stage
return Versioned::get_by_stage($baseClass, $from)->byID($id);
} | php | public function getAtVersion($from)
{
// Null implies return current version
if (is_null($from)) {
return $this->owner;
}
$baseClass = $this->owner->baseClass();
$id = $this->owner->ID ?: $this->owner->OldID;
// By version number
if (is_numeric($from)) {
return Versioned::get_version($baseClass, $id, $from);
}
// By stage
return Versioned::get_by_stage($baseClass, $from)->byID($id);
} | [
"public",
"function",
"getAtVersion",
"(",
"$",
"from",
")",
"{",
"// Null implies return current version",
"if",
"(",
"is_null",
"(",
"$",
"from",
")",
")",
"{",
"return",
"$",
"this",
"->",
"owner",
";",
"}",
"$",
"baseClass",
"=",
"$",
"this",
"->",
"... | Get this record at a specific version
@param int|string|null $from Version or stage to get at. Null mean returns self object
@return Versioned|DataObject | [
"Get",
"this",
"record",
"at",
"a",
"specific",
"version"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L346-L363 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.getLastEditedForVersion | protected function getLastEditedForVersion($version)
{
Deprecation::notice('5.0', 'Use getLastEditedAndStageForVersion instead');
$result = $this->getLastEditedAndStageForVersion($version);
if ($result) {
return reset($result);
}
return null;
} | php | protected function getLastEditedForVersion($version)
{
Deprecation::notice('5.0', 'Use getLastEditedAndStageForVersion instead');
$result = $this->getLastEditedAndStageForVersion($version);
if ($result) {
return reset($result);
}
return null;
} | [
"protected",
"function",
"getLastEditedForVersion",
"(",
"$",
"version",
")",
"{",
"Deprecation",
"::",
"notice",
"(",
"'5.0'",
",",
"'Use getLastEditedAndStageForVersion instead'",
")",
";",
"$",
"result",
"=",
"$",
"this",
"->",
"getLastEditedAndStageForVersion",
"(... | Get modified date for the given version
@deprecated 4.2..5.0 Use getLastEditedAndStageForVersion instead
@param int $version
@return string | [
"Get",
"modified",
"date",
"for",
"the",
"given",
"version"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L372-L380 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.getLastEditedAndStageForVersion | protected function getLastEditedAndStageForVersion($version)
{
// Cache key
$baseTable = $this->baseTable();
$id = $this->owner->ID;
$key = "{$baseTable}#{$id}/{$version}";
// Check cache
if (isset($this->versionModifiedCache[$key])) {
return $this->versionModifiedCache[$key];
}
// Build query
$table = "\"{$baseTable}_Versions\"";
$query = SQLSelect::create(['"LastEdited"', '"WasPublished"'], $table)
->addWhere([
"{$table}.\"RecordID\"" => $id,
"{$table}.\"Version\"" => $version
]);
$result = $query->execute()->record();
if (!$result) {
return null;
}
$list = [
$result['LastEdited'],
$result['WasPublished'] ? static::LIVE : static::DRAFT,
];
$this->versionModifiedCache[$key] = $list;
return $list;
} | php | protected function getLastEditedAndStageForVersion($version)
{
// Cache key
$baseTable = $this->baseTable();
$id = $this->owner->ID;
$key = "{$baseTable}#{$id}/{$version}";
// Check cache
if (isset($this->versionModifiedCache[$key])) {
return $this->versionModifiedCache[$key];
}
// Build query
$table = "\"{$baseTable}_Versions\"";
$query = SQLSelect::create(['"LastEdited"', '"WasPublished"'], $table)
->addWhere([
"{$table}.\"RecordID\"" => $id,
"{$table}.\"Version\"" => $version
]);
$result = $query->execute()->record();
if (!$result) {
return null;
}
$list = [
$result['LastEdited'],
$result['WasPublished'] ? static::LIVE : static::DRAFT,
];
$this->versionModifiedCache[$key] = $list;
return $list;
} | [
"protected",
"function",
"getLastEditedAndStageForVersion",
"(",
"$",
"version",
")",
"{",
"// Cache key",
"$",
"baseTable",
"=",
"$",
"this",
"->",
"baseTable",
"(",
")",
";",
"$",
"id",
"=",
"$",
"this",
"->",
"owner",
"->",
"ID",
";",
"$",
"key",
"=",... | Get modified date and stage for the given version
@param int $version
@return array A list containing 0 => LastEdited, 1 => Stage | [
"Get",
"modified",
"date",
"and",
"stage",
"for",
"the",
"given",
"version"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L388-L417 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.updateInheritableQueryParams | public function updateInheritableQueryParams(&$params)
{
// Skip if versioned isn't set
if (!isset($params['Versioned.mode'])) {
return;
}
// Adjust query based on original selection criterea
switch ($params['Versioned.mode']) {
case 'all_versions':
{
// Versioned.mode === all_versions doesn't inherit very well, so default to stage
$params['Versioned.mode'] = 'stage';
$params['Versioned.stage'] = static::DRAFT;
break;
}
case 'version':
{
// If we selected this object from a specific version, we need
// to find the date this version was published, and ensure
// inherited queries select from that date.
$version = $params['Versioned.version'];
$dateAndStage = $this->getLastEditedAndStageForVersion($version);
// Filter related objects at the same date as this version
unset($params['Versioned.version']);
if ($dateAndStage) {
list($date, $stage) = $dateAndStage;
$params['Versioned.mode'] = 'archive';
$params['Versioned.date'] = $date;
$params['Versioned.stage'] = $stage;
} else {
// Fallback to default
$params['Versioned.mode'] = 'stage';
$params['Versioned.stage'] = static::DRAFT;
}
break;
}
}
} | php | public function updateInheritableQueryParams(&$params)
{
// Skip if versioned isn't set
if (!isset($params['Versioned.mode'])) {
return;
}
// Adjust query based on original selection criterea
switch ($params['Versioned.mode']) {
case 'all_versions':
{
// Versioned.mode === all_versions doesn't inherit very well, so default to stage
$params['Versioned.mode'] = 'stage';
$params['Versioned.stage'] = static::DRAFT;
break;
}
case 'version':
{
// If we selected this object from a specific version, we need
// to find the date this version was published, and ensure
// inherited queries select from that date.
$version = $params['Versioned.version'];
$dateAndStage = $this->getLastEditedAndStageForVersion($version);
// Filter related objects at the same date as this version
unset($params['Versioned.version']);
if ($dateAndStage) {
list($date, $stage) = $dateAndStage;
$params['Versioned.mode'] = 'archive';
$params['Versioned.date'] = $date;
$params['Versioned.stage'] = $stage;
} else {
// Fallback to default
$params['Versioned.mode'] = 'stage';
$params['Versioned.stage'] = static::DRAFT;
}
break;
}
}
} | [
"public",
"function",
"updateInheritableQueryParams",
"(",
"&",
"$",
"params",
")",
"{",
"// Skip if versioned isn't set",
"if",
"(",
"!",
"isset",
"(",
"$",
"params",
"[",
"'Versioned.mode'",
"]",
")",
")",
"{",
"return",
";",
"}",
"// Adjust query based on origi... | Updates query parameters of relations attached to versioned dataobjects
@param array $params | [
"Updates",
"query",
"parameters",
"of",
"relations",
"attached",
"to",
"versioned",
"dataobjects"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L424-L463 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.augmentSQL | public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null)
{
// Ensure query mode exists
$versionedMode = $dataQuery->getQueryParam('Versioned.mode');
if (!$versionedMode) {
return;
}
switch ($versionedMode) {
case 'stage':
$this->augmentSQLStage($query, $dataQuery);
break;
case 'stage_unique':
$this->augmentSQLStageUnique($query, $dataQuery);
break;
case 'archive':
$this->augmentSQLVersionedArchive($query, $dataQuery);
break;
case 'latest_version_single':
$this->augmentSQLVersionedLatestSingle($query, $dataQuery);
break;
case 'latest_versions':
$this->augmentSQLVersionedLatest($query);
break;
case 'version':
$this->augmentSQLVersionedVersion($query, $dataQuery);
break;
case 'all_versions':
$this->augmentSQLVersionedAll($query);
break;
default:
throw new InvalidArgumentException("Bad value for query parameter Versioned.mode: {$versionedMode}");
}
} | php | public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null)
{
// Ensure query mode exists
$versionedMode = $dataQuery->getQueryParam('Versioned.mode');
if (!$versionedMode) {
return;
}
switch ($versionedMode) {
case 'stage':
$this->augmentSQLStage($query, $dataQuery);
break;
case 'stage_unique':
$this->augmentSQLStageUnique($query, $dataQuery);
break;
case 'archive':
$this->augmentSQLVersionedArchive($query, $dataQuery);
break;
case 'latest_version_single':
$this->augmentSQLVersionedLatestSingle($query, $dataQuery);
break;
case 'latest_versions':
$this->augmentSQLVersionedLatest($query);
break;
case 'version':
$this->augmentSQLVersionedVersion($query, $dataQuery);
break;
case 'all_versions':
$this->augmentSQLVersionedAll($query);
break;
default:
throw new InvalidArgumentException("Bad value for query parameter Versioned.mode: {$versionedMode}");
}
} | [
"public",
"function",
"augmentSQL",
"(",
"SQLSelect",
"$",
"query",
",",
"DataQuery",
"$",
"dataQuery",
"=",
"null",
")",
"{",
"// Ensure query mode exists",
"$",
"versionedMode",
"=",
"$",
"dataQuery",
"->",
"getQueryParam",
"(",
"'Versioned.mode'",
")",
";",
"... | Augment the the SQLSelect that is created by the DataQuery
See {@see augmentLazyLoadFields} for lazy-loading applied prior to this.
@param SQLSelect $query
@param DataQuery $dataQuery
@throws InvalidArgumentException | [
"Augment",
"the",
"the",
"SQLSelect",
"that",
"is",
"created",
"by",
"the",
"DataQuery"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L474-L506 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.augmentSQLStageUnique | protected function augmentSQLStageUnique(SQLSelect $query, DataQuery $dataQuery)
{
if (!$this->hasStages()) {
return;
}
// Set stage first
$this->augmentSQLStage($query, $dataQuery);
// Now exclude any ID from any other stage.
$stage = $dataQuery->getQueryParam('Versioned.stage');
$excludingStage = $stage === static::DRAFT ? static::LIVE : static::DRAFT;
// Note that we double rename to avoid the regular stage rename
// renaming all subquery references to be Versioned.stage
$tempName = 'ExclusionarySource_' . $excludingStage;
$excludingTable = $this->baseTable($excludingStage);
$baseTable = $this->baseTable($stage);
$query->addWhere("\"{$baseTable}\".\"ID\" NOT IN (SELECT \"ID\" FROM \"{$tempName}\")");
$query->renameTable($tempName, $excludingTable);
} | php | protected function augmentSQLStageUnique(SQLSelect $query, DataQuery $dataQuery)
{
if (!$this->hasStages()) {
return;
}
// Set stage first
$this->augmentSQLStage($query, $dataQuery);
// Now exclude any ID from any other stage.
$stage = $dataQuery->getQueryParam('Versioned.stage');
$excludingStage = $stage === static::DRAFT ? static::LIVE : static::DRAFT;
// Note that we double rename to avoid the regular stage rename
// renaming all subquery references to be Versioned.stage
$tempName = 'ExclusionarySource_' . $excludingStage;
$excludingTable = $this->baseTable($excludingStage);
$baseTable = $this->baseTable($stage);
$query->addWhere("\"{$baseTable}\".\"ID\" NOT IN (SELECT \"ID\" FROM \"{$tempName}\")");
$query->renameTable($tempName, $excludingTable);
} | [
"protected",
"function",
"augmentSQLStageUnique",
"(",
"SQLSelect",
"$",
"query",
",",
"DataQuery",
"$",
"dataQuery",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasStages",
"(",
")",
")",
"{",
"return",
";",
"}",
"// Set stage first",
"$",
"this",
"->",... | Reading a specific stage, but only return items that aren't in any other stage
@param SQLSelect $query
@param DataQuery $dataQuery | [
"Reading",
"a",
"specific",
"stage",
"but",
"only",
"return",
"items",
"that",
"aren",
"t",
"in",
"any",
"other",
"stage"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L540-L559 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.augmentSQLVersioned | protected function augmentSQLVersioned(SQLSelect $query)
{
$baseTable = $this->baseTable();
foreach ($query->getFrom() as $alias => $join) {
if (!$this->isTableVersioned($alias)) {
continue;
}
if ($alias != $baseTable) {
// Make sure join includes version as well
$query->setJoinFilter(
$alias,
"\"{$alias}_Versions\".\"RecordID\" = \"{$baseTable}_Versions\".\"RecordID\""
. " AND \"{$alias}_Versions\".\"Version\" = \"{$baseTable}_Versions\".\"Version\""
);
}
// Rewrite all usages of `Table` to `Table_Versions`
$query->renameTable($alias, $alias . '_Versions');
// However, add an alias back to the base table in case this must later be joined.
// See ApplyVersionFilters for example which joins _Versions back onto draft table.
$query->renameTable($alias . '_Draft', $alias);
}
// Add all <basetable>_Versions columns
foreach (Config::inst()->get(static::class, 'db_for_versions_table') as $name => $type) {
$query->selectField(sprintf('"%s_Versions"."%s"', $baseTable, $name), $name);
}
// Alias the record ID as the row ID, and ensure ID filters are aliased correctly
$query->selectField("\"{$baseTable}_Versions\".\"RecordID\"", "ID");
$query->replaceText("\"{$baseTable}_Versions\".\"ID\"", "\"{$baseTable}_Versions\".\"RecordID\"");
// However, if doing count, undo rewrite of "ID" column
$query->replaceText(
"count(DISTINCT \"{$baseTable}_Versions\".\"RecordID\")",
"count(DISTINCT \"{$baseTable}_Versions\".\"ID\")"
);
// Filter deleted versions, which are all unqueryable
$query->addWhere(["\"{$baseTable}_Versions\".\"WasDeleted\"" => 0]);
} | php | protected function augmentSQLVersioned(SQLSelect $query)
{
$baseTable = $this->baseTable();
foreach ($query->getFrom() as $alias => $join) {
if (!$this->isTableVersioned($alias)) {
continue;
}
if ($alias != $baseTable) {
// Make sure join includes version as well
$query->setJoinFilter(
$alias,
"\"{$alias}_Versions\".\"RecordID\" = \"{$baseTable}_Versions\".\"RecordID\""
. " AND \"{$alias}_Versions\".\"Version\" = \"{$baseTable}_Versions\".\"Version\""
);
}
// Rewrite all usages of `Table` to `Table_Versions`
$query->renameTable($alias, $alias . '_Versions');
// However, add an alias back to the base table in case this must later be joined.
// See ApplyVersionFilters for example which joins _Versions back onto draft table.
$query->renameTable($alias . '_Draft', $alias);
}
// Add all <basetable>_Versions columns
foreach (Config::inst()->get(static::class, 'db_for_versions_table') as $name => $type) {
$query->selectField(sprintf('"%s_Versions"."%s"', $baseTable, $name), $name);
}
// Alias the record ID as the row ID, and ensure ID filters are aliased correctly
$query->selectField("\"{$baseTable}_Versions\".\"RecordID\"", "ID");
$query->replaceText("\"{$baseTable}_Versions\".\"ID\"", "\"{$baseTable}_Versions\".\"RecordID\"");
// However, if doing count, undo rewrite of "ID" column
$query->replaceText(
"count(DISTINCT \"{$baseTable}_Versions\".\"RecordID\")",
"count(DISTINCT \"{$baseTable}_Versions\".\"ID\")"
);
// Filter deleted versions, which are all unqueryable
$query->addWhere(["\"{$baseTable}_Versions\".\"WasDeleted\"" => 0]);
} | [
"protected",
"function",
"augmentSQLVersioned",
"(",
"SQLSelect",
"$",
"query",
")",
"{",
"$",
"baseTable",
"=",
"$",
"this",
"->",
"baseTable",
"(",
")",
";",
"foreach",
"(",
"$",
"query",
"->",
"getFrom",
"(",
")",
"as",
"$",
"alias",
"=>",
"$",
"joi... | Augment SQL to select from `_Versions` table instead.
@param SQLSelect $query | [
"Augment",
"SQL",
"to",
"select",
"from",
"_Versions",
"table",
"instead",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L566-L607 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.augmentSQLVersionedArchive | protected function augmentSQLVersionedArchive(SQLSelect $query, DataQuery $dataQuery)
{
$baseTable = $this->baseTable();
$date = $dataQuery->getQueryParam('Versioned.date');
if (!$date) {
throw new InvalidArgumentException("Invalid archive date");
}
// Query against _Versions table first
$this->augmentSQLVersioned($query);
// Validate stage
$stage = $dataQuery->getQueryParam('Versioned.stage');
ReadingMode::validateStage($stage);
// Filter on appropriate stage column in addition to date
if ($this->hasStages()) {
$stageColumn = $stage === static::LIVE
? 'WasPublished'
: 'WasDraft';
$stageCondition = "AND \"{$baseTable}_Versions\".\"{$stageColumn}\" = 1";
} else {
$stageCondition = '';
}
// Join on latest version filtered by date
$query->addInnerJoin(
<<<SQL
(
SELECT "{$baseTable}_Versions"."RecordID",
MAX("{$baseTable}_Versions"."Version") AS "LatestVersion"
FROM "{$baseTable}_Versions"
WHERE "{$baseTable}_Versions"."LastEdited" <= ?
{$stageCondition}
GROUP BY "{$baseTable}_Versions"."RecordID"
)
SQL
,
<<<SQL
"{$baseTable}_Versions_Latest"."RecordID" = "{$baseTable}_Versions"."RecordID"
AND "{$baseTable}_Versions_Latest"."LatestVersion" = "{$baseTable}_Versions"."Version"
SQL
,
"{$baseTable}_Versions_Latest",
20,
[$date]
);
} | php | protected function augmentSQLVersionedArchive(SQLSelect $query, DataQuery $dataQuery)
{
$baseTable = $this->baseTable();
$date = $dataQuery->getQueryParam('Versioned.date');
if (!$date) {
throw new InvalidArgumentException("Invalid archive date");
}
// Query against _Versions table first
$this->augmentSQLVersioned($query);
// Validate stage
$stage = $dataQuery->getQueryParam('Versioned.stage');
ReadingMode::validateStage($stage);
// Filter on appropriate stage column in addition to date
if ($this->hasStages()) {
$stageColumn = $stage === static::LIVE
? 'WasPublished'
: 'WasDraft';
$stageCondition = "AND \"{$baseTable}_Versions\".\"{$stageColumn}\" = 1";
} else {
$stageCondition = '';
}
// Join on latest version filtered by date
$query->addInnerJoin(
<<<SQL
(
SELECT "{$baseTable}_Versions"."RecordID",
MAX("{$baseTable}_Versions"."Version") AS "LatestVersion"
FROM "{$baseTable}_Versions"
WHERE "{$baseTable}_Versions"."LastEdited" <= ?
{$stageCondition}
GROUP BY "{$baseTable}_Versions"."RecordID"
)
SQL
,
<<<SQL
"{$baseTable}_Versions_Latest"."RecordID" = "{$baseTable}_Versions"."RecordID"
AND "{$baseTable}_Versions_Latest"."LatestVersion" = "{$baseTable}_Versions"."Version"
SQL
,
"{$baseTable}_Versions_Latest",
20,
[$date]
);
} | [
"protected",
"function",
"augmentSQLVersionedArchive",
"(",
"SQLSelect",
"$",
"query",
",",
"DataQuery",
"$",
"dataQuery",
")",
"{",
"$",
"baseTable",
"=",
"$",
"this",
"->",
"baseTable",
"(",
")",
";",
"$",
"date",
"=",
"$",
"dataQuery",
"->",
"getQueryPara... | Filter the versioned history by a specific date and archive stage
@param SQLSelect $query
@param DataQuery $dataQuery | [
"Filter",
"the",
"versioned",
"history",
"by",
"a",
"specific",
"date",
"and",
"archive",
"stage"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L615-L662 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.augmentSQLVersionedVersion | protected function augmentSQLVersionedVersion(SQLSelect $query, DataQuery $dataQuery)
{
$version = $dataQuery->getQueryParam('Versioned.version');
if (!$version) {
throw new InvalidArgumentException("Invalid version");
}
// Query against _Versions table first
$this->augmentSQLVersioned($query);
// Add filter on version field
$baseTable = $this->baseTable();
$query->addWhere([
"\"{$baseTable}_Versions\".\"Version\"" => $version,
]);
} | php | protected function augmentSQLVersionedVersion(SQLSelect $query, DataQuery $dataQuery)
{
$version = $dataQuery->getQueryParam('Versioned.version');
if (!$version) {
throw new InvalidArgumentException("Invalid version");
}
// Query against _Versions table first
$this->augmentSQLVersioned($query);
// Add filter on version field
$baseTable = $this->baseTable();
$query->addWhere([
"\"{$baseTable}_Versions\".\"Version\"" => $version,
]);
} | [
"protected",
"function",
"augmentSQLVersionedVersion",
"(",
"SQLSelect",
"$",
"query",
",",
"DataQuery",
"$",
"dataQuery",
")",
"{",
"$",
"version",
"=",
"$",
"dataQuery",
"->",
"getQueryParam",
"(",
"'Versioned.version'",
")",
";",
"if",
"(",
"!",
"$",
"versi... | If selecting a specific version, filter it here
@param SQLSelect $query
@param DataQuery $dataQuery | [
"If",
"selecting",
"a",
"specific",
"version",
"filter",
"it",
"here"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L731-L746 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.augmentSQLVersionedAll | protected function augmentSQLVersionedAll(SQLSelect $query)
{
// Query against _Versions table first
$this->augmentSQLVersioned($query);
$baseTable = $this->baseTable();
$query->addOrderBy("\"{$baseTable}_Versions\".\"Version\"");
} | php | protected function augmentSQLVersionedAll(SQLSelect $query)
{
// Query against _Versions table first
$this->augmentSQLVersioned($query);
$baseTable = $this->baseTable();
$query->addOrderBy("\"{$baseTable}_Versions\".\"Version\"");
} | [
"protected",
"function",
"augmentSQLVersionedAll",
"(",
"SQLSelect",
"$",
"query",
")",
"{",
"// Query against _Versions table first",
"$",
"this",
"->",
"augmentSQLVersioned",
"(",
"$",
"query",
")",
";",
"$",
"baseTable",
"=",
"$",
"this",
"->",
"baseTable",
"("... | If all versions are requested, ensure that records are sorted by this field
@param SQLSelect $query | [
"If",
"all",
"versions",
"are",
"requested",
"ensure",
"that",
"records",
"are",
"sorted",
"by",
"this",
"field"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L753-L760 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.isTableVersioned | protected function isTableVersioned($table)
{
$schema = DataObject::getSchema();
$tableClass = $schema->tableClass($table);
if (empty($tableClass)) {
return false;
}
// Check that this class belongs to the same tree
$baseClass = $schema->baseDataClass($this->owner);
if (!is_a($tableClass, $baseClass, true)) {
return false;
}
// Check that this isn't a derived table
// (e.g. _Live, or a many_many table)
$mainTable = $schema->tableName($tableClass);
if ($mainTable !== $table) {
return false;
}
return true;
} | php | protected function isTableVersioned($table)
{
$schema = DataObject::getSchema();
$tableClass = $schema->tableClass($table);
if (empty($tableClass)) {
return false;
}
// Check that this class belongs to the same tree
$baseClass = $schema->baseDataClass($this->owner);
if (!is_a($tableClass, $baseClass, true)) {
return false;
}
// Check that this isn't a derived table
// (e.g. _Live, or a many_many table)
$mainTable = $schema->tableName($tableClass);
if ($mainTable !== $table) {
return false;
}
return true;
} | [
"protected",
"function",
"isTableVersioned",
"(",
"$",
"table",
")",
"{",
"$",
"schema",
"=",
"DataObject",
"::",
"getSchema",
"(",
")",
";",
"$",
"tableClass",
"=",
"$",
"schema",
"->",
"tableClass",
"(",
"$",
"table",
")",
";",
"if",
"(",
"empty",
"(... | Determine if the given versioned table is a part of the sub-tree of the current dataobject
This helps prevent rewriting of other tables that get joined in, in particular, many_many tables
@param string $table
@return bool True if this table should be versioned | [
"Determine",
"if",
"the",
"given",
"versioned",
"table",
"is",
"a",
"part",
"of",
"the",
"sub",
"-",
"tree",
"of",
"the",
"current",
"dataobject",
"This",
"helps",
"prevent",
"rewriting",
"of",
"other",
"tables",
"that",
"get",
"joined",
"in",
"in",
"parti... | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L769-L791 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.augmentLoadLazyFields | public function augmentLoadLazyFields(SQLSelect &$query, DataQuery &$dataQuery = null, $dataObject)
{
// The VersionedMode local variable ensures that this decorator only applies to
// queries that have originated from the Versioned object, and have the Versioned
// metadata set on the query object. This prevents regular queries from
// accidentally querying the *_Versions tables.
$versionedMode = $dataObject->getSourceQueryParam('Versioned.mode');
$modesToAllowVersioning = ['all_versions', 'latest_versions', 'archive', 'version'];
if (!empty($dataObject->Version) &&
(!empty($versionedMode) && in_array($versionedMode, $modesToAllowVersioning))
) {
// This will ensure that augmentSQL will select only the same version as the owner,
// regardless of how this object was initially selected
$versionColumn = $this->owner->getSchema()->sqlColumnForField($this->owner, 'Version');
$dataQuery->where([
$versionColumn => $dataObject->Version
]);
$dataQuery->setQueryParam('Versioned.mode', 'all_versions');
}
} | php | public function augmentLoadLazyFields(SQLSelect &$query, DataQuery &$dataQuery = null, $dataObject)
{
// The VersionedMode local variable ensures that this decorator only applies to
// queries that have originated from the Versioned object, and have the Versioned
// metadata set on the query object. This prevents regular queries from
// accidentally querying the *_Versions tables.
$versionedMode = $dataObject->getSourceQueryParam('Versioned.mode');
$modesToAllowVersioning = ['all_versions', 'latest_versions', 'archive', 'version'];
if (!empty($dataObject->Version) &&
(!empty($versionedMode) && in_array($versionedMode, $modesToAllowVersioning))
) {
// This will ensure that augmentSQL will select only the same version as the owner,
// regardless of how this object was initially selected
$versionColumn = $this->owner->getSchema()->sqlColumnForField($this->owner, 'Version');
$dataQuery->where([
$versionColumn => $dataObject->Version
]);
$dataQuery->setQueryParam('Versioned.mode', 'all_versions');
}
} | [
"public",
"function",
"augmentLoadLazyFields",
"(",
"SQLSelect",
"&",
"$",
"query",
",",
"DataQuery",
"&",
"$",
"dataQuery",
"=",
"null",
",",
"$",
"dataObject",
")",
"{",
"// The VersionedMode local variable ensures that this decorator only applies to",
"// queries that ha... | For lazy loaded fields requiring extra sql manipulation, ie versioning.
@param SQLSelect $query
@param DataQuery $dataQuery
@param DataObject $dataObject | [
"For",
"lazy",
"loaded",
"fields",
"requiring",
"extra",
"sql",
"manipulation",
"ie",
"versioning",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L800-L819 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.cleanupVersionedOrphans | protected function cleanupVersionedOrphans($baseTable, $childTable)
{
// Avoid if disabled
if ($this->owner->config()->get('versioned_orphans_disabled')) {
return;
}
// Skip if tables are the same (ignore case)
if (strcasecmp($childTable, $baseTable) === 0) {
return;
}
// Skip if child table doesn't exist
// If it does, ensure query case matches found case
$tables = DB::get_schema()->tableList();
if (!array_key_exists(strtolower($childTable), $tables)) {
return;
}
$childTable = $tables[strtolower($childTable)];
// Select all orphaned version records
$orphanedQuery = SQLSelect::create()
->selectField("\"{$childTable}\".\"ID\"")
->setFrom("\"{$childTable}\"");
// If we have a parent table limit orphaned records
// to only those that exist in this
if (array_key_exists(strtolower($baseTable), $tables)) {
// Ensure we match db table case
$baseTable = $tables[strtolower($baseTable)];
$orphanedQuery
->addLeftJoin(
$baseTable,
"\"{$childTable}\".\"RecordID\" = \"{$baseTable}\".\"RecordID\"
AND \"{$childTable}\".\"Version\" = \"{$baseTable}\".\"Version\""
)
->addWhere("\"{$baseTable}\".\"ID\" IS NULL");
}
$count = $orphanedQuery->count();
if ($count > 0) {
DB::alteration_message("Removing {$count} orphaned versioned records", "deleted");
$ids = $orphanedQuery->execute()->column();
foreach ($ids as $id) {
DB::prepared_query("DELETE FROM \"{$childTable}\" WHERE \"ID\" = ?", [$id]);
}
}
} | php | protected function cleanupVersionedOrphans($baseTable, $childTable)
{
// Avoid if disabled
if ($this->owner->config()->get('versioned_orphans_disabled')) {
return;
}
// Skip if tables are the same (ignore case)
if (strcasecmp($childTable, $baseTable) === 0) {
return;
}
// Skip if child table doesn't exist
// If it does, ensure query case matches found case
$tables = DB::get_schema()->tableList();
if (!array_key_exists(strtolower($childTable), $tables)) {
return;
}
$childTable = $tables[strtolower($childTable)];
// Select all orphaned version records
$orphanedQuery = SQLSelect::create()
->selectField("\"{$childTable}\".\"ID\"")
->setFrom("\"{$childTable}\"");
// If we have a parent table limit orphaned records
// to only those that exist in this
if (array_key_exists(strtolower($baseTable), $tables)) {
// Ensure we match db table case
$baseTable = $tables[strtolower($baseTable)];
$orphanedQuery
->addLeftJoin(
$baseTable,
"\"{$childTable}\".\"RecordID\" = \"{$baseTable}\".\"RecordID\"
AND \"{$childTable}\".\"Version\" = \"{$baseTable}\".\"Version\""
)
->addWhere("\"{$baseTable}\".\"ID\" IS NULL");
}
$count = $orphanedQuery->count();
if ($count > 0) {
DB::alteration_message("Removing {$count} orphaned versioned records", "deleted");
$ids = $orphanedQuery->execute()->column();
foreach ($ids as $id) {
DB::prepared_query("DELETE FROM \"{$childTable}\" WHERE \"ID\" = ?", [$id]);
}
}
} | [
"protected",
"function",
"cleanupVersionedOrphans",
"(",
"$",
"baseTable",
",",
"$",
"childTable",
")",
"{",
"// Avoid if disabled",
"if",
"(",
"$",
"this",
"->",
"owner",
"->",
"config",
"(",
")",
"->",
"get",
"(",
"'versioned_orphans_disabled'",
")",
")",
"{... | Cleanup orphaned records in the _Versions table
@param string $baseTable base table to use as authoritative source of records
@param string $childTable Sub-table to clean orphans from | [
"Cleanup",
"orphaned",
"records",
"in",
"the",
"_Versions",
"table"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L948-L995 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.createDeletedVersion | protected function createDeletedVersion($stages = [])
{
// Skip if suppressed by parent delete
if (!$this->getDeleteWritesVersion()) {
return;
}
// Prepare manipulation
$baseTable = $this->owner->baseTable();
$now = DBDatetime::now()->Rfc2822();
// Ensure all fixed_fields are specified
$manipulation = [
$baseTable => [
'fields' => [
'ID' => $this->owner->ID,
'LastEdited' => $now,
'Created' => $this->owner->Created ?: $now,
'ClassName' => $this->owner->ClassName,
],
],
];
// Prepare "deleted" augment write
$this->augmentWriteVersioned(
$manipulation,
$this->owner->baseClass(),
$baseTable,
$this->owner->ID,
$stages,
true
);
unset($manipulation[$baseTable]);
$this->owner->extend('augmentWriteDeletedVersion', $manipulation, $stages);
DB::manipulate($manipulation);
} | php | protected function createDeletedVersion($stages = [])
{
// Skip if suppressed by parent delete
if (!$this->getDeleteWritesVersion()) {
return;
}
// Prepare manipulation
$baseTable = $this->owner->baseTable();
$now = DBDatetime::now()->Rfc2822();
// Ensure all fixed_fields are specified
$manipulation = [
$baseTable => [
'fields' => [
'ID' => $this->owner->ID,
'LastEdited' => $now,
'Created' => $this->owner->Created ?: $now,
'ClassName' => $this->owner->ClassName,
],
],
];
// Prepare "deleted" augment write
$this->augmentWriteVersioned(
$manipulation,
$this->owner->baseClass(),
$baseTable,
$this->owner->ID,
$stages,
true
);
unset($manipulation[$baseTable]);
$this->owner->extend('augmentWriteDeletedVersion', $manipulation, $stages);
DB::manipulate($manipulation);
} | [
"protected",
"function",
"createDeletedVersion",
"(",
"$",
"stages",
"=",
"[",
"]",
")",
"{",
"// Skip if suppressed by parent delete",
"if",
"(",
"!",
"$",
"this",
"->",
"getDeleteWritesVersion",
"(",
")",
")",
"{",
"return",
";",
"}",
"// Prepare manipulation",
... | Adds a WasDeleted=1 version entry for this record, and records any stages
the deletion applies to
@param string[]|string $stages Stage or array of affected stages | [
"Adds",
"a",
"WasDeleted",
"=",
"1",
"version",
"entry",
"for",
"this",
"record",
"and",
"records",
"any",
"stages",
"the",
"deletion",
"applies",
"to"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1127-L1159 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.suppressDeletedVersion | protected function suppressDeletedVersion($callback)
{
$original = $this->getDeleteWritesVersion();
try {
$this->setDeleteWritesVersion(false);
return $callback();
} finally {
$this->setDeleteWritesVersion($original);
}
} | php | protected function suppressDeletedVersion($callback)
{
$original = $this->getDeleteWritesVersion();
try {
$this->setDeleteWritesVersion(false);
return $callback();
} finally {
$this->setDeleteWritesVersion($original);
}
} | [
"protected",
"function",
"suppressDeletedVersion",
"(",
"$",
"callback",
")",
"{",
"$",
"original",
"=",
"$",
"this",
"->",
"getDeleteWritesVersion",
"(",
")",
";",
"try",
"{",
"$",
"this",
"->",
"setDeleteWritesVersion",
"(",
"false",
")",
";",
"return",
"$... | Helper method to safely suppress delete callback
@param callable $callback
@return mixed Result of $callback() | [
"Helper",
"method",
"to",
"safely",
"suppress",
"delete",
"callback"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1303-L1312 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.canArchive | public function canArchive($member = null)
{
// Skip if invoked by extendedCan()
if (func_num_args() > 4) {
return null;
}
if (!$member) {
$member = Security::getCurrentUser();
}
// Standard mechanism for accepting permission changes from extensions
$owner = $this->owner;
$extended = $owner->extendedCan('canArchive', $member);
if ($extended !== null) {
return $extended;
}
// Admin permissions allow
if (Permission::checkMember($member, "ADMIN")) {
return true;
}
// Check if this record can be deleted from stage
if (!$owner->canDelete($member)) {
return false;
}
// Check if we can delete from live
if (!$owner->canUnpublish($member)) {
return false;
}
return true;
} | php | public function canArchive($member = null)
{
// Skip if invoked by extendedCan()
if (func_num_args() > 4) {
return null;
}
if (!$member) {
$member = Security::getCurrentUser();
}
// Standard mechanism for accepting permission changes from extensions
$owner = $this->owner;
$extended = $owner->extendedCan('canArchive', $member);
if ($extended !== null) {
return $extended;
}
// Admin permissions allow
if (Permission::checkMember($member, "ADMIN")) {
return true;
}
// Check if this record can be deleted from stage
if (!$owner->canDelete($member)) {
return false;
}
// Check if we can delete from live
if (!$owner->canUnpublish($member)) {
return false;
}
return true;
} | [
"public",
"function",
"canArchive",
"(",
"$",
"member",
"=",
"null",
")",
"{",
"// Skip if invoked by extendedCan()",
"if",
"(",
"func_num_args",
"(",
")",
">",
"4",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"$",
"member",
")",
"{",
"$",
"m... | Check if the current user is allowed to archive this record.
If extended, ensure that both canDelete and canUnpublish are extended also
@param Member $member
@return bool | [
"Check",
"if",
"the",
"current",
"user",
"is",
"allowed",
"to",
"archive",
"this",
"record",
".",
"If",
"extended",
"ensure",
"that",
"both",
"canDelete",
"and",
"canUnpublish",
"are",
"extended",
"also"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1399-L1433 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.canRevertToLive | public function canRevertToLive($member = null)
{
$owner = $this->owner;
// Skip if invoked by extendedCan()
if (func_num_args() > 4) {
return null;
}
// Can't revert if not on live
if (!$owner->isPublished()) {
return false;
}
if (!$member) {
$member = Security::getCurrentUser();
}
if (Permission::checkMember($member, "ADMIN")) {
return true;
}
// Standard mechanism for accepting permission changes from extensions
$extended = $owner->extendedCan('canRevertToLive', $member);
if ($extended !== null) {
return $extended;
}
// Default to canEdit
return $owner->canEdit($member);
} | php | public function canRevertToLive($member = null)
{
$owner = $this->owner;
// Skip if invoked by extendedCan()
if (func_num_args() > 4) {
return null;
}
// Can't revert if not on live
if (!$owner->isPublished()) {
return false;
}
if (!$member) {
$member = Security::getCurrentUser();
}
if (Permission::checkMember($member, "ADMIN")) {
return true;
}
// Standard mechanism for accepting permission changes from extensions
$extended = $owner->extendedCan('canRevertToLive', $member);
if ($extended !== null) {
return $extended;
}
// Default to canEdit
return $owner->canEdit($member);
} | [
"public",
"function",
"canRevertToLive",
"(",
"$",
"member",
"=",
"null",
")",
"{",
"$",
"owner",
"=",
"$",
"this",
"->",
"owner",
";",
"// Skip if invoked by extendedCan()",
"if",
"(",
"func_num_args",
"(",
")",
">",
"4",
")",
"{",
"return",
"null",
";",
... | Check if the user can revert this record to live
@param Member $member
@return bool | [
"Check",
"if",
"the",
"user",
"can",
"revert",
"this",
"record",
"to",
"live"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1441-L1471 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.canView | public function canView($member = null)
{
// Invoke default version-gnostic canView
if ($this->owner->canViewVersioned($member) === false) {
return false;
}
return null;
} | php | public function canView($member = null)
{
// Invoke default version-gnostic canView
if ($this->owner->canViewVersioned($member) === false) {
return false;
}
return null;
} | [
"public",
"function",
"canView",
"(",
"$",
"member",
"=",
"null",
")",
"{",
"// Invoke default version-gnostic canView",
"if",
"(",
"$",
"this",
"->",
"owner",
"->",
"canViewVersioned",
"(",
"$",
"member",
")",
"===",
"false",
")",
"{",
"return",
"false",
";... | Extend permissions to include additional security for objects that are not published to live.
@param Member $member
@return bool|null | [
"Extend",
"permissions",
"to",
"include",
"additional",
"security",
"for",
"objects",
"that",
"are",
"not",
"published",
"to",
"live",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1512-L1519 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.canViewVersioned | public function canViewVersioned($member = null)
{
// Bypass when live stage
$owner = $this->owner;
// Bypass if site is unsecured
if (!self::get_draft_site_secured()) {
return true;
}
// Get reading mode from source query (or current mode)
$readingParams = $owner->getSourceQueryParams()
// Guess record mode from current reading mode instead
?: ReadingMode::toDataQueryParams(static::get_reading_mode());
// If this is the live record we can view it
if (isset($readingParams["Versioned.mode"])
&& $readingParams["Versioned.mode"] === 'stage'
&& $readingParams["Versioned.stage"] === static::LIVE
) {
return true;
}
// Bypass if record doesn't have a live stage
if (!$this->hasStages()) {
return true;
}
// If we weren't definitely loaded from live, and we can't view non-live content, we need to
// check to make sure this version is the live version and so can be viewed
$latestVersion = Versioned::get_versionnumber_by_stage(get_class($owner), static::LIVE, $owner->ID);
if ($latestVersion == $owner->Version) {
// Even if this is loaded from a non-live stage, this is the live version
return true;
}
// If stages are synchronised treat this as the live stage
if (!$this->stagesDiffer()) {
return true;
}
// Extend versioned behaviour
$extended = $owner->extendedCan('canViewNonLive', $member);
if ($extended !== null) {
return (bool)$extended;
}
// Fall back to default permission check
$permissions = Config::inst()->get(get_class($owner), 'non_live_permissions');
$check = Permission::checkMember($member, $permissions);
return (bool)$check;
} | php | public function canViewVersioned($member = null)
{
// Bypass when live stage
$owner = $this->owner;
// Bypass if site is unsecured
if (!self::get_draft_site_secured()) {
return true;
}
// Get reading mode from source query (or current mode)
$readingParams = $owner->getSourceQueryParams()
// Guess record mode from current reading mode instead
?: ReadingMode::toDataQueryParams(static::get_reading_mode());
// If this is the live record we can view it
if (isset($readingParams["Versioned.mode"])
&& $readingParams["Versioned.mode"] === 'stage'
&& $readingParams["Versioned.stage"] === static::LIVE
) {
return true;
}
// Bypass if record doesn't have a live stage
if (!$this->hasStages()) {
return true;
}
// If we weren't definitely loaded from live, and we can't view non-live content, we need to
// check to make sure this version is the live version and so can be viewed
$latestVersion = Versioned::get_versionnumber_by_stage(get_class($owner), static::LIVE, $owner->ID);
if ($latestVersion == $owner->Version) {
// Even if this is loaded from a non-live stage, this is the live version
return true;
}
// If stages are synchronised treat this as the live stage
if (!$this->stagesDiffer()) {
return true;
}
// Extend versioned behaviour
$extended = $owner->extendedCan('canViewNonLive', $member);
if ($extended !== null) {
return (bool)$extended;
}
// Fall back to default permission check
$permissions = Config::inst()->get(get_class($owner), 'non_live_permissions');
$check = Permission::checkMember($member, $permissions);
return (bool)$check;
} | [
"public",
"function",
"canViewVersioned",
"(",
"$",
"member",
"=",
"null",
")",
"{",
"// Bypass when live stage",
"$",
"owner",
"=",
"$",
"this",
"->",
"owner",
";",
"// Bypass if site is unsecured",
"if",
"(",
"!",
"self",
"::",
"get_draft_site_secured",
"(",
"... | Determine if there are any additional restrictions on this object for the given reading version.
Override this in a subclass to customise any additional effect that Versioned applies to canView.
This is expected to be called by canView, and thus is only responsible for denying access if
the default canView would otherwise ALLOW access. Thus it should not be called in isolation
as an authoritative permission check.
This has the following extension points:
- canViewDraft is invoked if Mode = stage and Stage = stage
- canViewArchived is invoked if Mode = archive
@param Member $member
@return bool False is returned if the current viewing mode denies visibility | [
"Determine",
"if",
"there",
"are",
"any",
"additional",
"restrictions",
"on",
"this",
"object",
"for",
"the",
"given",
"reading",
"version",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1537-L1588 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.publishSingle | public function publishSingle()
{
$owner = $this->owner;
// get the last published version
$original = null;
if ($this->isPublished()) {
$original = self::get_by_stage($owner->baseClass(), self::LIVE)
->byID($owner->ID);
}
// Publish it
$owner->invokeWithExtensions('onBeforePublish', $original);
$owner->writeToStage(static::LIVE);
$owner->invokeWithExtensions('onAfterPublish', $original);
return true;
} | php | public function publishSingle()
{
$owner = $this->owner;
// get the last published version
$original = null;
if ($this->isPublished()) {
$original = self::get_by_stage($owner->baseClass(), self::LIVE)
->byID($owner->ID);
}
// Publish it
$owner->invokeWithExtensions('onBeforePublish', $original);
$owner->writeToStage(static::LIVE);
$owner->invokeWithExtensions('onAfterPublish', $original);
return true;
} | [
"public",
"function",
"publishSingle",
"(",
")",
"{",
"$",
"owner",
"=",
"$",
"this",
"->",
"owner",
";",
"// get the last published version",
"$",
"original",
"=",
"null",
";",
"if",
"(",
"$",
"this",
"->",
"isPublished",
"(",
")",
")",
"{",
"$",
"origi... | Publishes this object to Live, but doesn't publish owned objects.
User code should call {@see canPublish()} prior to invoking this method.
@return bool True if publish was successful | [
"Publishes",
"this",
"object",
"to",
"Live",
"but",
"doesn",
"t",
"publish",
"owned",
"objects",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1706-L1721 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.doArchive | public function doArchive()
{
$owner = $this->owner;
$owner->invokeWithExtensions('onBeforeArchive', $this);
$owner->deleteFromChangeSets();
// Unpublish without creating deleted version
$this->suppressDeletedVersion(function () use ($owner) {
$owner->doUnpublish();
$owner->deleteFromStage(static::DRAFT);
});
// Create deleted version in both stages
$this->createDeletedVersion([
static::LIVE,
static::DRAFT,
]);
$owner->invokeWithExtensions('onAfterArchive', $this);
return true;
} | php | public function doArchive()
{
$owner = $this->owner;
$owner->invokeWithExtensions('onBeforeArchive', $this);
$owner->deleteFromChangeSets();
// Unpublish without creating deleted version
$this->suppressDeletedVersion(function () use ($owner) {
$owner->doUnpublish();
$owner->deleteFromStage(static::DRAFT);
});
// Create deleted version in both stages
$this->createDeletedVersion([
static::LIVE,
static::DRAFT,
]);
$owner->invokeWithExtensions('onAfterArchive', $this);
return true;
} | [
"public",
"function",
"doArchive",
"(",
")",
"{",
"$",
"owner",
"=",
"$",
"this",
"->",
"owner",
";",
"$",
"owner",
"->",
"invokeWithExtensions",
"(",
"'onBeforeArchive'",
",",
"$",
"this",
")",
";",
"$",
"owner",
"->",
"deleteFromChangeSets",
"(",
")",
... | Removes the record from both live and stage
User code should call {@see canArchive()} prior to invoking this method.
@return bool Success | [
"Removes",
"the",
"record",
"from",
"both",
"live",
"and",
"stage"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1730-L1747 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.doUnpublish | public function doUnpublish()
{
$owner = $this->owner;
// Skip if this record isn't saved
if (!$owner->isInDB()) {
return false;
}
// Skip if this record isn't on live
if (!$owner->isPublished()) {
return false;
}
$owner->invokeWithExtensions('onBeforeUnpublish');
// Modify in isolated mode
static::withVersionedMode(function () use ($owner) {
static::set_stage(static::LIVE);
// This way our ID won't be unset
$clone = clone $owner;
$clone->delete();
});
$owner->invokeWithExtensions('onAfterUnpublish');
return true;
} | php | public function doUnpublish()
{
$owner = $this->owner;
// Skip if this record isn't saved
if (!$owner->isInDB()) {
return false;
}
// Skip if this record isn't on live
if (!$owner->isPublished()) {
return false;
}
$owner->invokeWithExtensions('onBeforeUnpublish');
// Modify in isolated mode
static::withVersionedMode(function () use ($owner) {
static::set_stage(static::LIVE);
// This way our ID won't be unset
$clone = clone $owner;
$clone->delete();
});
$owner->invokeWithExtensions('onAfterUnpublish');
return true;
} | [
"public",
"function",
"doUnpublish",
"(",
")",
"{",
"$",
"owner",
"=",
"$",
"this",
"->",
"owner",
";",
"// Skip if this record isn't saved",
"if",
"(",
"!",
"$",
"owner",
"->",
"isInDB",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Skip if this re... | Removes this record from the live site
User code should call {@see canUnpublish()} prior to invoking this method.
@return bool Flag whether the unpublish was successful | [
"Removes",
"this",
"record",
"from",
"the",
"live",
"site"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1756-L1782 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.hasPublishedOwners | public function hasPublishedOwners()
{
if (!$this->isPublished()) {
return false;
}
// Count live owners
/** @var Versioned|RecursivePublishable|DataObject $liveRecord */
$liveRecord = static::get_by_stage(get_class($this->owner), Versioned::LIVE)->byID($this->owner->ID);
return $liveRecord->findOwners(false)->count() > 0;
} | php | public function hasPublishedOwners()
{
if (!$this->isPublished()) {
return false;
}
// Count live owners
/** @var Versioned|RecursivePublishable|DataObject $liveRecord */
$liveRecord = static::get_by_stage(get_class($this->owner), Versioned::LIVE)->byID($this->owner->ID);
return $liveRecord->findOwners(false)->count() > 0;
} | [
"public",
"function",
"hasPublishedOwners",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isPublished",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Count live owners",
"/** @var Versioned|RecursivePublishable|DataObject $liveRecord */",
"$",
"liveRecord"... | Determine if this object is published, and has any published owners.
If this is true, a warning should be shown before this is published.
Note: This method returns false if the object itself is unpublished,
since owners are only considered on the same stage as the record itself.
@return bool | [
"Determine",
"if",
"this",
"object",
"is",
"published",
"and",
"has",
"any",
"published",
"owners",
".",
"If",
"this",
"is",
"true",
"a",
"warning",
"should",
"be",
"shown",
"before",
"this",
"is",
"published",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1799-L1808 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.copyVersionToStage | public function copyVersionToStage($fromStage, $toStage, $createNewVersion = true)
{
// Disallow $createNewVersion = false
if (!$createNewVersion) {
Deprecation::notice('5.0', 'copyVersionToStage no longer allows $createNewVersion to be false');
$createNewVersion = true;
}
$owner = $this->owner;
$owner->invokeWithExtensions('onBeforeVersionedPublish', $fromStage, $toStage, $createNewVersion);
// Get at specific version
$from = $this->getAtVersion($fromStage);
if (!$from) {
$baseClass = $owner->baseClass();
throw new InvalidArgumentException("Can't find {$baseClass}#{$owner->ID} in stage {$fromStage}");
}
$from->writeToStage($toStage);
$owner->invokeWithExtensions('onAfterVersionedPublish', $fromStage, $toStage, $createNewVersion);
} | php | public function copyVersionToStage($fromStage, $toStage, $createNewVersion = true)
{
// Disallow $createNewVersion = false
if (!$createNewVersion) {
Deprecation::notice('5.0', 'copyVersionToStage no longer allows $createNewVersion to be false');
$createNewVersion = true;
}
$owner = $this->owner;
$owner->invokeWithExtensions('onBeforeVersionedPublish', $fromStage, $toStage, $createNewVersion);
// Get at specific version
$from = $this->getAtVersion($fromStage);
if (!$from) {
$baseClass = $owner->baseClass();
throw new InvalidArgumentException("Can't find {$baseClass}#{$owner->ID} in stage {$fromStage}");
}
$from->writeToStage($toStage);
$owner->invokeWithExtensions('onAfterVersionedPublish', $fromStage, $toStage, $createNewVersion);
} | [
"public",
"function",
"copyVersionToStage",
"(",
"$",
"fromStage",
",",
"$",
"toStage",
",",
"$",
"createNewVersion",
"=",
"true",
")",
"{",
"// Disallow $createNewVersion = false",
"if",
"(",
"!",
"$",
"createNewVersion",
")",
"{",
"Deprecation",
"::",
"notice",
... | Move a database record from one stage to the other.
@param int|string|null $fromStage Place to copy from. Can be either a stage name or a version number.
Null copies current object to stage
@param string $toStage Place to copy to. Must be a stage name.
@param bool $createNewVersion [DEPRECATED] This parameter is ignored, as copying to stage should always
create a new version. | [
"Move",
"a",
"database",
"record",
"from",
"one",
"stage",
"to",
"the",
"other",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1851-L1870 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.stagesDiffer | public function stagesDiffer()
{
if (func_num_args() > 0) {
Deprecation::notice('5.0', 'Versioned only has two stages and stagesDiffer no longer requires parameters');
}
$id = $this->owner->ID ?: $this->owner->OldID;
if (!$id || !$this->hasStages()) {
return false;
}
$draftVersion = static::get_versionnumber_by_stage($this->owner, Versioned::DRAFT, $id);
$liveVersion = static::get_versionnumber_by_stage($this->owner, Versioned::LIVE, $id);
return $draftVersion !== $liveVersion;
} | php | public function stagesDiffer()
{
if (func_num_args() > 0) {
Deprecation::notice('5.0', 'Versioned only has two stages and stagesDiffer no longer requires parameters');
}
$id = $this->owner->ID ?: $this->owner->OldID;
if (!$id || !$this->hasStages()) {
return false;
}
$draftVersion = static::get_versionnumber_by_stage($this->owner, Versioned::DRAFT, $id);
$liveVersion = static::get_versionnumber_by_stage($this->owner, Versioned::LIVE, $id);
return $draftVersion !== $liveVersion;
} | [
"public",
"function",
"stagesDiffer",
"(",
")",
"{",
"if",
"(",
"func_num_args",
"(",
")",
">",
"0",
")",
"{",
"Deprecation",
"::",
"notice",
"(",
"'5.0'",
",",
"'Versioned only has two stages and stagesDiffer no longer requires parameters'",
")",
";",
"}",
"$",
"... | Compare two stages to see if they're different.
Only checks the version numbers, not the actual content.
@return bool | [
"Compare",
"two",
"stages",
"to",
"see",
"if",
"they",
"re",
"different",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1910-L1923 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.allVersions | public function allVersions($filter = "", $sort = "", $limit = "", $join = "", $having = "")
{
// Make sure the table names are not postfixed (e.g. _Live)
$oldMode = static::get_reading_mode();
static::set_stage(static::DRAFT);
$owner = $this->owner;
$list = DataObject::get(DataObject::getSchema()->baseDataClass($owner), $filter, $sort, $join, $limit);
if ($having) {
// @todo - This method doesn't exist on DataList
$list->having($having);
}
$query = $list->dataQuery()->query();
$baseTable = null;
foreach ($query->getFrom() as $table => $tableJoin) {
if (is_string($tableJoin) && $tableJoin[0] == '"') {
$baseTable = str_replace('"', '', $tableJoin);
} elseif (is_string($tableJoin) && substr($tableJoin, 0, 5) != 'INNER') {
$query->setFrom([
$table => "LEFT JOIN \"$table\" ON \"$table\".\"RecordID\"=\"{$baseTable}_Versions\".\"RecordID\""
. " AND \"$table\".\"Version\" = \"{$baseTable}_Versions\".\"Version\""
]);
}
$query->renameTable($table, $table . '_Versions');
}
// Add all <basetable>_Versions columns
foreach (Config::inst()->get(static::class, 'db_for_versions_table') as $name => $type) {
$query->selectField(sprintf('"%s_Versions"."%s"', $baseTable, $name), $name);
}
$query->addWhere([
"\"{$baseTable}_Versions\".\"RecordID\" = ?" => $owner->ID
]);
$query->setOrderBy(($sort) ? $sort
: "\"{$baseTable}_Versions\".\"LastEdited\" DESC, \"{$baseTable}_Versions\".\"Version\" DESC");
$records = $query->execute();
$versions = new ArrayList();
foreach ($records as $record) {
$versions->push(new Versioned_Version($record));
}
Versioned::set_reading_mode($oldMode);
return $versions;
} | php | public function allVersions($filter = "", $sort = "", $limit = "", $join = "", $having = "")
{
// Make sure the table names are not postfixed (e.g. _Live)
$oldMode = static::get_reading_mode();
static::set_stage(static::DRAFT);
$owner = $this->owner;
$list = DataObject::get(DataObject::getSchema()->baseDataClass($owner), $filter, $sort, $join, $limit);
if ($having) {
// @todo - This method doesn't exist on DataList
$list->having($having);
}
$query = $list->dataQuery()->query();
$baseTable = null;
foreach ($query->getFrom() as $table => $tableJoin) {
if (is_string($tableJoin) && $tableJoin[0] == '"') {
$baseTable = str_replace('"', '', $tableJoin);
} elseif (is_string($tableJoin) && substr($tableJoin, 0, 5) != 'INNER') {
$query->setFrom([
$table => "LEFT JOIN \"$table\" ON \"$table\".\"RecordID\"=\"{$baseTable}_Versions\".\"RecordID\""
. " AND \"$table\".\"Version\" = \"{$baseTable}_Versions\".\"Version\""
]);
}
$query->renameTable($table, $table . '_Versions');
}
// Add all <basetable>_Versions columns
foreach (Config::inst()->get(static::class, 'db_for_versions_table') as $name => $type) {
$query->selectField(sprintf('"%s_Versions"."%s"', $baseTable, $name), $name);
}
$query->addWhere([
"\"{$baseTable}_Versions\".\"RecordID\" = ?" => $owner->ID
]);
$query->setOrderBy(($sort) ? $sort
: "\"{$baseTable}_Versions\".\"LastEdited\" DESC, \"{$baseTable}_Versions\".\"Version\" DESC");
$records = $query->execute();
$versions = new ArrayList();
foreach ($records as $record) {
$versions->push(new Versioned_Version($record));
}
Versioned::set_reading_mode($oldMode);
return $versions;
} | [
"public",
"function",
"allVersions",
"(",
"$",
"filter",
"=",
"\"\"",
",",
"$",
"sort",
"=",
"\"\"",
",",
"$",
"limit",
"=",
"\"\"",
",",
"$",
"join",
"=",
"\"\"",
",",
"$",
"having",
"=",
"\"\"",
")",
"{",
"// Make sure the table names are not postfixed (... | Return a list of all the versions available.
@param string $filter
@param string $sort
@param string $limit
@param string $join @deprecated use leftJoin($table, $joinClause) instead
@param string $having @deprecated
@return ArrayList | [
"Return",
"a",
"list",
"of",
"all",
"the",
"versions",
"available",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1961-L2009 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.compareVersions | public function compareVersions($from, $to)
{
$owner = $this->owner;
$fromRecord = Versioned::get_version(get_class($owner), $owner->ID, $from);
$toRecord = Versioned::get_version(get_class($owner), $owner->ID, $to);
$diff = new DataDifferencer($fromRecord, $toRecord);
return $diff->diffedData();
} | php | public function compareVersions($from, $to)
{
$owner = $this->owner;
$fromRecord = Versioned::get_version(get_class($owner), $owner->ID, $from);
$toRecord = Versioned::get_version(get_class($owner), $owner->ID, $to);
$diff = new DataDifferencer($fromRecord, $toRecord);
return $diff->diffedData();
} | [
"public",
"function",
"compareVersions",
"(",
"$",
"from",
",",
"$",
"to",
")",
"{",
"$",
"owner",
"=",
"$",
"this",
"->",
"owner",
";",
"$",
"fromRecord",
"=",
"Versioned",
"::",
"get_version",
"(",
"get_class",
"(",
"$",
"owner",
")",
",",
"$",
"ow... | Compare two version, and return the diff between them.
@param string $from The version to compare from.
@param string $to The version to compare to.
@return DataObject | [
"Compare",
"two",
"version",
"and",
"return",
"the",
"diff",
"between",
"them",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L2019-L2028 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.baseTable | protected function baseTable($stage = null)
{
$baseTable = $this->owner->baseTable();
return $this->stageTable($baseTable, $stage);
} | php | protected function baseTable($stage = null)
{
$baseTable = $this->owner->baseTable();
return $this->stageTable($baseTable, $stage);
} | [
"protected",
"function",
"baseTable",
"(",
"$",
"stage",
"=",
"null",
")",
"{",
"$",
"baseTable",
"=",
"$",
"this",
"->",
"owner",
"->",
"baseTable",
"(",
")",
";",
"return",
"$",
"this",
"->",
"stageTable",
"(",
"$",
"baseTable",
",",
"$",
"stage",
... | Return the base table - the class that directly extends DataObject.
Protected so it doesn't conflict with DataObject::baseTable()
@param string $stage
@return string | [
"Return",
"the",
"base",
"table",
"-",
"the",
"class",
"that",
"directly",
"extends",
"DataObject",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L2038-L2042 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.choose_site_stage | public static function choose_site_stage(HTTPRequest $request)
{
$mode = static::get_default_reading_mode();
// Check any pre-existing session mode
$useSession = Config::inst()->get(static::class, 'use_session');
$updateSession = false;
if ($useSession) {
// Boot reading mode from session
$mode = $request->getSession()->get('readingMode') ?: $mode;
// Set draft site security if disabled for this session
if ($request->getSession()->get('unsecuredDraftSite')) {
static::set_draft_site_secured(false);
}
}
// Verify if querystring contains valid reading mode
$queryMode = ReadingMode::fromQueryString($request->getVars());
if ($queryMode) {
$mode = $queryMode;
$updateSession = true;
}
// Save reading mode
Versioned::set_reading_mode($mode);
// Set mode if session enabled
if ($useSession && $updateSession) {
$request->getSession()->set('readingMode', $mode);
}
if (!headers_sent() && !Director::is_cli()) {
if (Versioned::get_stage() === static::LIVE) {
// clear the cookie if it's set
if (Cookie::get('bypassStaticCache')) {
Cookie::force_expiry('bypassStaticCache', null, null, false, true /* httponly */);
}
} else {
// set the cookie if it's cleared
if (!Cookie::get('bypassStaticCache')) {
Cookie::set('bypassStaticCache', '1', 0, null, null, false, true /* httponly */);
}
}
}
} | php | public static function choose_site_stage(HTTPRequest $request)
{
$mode = static::get_default_reading_mode();
// Check any pre-existing session mode
$useSession = Config::inst()->get(static::class, 'use_session');
$updateSession = false;
if ($useSession) {
// Boot reading mode from session
$mode = $request->getSession()->get('readingMode') ?: $mode;
// Set draft site security if disabled for this session
if ($request->getSession()->get('unsecuredDraftSite')) {
static::set_draft_site_secured(false);
}
}
// Verify if querystring contains valid reading mode
$queryMode = ReadingMode::fromQueryString($request->getVars());
if ($queryMode) {
$mode = $queryMode;
$updateSession = true;
}
// Save reading mode
Versioned::set_reading_mode($mode);
// Set mode if session enabled
if ($useSession && $updateSession) {
$request->getSession()->set('readingMode', $mode);
}
if (!headers_sent() && !Director::is_cli()) {
if (Versioned::get_stage() === static::LIVE) {
// clear the cookie if it's set
if (Cookie::get('bypassStaticCache')) {
Cookie::force_expiry('bypassStaticCache', null, null, false, true /* httponly */);
}
} else {
// set the cookie if it's cleared
if (!Cookie::get('bypassStaticCache')) {
Cookie::set('bypassStaticCache', '1', 0, null, null, false, true /* httponly */);
}
}
}
} | [
"public",
"static",
"function",
"choose_site_stage",
"(",
"HTTPRequest",
"$",
"request",
")",
"{",
"$",
"mode",
"=",
"static",
"::",
"get_default_reading_mode",
"(",
")",
";",
"// Check any pre-existing session mode",
"$",
"useSession",
"=",
"Config",
"::",
"inst",
... | Choose the stage the site is currently on.
If $_GET['stage'] is set, then it will use that stage, and store it in
the session.
if $_GET['archiveDate'] is set, it will use that date, and store it in
the session.
If neither of these are set, it checks the session, otherwise the stage
is set to 'Live'.
@param HTTPRequest $request | [
"Choose",
"the",
"stage",
"the",
"site",
"is",
"currently",
"on",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L2108-L2153 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.current_archived_stage | public static function current_archived_stage()
{
$parts = explode('.', Versioned::get_reading_mode());
if (sizeof($parts) === 3 && $parts[0] == 'Archive') {
return $parts[2];
}
return static::DRAFT;
} | php | public static function current_archived_stage()
{
$parts = explode('.', Versioned::get_reading_mode());
if (sizeof($parts) === 3 && $parts[0] == 'Archive') {
return $parts[2];
}
return static::DRAFT;
} | [
"public",
"static",
"function",
"current_archived_stage",
"(",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"'.'",
",",
"Versioned",
"::",
"get_reading_mode",
"(",
")",
")",
";",
"if",
"(",
"sizeof",
"(",
"$",
"parts",
")",
"===",
"3",
"&&",
"$",
"part... | Get the current archive stage.
@return string | [
"Get",
"the",
"current",
"archive",
"stage",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L2209-L2216 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.get_draft_site_secured | public static function get_draft_site_secured()
{
if (isset(static::$is_draft_site_secured)) {
return (bool)static::$is_draft_site_secured;
}
// Config default
return (bool)Config::inst()->get(self::class, 'draft_site_secured');
} | php | public static function get_draft_site_secured()
{
if (isset(static::$is_draft_site_secured)) {
return (bool)static::$is_draft_site_secured;
}
// Config default
return (bool)Config::inst()->get(self::class, 'draft_site_secured');
} | [
"public",
"static",
"function",
"get_draft_site_secured",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"static",
"::",
"$",
"is_draft_site_secured",
")",
")",
"{",
"return",
"(",
"bool",
")",
"static",
"::",
"$",
"is_draft_site_secured",
";",
"}",
"// Config defaul... | Check if draft site should be secured.
Can be turned off if draft site unauthenticated
@return bool | [
"Check",
"if",
"draft",
"site",
"should",
"be",
"secured",
".",
"Can",
"be",
"turned",
"off",
"if",
"draft",
"site",
"unauthenticated"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L2257-L2264 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.reading_archived_date | public static function reading_archived_date($date, $stage = self::DRAFT)
{
ReadingMode::validateStage($stage);
Versioned::set_reading_mode('Archive.' . $date . '.' . $stage);
} | php | public static function reading_archived_date($date, $stage = self::DRAFT)
{
ReadingMode::validateStage($stage);
Versioned::set_reading_mode('Archive.' . $date . '.' . $stage);
} | [
"public",
"static",
"function",
"reading_archived_date",
"(",
"$",
"date",
",",
"$",
"stage",
"=",
"self",
"::",
"DRAFT",
")",
"{",
"ReadingMode",
"::",
"validateStage",
"(",
"$",
"stage",
")",
";",
"Versioned",
"::",
"set_reading_mode",
"(",
"'Archive.'",
"... | Set the reading archive date.
@param string $date New reading archived date.
@param string $stage Set stage | [
"Set",
"the",
"reading",
"archive",
"date",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L2282-L2286 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.get_one_by_stage | public static function get_one_by_stage($class, $stage, $filter = '', $cache = true, $sort = '')
{
return static::withVersionedMode(function () use ($class, $stage, $filter, $cache, $sort) {
Versioned::set_stage($stage);
return DataObject::get_one($class, $filter, $cache, $sort);
});
} | php | public static function get_one_by_stage($class, $stage, $filter = '', $cache = true, $sort = '')
{
return static::withVersionedMode(function () use ($class, $stage, $filter, $cache, $sort) {
Versioned::set_stage($stage);
return DataObject::get_one($class, $filter, $cache, $sort);
});
} | [
"public",
"static",
"function",
"get_one_by_stage",
"(",
"$",
"class",
",",
"$",
"stage",
",",
"$",
"filter",
"=",
"''",
",",
"$",
"cache",
"=",
"true",
",",
"$",
"sort",
"=",
"''",
")",
"{",
"return",
"static",
"::",
"withVersionedMode",
"(",
"functio... | Get a singleton instance of a class in the given stage.
@param string $class The name of the class.
@param string $stage The name of the stage.
@param string $filter A filter to be inserted into the WHERE clause.
@param boolean $cache Use caching.
@param string $sort A sort expression to be inserted into the ORDER BY clause.
@return DataObject | [
"Get",
"a",
"singleton",
"instance",
"of",
"a",
"class",
"in",
"the",
"given",
"stage",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L2299-L2305 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.get_versionnumber_by_stage | public static function get_versionnumber_by_stage($class, $stage, $id, $cache = true)
{
ReadingMode::validateStage($stage);
$baseClass = DataObject::getSchema()->baseDataClass($class);
$stageTable = DataObject::getSchema()->tableName($baseClass);
if ($stage === static::LIVE) {
$stageTable .= "_{$stage}";
}
// cached call
if ($cache) {
if (isset(self::$cache_versionnumber[$baseClass][$stage][$id])) {
return self::$cache_versionnumber[$baseClass][$stage][$id] ?: null;
} elseif (isset(self::$cache_versionnumber[$baseClass][$stage]['_complete'])) {
// if the cache was marked as "complete" then we know the record is missing, just return null
// this is used for treeview optimisation to avoid unnecessary re-requests for draft pages
return null;
}
}
// get version as performance-optimized SQL query (gets called for each record in the sitetree)
$version = DB::prepared_query(
"SELECT \"Version\" FROM \"$stageTable\" WHERE \"ID\" = ?",
[$id]
)->value();
// cache value (if required)
if ($cache) {
if (!isset(self::$cache_versionnumber[$baseClass])) {
self::$cache_versionnumber[$baseClass] = [];
}
if (!isset(self::$cache_versionnumber[$baseClass][$stage])) {
self::$cache_versionnumber[$baseClass][$stage] = [];
}
// Internally store nulls as 0
self::$cache_versionnumber[$baseClass][$stage][$id] = $version ?: 0;
}
return $version ?: null;
} | php | public static function get_versionnumber_by_stage($class, $stage, $id, $cache = true)
{
ReadingMode::validateStage($stage);
$baseClass = DataObject::getSchema()->baseDataClass($class);
$stageTable = DataObject::getSchema()->tableName($baseClass);
if ($stage === static::LIVE) {
$stageTable .= "_{$stage}";
}
// cached call
if ($cache) {
if (isset(self::$cache_versionnumber[$baseClass][$stage][$id])) {
return self::$cache_versionnumber[$baseClass][$stage][$id] ?: null;
} elseif (isset(self::$cache_versionnumber[$baseClass][$stage]['_complete'])) {
// if the cache was marked as "complete" then we know the record is missing, just return null
// this is used for treeview optimisation to avoid unnecessary re-requests for draft pages
return null;
}
}
// get version as performance-optimized SQL query (gets called for each record in the sitetree)
$version = DB::prepared_query(
"SELECT \"Version\" FROM \"$stageTable\" WHERE \"ID\" = ?",
[$id]
)->value();
// cache value (if required)
if ($cache) {
if (!isset(self::$cache_versionnumber[$baseClass])) {
self::$cache_versionnumber[$baseClass] = [];
}
if (!isset(self::$cache_versionnumber[$baseClass][$stage])) {
self::$cache_versionnumber[$baseClass][$stage] = [];
}
// Internally store nulls as 0
self::$cache_versionnumber[$baseClass][$stage][$id] = $version ?: 0;
}
return $version ?: null;
} | [
"public",
"static",
"function",
"get_versionnumber_by_stage",
"(",
"$",
"class",
",",
"$",
"stage",
",",
"$",
"id",
",",
"$",
"cache",
"=",
"true",
")",
"{",
"ReadingMode",
"::",
"validateStage",
"(",
"$",
"stage",
")",
";",
"$",
"baseClass",
"=",
"DataO... | Gets the current version number of a specific record.
@param string $class Class to search
@param string $stage Stage name
@param int $id ID of the record
@param bool $cache Set to true to turn on cache
@return int|null Return the version number, or null if not on this stage | [
"Gets",
"the",
"current",
"version",
"number",
"of",
"a",
"specific",
"record",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L2316-L2357 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.get_by_stage | public static function get_by_stage(
$class,
$stage,
$filter = '',
$sort = '',
$join = '',
$limit = null,
$containerClass = DataList::class
) {
ReadingMode::validateStage($stage);
$result = DataObject::get($class, $filter, $sort, $join, $limit, $containerClass);
return $result->setDataQueryParam([
'Versioned.mode' => 'stage',
'Versioned.stage' => $stage
]);
} | php | public static function get_by_stage(
$class,
$stage,
$filter = '',
$sort = '',
$join = '',
$limit = null,
$containerClass = DataList::class
) {
ReadingMode::validateStage($stage);
$result = DataObject::get($class, $filter, $sort, $join, $limit, $containerClass);
return $result->setDataQueryParam([
'Versioned.mode' => 'stage',
'Versioned.stage' => $stage
]);
} | [
"public",
"static",
"function",
"get_by_stage",
"(",
"$",
"class",
",",
"$",
"stage",
",",
"$",
"filter",
"=",
"''",
",",
"$",
"sort",
"=",
"''",
",",
"$",
"join",
"=",
"''",
",",
"$",
"limit",
"=",
"null",
",",
"$",
"containerClass",
"=",
"DataLis... | Get a set of class instances by the given stage.
@param string $class The name of the class.
@param string $stage The name of the stage.
@param string $filter A filter to be inserted into the WHERE clause.
@param string $sort A sort expression to be inserted into the ORDER BY clause.
@param string $join Deprecated, use leftJoin($table, $joinClause) instead
@param int $limit A limit on the number of records returned from the database.
@param string $containerClass The container class for the result set (default is DataList)
@return DataList A modified DataList designated to the specified stage | [
"Get",
"a",
"set",
"of",
"class",
"instances",
"by",
"the",
"given",
"stage",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L2437-L2452 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.deleteFromStage | public function deleteFromStage($stage)
{
ReadingMode::validateStage($stage);
$owner = $this->owner;
static::withVersionedMode(function () use ($stage, $owner) {
Versioned::set_stage($stage);
$clone = clone $owner;
$clone->delete();
});
// Fix the version number cache (in case you go delete from stage and then check ExistsOnLive)
$baseClass = $owner->baseClass();
self::$cache_versionnumber[$baseClass][$stage][$owner->ID] = null;
} | php | public function deleteFromStage($stage)
{
ReadingMode::validateStage($stage);
$owner = $this->owner;
static::withVersionedMode(function () use ($stage, $owner) {
Versioned::set_stage($stage);
$clone = clone $owner;
$clone->delete();
});
// Fix the version number cache (in case you go delete from stage and then check ExistsOnLive)
$baseClass = $owner->baseClass();
self::$cache_versionnumber[$baseClass][$stage][$owner->ID] = null;
} | [
"public",
"function",
"deleteFromStage",
"(",
"$",
"stage",
")",
"{",
"ReadingMode",
"::",
"validateStage",
"(",
"$",
"stage",
")",
";",
"$",
"owner",
"=",
"$",
"this",
"->",
"owner",
";",
"static",
"::",
"withVersionedMode",
"(",
"function",
"(",
")",
"... | Delete this record from the given stage
@param string $stage | [
"Delete",
"this",
"record",
"from",
"the",
"given",
"stage"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L2459-L2472 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.rollbackSingle | public function rollbackSingle($version)
{
// Validate $version and safely cast
if (isset($version) && !is_numeric($version) && $version !== self::LIVE) {
throw new InvalidArgumentException("Invalid rollback source version $version");
}
if (isset($version) && is_numeric($version)) {
$version = (int)$version;
}
// Copy version between stage
$owner = $this->owner;
$owner->invokeWithExtensions('onBeforeRollbackSingle', $version);
$owner->copyVersionToStage($version, self::DRAFT);
$owner->invokeWithExtensions('onAfterRollbackSingle', $version);
} | php | public function rollbackSingle($version)
{
// Validate $version and safely cast
if (isset($version) && !is_numeric($version) && $version !== self::LIVE) {
throw new InvalidArgumentException("Invalid rollback source version $version");
}
if (isset($version) && is_numeric($version)) {
$version = (int)$version;
}
// Copy version between stage
$owner = $this->owner;
$owner->invokeWithExtensions('onBeforeRollbackSingle', $version);
$owner->copyVersionToStage($version, self::DRAFT);
$owner->invokeWithExtensions('onAfterRollbackSingle', $version);
} | [
"public",
"function",
"rollbackSingle",
"(",
"$",
"version",
")",
"{",
"// Validate $version and safely cast",
"if",
"(",
"isset",
"(",
"$",
"version",
")",
"&&",
"!",
"is_numeric",
"(",
"$",
"version",
")",
"&&",
"$",
"version",
"!==",
"self",
"::",
"LIVE",... | Rollback draft to a given version
@param int|string|null $version Version ID or Versioned::LIVE to rollback from live.
Null to rollback current owner object. | [
"Rollback",
"draft",
"to",
"a",
"given",
"version"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L2571-L2585 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.isPublished | public function isPublished()
{
$id = $this->owner->ID ?: $this->owner->OldID;
if (!$id) {
return false;
}
// Non-staged objects are considered "published" if saved
if (!$this->hasStages()) {
return true;
}
$liveVersion = static::get_versionnumber_by_stage($this->owner, Versioned::LIVE, $id);
return (bool)$liveVersion;
} | php | public function isPublished()
{
$id = $this->owner->ID ?: $this->owner->OldID;
if (!$id) {
return false;
}
// Non-staged objects are considered "published" if saved
if (!$this->hasStages()) {
return true;
}
$liveVersion = static::get_versionnumber_by_stage($this->owner, Versioned::LIVE, $id);
return (bool)$liveVersion;
} | [
"public",
"function",
"isPublished",
"(",
")",
"{",
"$",
"id",
"=",
"$",
"this",
"->",
"owner",
"->",
"ID",
"?",
":",
"$",
"this",
"->",
"owner",
"->",
"OldID",
";",
"if",
"(",
"!",
"$",
"id",
")",
"{",
"return",
"false",
";",
"}",
"// Non-staged... | Check if this record exists on live
@return bool | [
"Check",
"if",
"this",
"record",
"exists",
"on",
"live"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L2664-L2678 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.isArchived | public function isArchived()
{
$id = $this->owner->ID ?: $this->owner->OldID;
return $id && !$this->isOnDraft() && !$this->isPublished();
} | php | public function isArchived()
{
$id = $this->owner->ID ?: $this->owner->OldID;
return $id && !$this->isOnDraft() && !$this->isPublished();
} | [
"public",
"function",
"isArchived",
"(",
")",
"{",
"$",
"id",
"=",
"$",
"this",
"->",
"owner",
"->",
"ID",
"?",
":",
"$",
"this",
"->",
"owner",
"->",
"OldID",
";",
"return",
"$",
"id",
"&&",
"!",
"$",
"this",
"->",
"isOnDraft",
"(",
")",
"&&",
... | Check if page doesn't exist on any stage, but used to be
@return bool | [
"Check",
"if",
"page",
"doesn",
"t",
"exist",
"on",
"any",
"stage",
"but",
"used",
"to",
"be"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L2685-L2689 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.isOnDraft | public function isOnDraft()
{
$id = $this->owner->ID ?: $this->owner->OldID;
if (!$id) {
return false;
}
if (!$this->hasStages()) {
return true;
}
$draftVersion = static::get_versionnumber_by_stage($this->owner, Versioned::DRAFT, $id);
return (bool)$draftVersion;
} | php | public function isOnDraft()
{
$id = $this->owner->ID ?: $this->owner->OldID;
if (!$id) {
return false;
}
if (!$this->hasStages()) {
return true;
}
$draftVersion = static::get_versionnumber_by_stage($this->owner, Versioned::DRAFT, $id);
return (bool)$draftVersion;
} | [
"public",
"function",
"isOnDraft",
"(",
")",
"{",
"$",
"id",
"=",
"$",
"this",
"->",
"owner",
"->",
"ID",
"?",
":",
"$",
"this",
"->",
"owner",
"->",
"OldID",
";",
"if",
"(",
"!",
"$",
"id",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"... | Check if this record exists on the draft stage
@return bool | [
"Check",
"if",
"this",
"record",
"exists",
"on",
"the",
"draft",
"stage"
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L2696-L2708 | train |
silverstripe/silverstripe-versioned | src/Versioned.php | Versioned.get_version | public static function get_version($class, $id, $version)
{
$baseClass = DataObject::getSchema()->baseDataClass($class);
$list = DataList::create($baseClass)
->setDataQueryParam([
"Versioned.mode" => 'version',
"Versioned.version" => $version
]);
return $list->byID($id);
} | php | public static function get_version($class, $id, $version)
{
$baseClass = DataObject::getSchema()->baseDataClass($class);
$list = DataList::create($baseClass)
->setDataQueryParam([
"Versioned.mode" => 'version',
"Versioned.version" => $version
]);
return $list->byID($id);
} | [
"public",
"static",
"function",
"get_version",
"(",
"$",
"class",
",",
"$",
"id",
",",
"$",
"version",
")",
"{",
"$",
"baseClass",
"=",
"DataObject",
"::",
"getSchema",
"(",
")",
"->",
"baseDataClass",
"(",
"$",
"class",
")",
";",
"$",
"list",
"=",
"... | Return the specific version of the given id.
Caution: The record is retrieved as a DataObject, but saving back
modifications via write() will create a new version, rather than
modifying the existing one.
@param string $class
@param int $id
@param int $version
@return DataObject | [
"Return",
"the",
"specific",
"version",
"of",
"the",
"given",
"id",
"."
] | bddf25fd3a713e7ed7a861d6c6992febc3c7998b | https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L2777-L2787 | train |
UndefinedOffset/SortableGridField | src/Forms/GridFieldSortableRows.php | GridFieldSortableRows.getManipulatedData | public function getManipulatedData(GridField $gridField, SS_List $dataList)
{
//Detect and correct items with a sort column value of 0 (push to bottom)
$this->fixSortColumn($gridField, $dataList);
$headerState = $gridField->State->GridFieldSortableHeader;
$state = $gridField->State->GridFieldSortableRows;
if ((!is_bool($state->sortableToggle) || $state->sortableToggle === false) && $headerState && is_string($headerState->SortColumn) && is_string($headerState->SortDirection)) {
return $dataList->sort($headerState->SortColumn, $headerState->SortDirection);
}
if ($state->sortableToggle === true) {
$gridField->getConfig()->removeComponentsByType(GridFieldFilterHeader::class);
$gridField->getConfig()->removeComponentsByType(GridFieldSortableHeader::class);
}
return $dataList->sort($this->sortColumn);
} | php | public function getManipulatedData(GridField $gridField, SS_List $dataList)
{
//Detect and correct items with a sort column value of 0 (push to bottom)
$this->fixSortColumn($gridField, $dataList);
$headerState = $gridField->State->GridFieldSortableHeader;
$state = $gridField->State->GridFieldSortableRows;
if ((!is_bool($state->sortableToggle) || $state->sortableToggle === false) && $headerState && is_string($headerState->SortColumn) && is_string($headerState->SortDirection)) {
return $dataList->sort($headerState->SortColumn, $headerState->SortDirection);
}
if ($state->sortableToggle === true) {
$gridField->getConfig()->removeComponentsByType(GridFieldFilterHeader::class);
$gridField->getConfig()->removeComponentsByType(GridFieldSortableHeader::class);
}
return $dataList->sort($this->sortColumn);
} | [
"public",
"function",
"getManipulatedData",
"(",
"GridField",
"$",
"gridField",
",",
"SS_List",
"$",
"dataList",
")",
"{",
"//Detect and correct items with a sort column value of 0 (push to bottom)",
"$",
"this",
"->",
"fixSortColumn",
"(",
"$",
"gridField",
",",
"$",
"... | Manipulate the datalist as needed by this grid modifier.
@param GridField $gridField Grid Field Reference
@param SS_List|DataList $dataList Data List to adjust
@return DataList Modified Data List | [
"Manipulate",
"the",
"datalist",
"as",
"needed",
"by",
"this",
"grid",
"modifier",
"."
] | af492d02675f1222197f6d1dd1d32122fb4cc1cb | https://github.com/UndefinedOffset/SortableGridField/blob/af492d02675f1222197f6d1dd1d32122fb4cc1cb/src/Forms/GridFieldSortableRows.php#L151-L169 | train |
UndefinedOffset/SortableGridField | src/Forms/GridFieldSortableRows.php | GridFieldSortableRows.handleAction | public function handleAction(GridField $gridField, $actionName, $arguments, $data)
{
$state = $gridField->State->GridFieldSortableRows;
if (!is_bool($state->sortableToggle)) {
$state->sortableToggle = false;
} else if ($state->sortableToggle == true) {
$gridField->getConfig()->removeComponentsByType(GridFieldFilterHeader::class);
$gridField->getConfig()->removeComponentsByType(GridFieldSortableHeader::class);
}
if ($actionName == 'savegridrowsort') {
return $this->saveGridRowSort($gridField, $data);
} else if ($actionName == 'sorttopage') {
return $this->sortToPage($gridField, $data);
}
} | php | public function handleAction(GridField $gridField, $actionName, $arguments, $data)
{
$state = $gridField->State->GridFieldSortableRows;
if (!is_bool($state->sortableToggle)) {
$state->sortableToggle = false;
} else if ($state->sortableToggle == true) {
$gridField->getConfig()->removeComponentsByType(GridFieldFilterHeader::class);
$gridField->getConfig()->removeComponentsByType(GridFieldSortableHeader::class);
}
if ($actionName == 'savegridrowsort') {
return $this->saveGridRowSort($gridField, $data);
} else if ($actionName == 'sorttopage') {
return $this->sortToPage($gridField, $data);
}
} | [
"public",
"function",
"handleAction",
"(",
"GridField",
"$",
"gridField",
",",
"$",
"actionName",
",",
"$",
"arguments",
",",
"$",
"data",
")",
"{",
"$",
"state",
"=",
"$",
"gridField",
"->",
"State",
"->",
"GridFieldSortableRows",
";",
"if",
"(",
"!",
"... | Handle an action on the given grid field.
@param GridField $gridField Grid Field Reference
@param String $actionName Action identifier, see {@link getActions()}.
@param array $arguments Arguments relevant for this
@param array $data All form data | [
"Handle",
"an",
"action",
"on",
"the",
"given",
"grid",
"field",
"."
] | af492d02675f1222197f6d1dd1d32122fb4cc1cb | https://github.com/UndefinedOffset/SortableGridField/blob/af492d02675f1222197f6d1dd1d32122fb4cc1cb/src/Forms/GridFieldSortableRows.php#L429-L445 | train |
pusher/chatkit-server-php | src/Chatkit.php | Chatkit.log | protected function log($msg)
{
if (is_null($this->logger) === false) {
$this->logger->log('Chatkit: '.$msg);
}
} | php | protected function log($msg)
{
if (is_null($this->logger) === false) {
$this->logger->log('Chatkit: '.$msg);
}
} | [
"protected",
"function",
"log",
"(",
"$",
"msg",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"logger",
")",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"log",
"(",
"'Chatkit: '",
".",
"$",
"msg",
")",
";",
"}",
"}"
] | Log a string.
@param string $msg The message to log
@return void | [
"Log",
"a",
"string",
"."
] | 13975a4d89a109c1fe3e16e4e0441bab82ec5ad1 | https://github.com/pusher/chatkit-server-php/blob/13975a4d89a109c1fe3e16e4e0441bab82ec5ad1/src/Chatkit.php#L157-L162 | train |
pusher/chatkit-server-php | src/Chatkit.php | Chatkit.createRoom | public function createRoom($options)
{
if (!isset($options['creator_id'])) {
throw new MissingArgumentException('You must provide the ID of the user creating the room');
}
if (!isset($options['name'])) {
throw new MissingArgumentException('You must provide a name for the room');
}
$body = [
'name' => $options['name'],
'private' => false
];
if (isset($options['private'])) {
$body['private'] = $options['private'];
}
if (isset($options['user_ids'])) {
$body['user_ids'] = $options['user_ids'];
}
if (isset($options['custom_data'])) {
$body['custom_data'] = $options['custom_data'];
}
$token = $this->getServerToken([ 'user_id' => $options['creator_id'] ])['token'];
return $this->apiRequest([
'method' => 'POST',
'path' => '/rooms',
'jwt' => $token,
'body' => $body
]);
} | php | public function createRoom($options)
{
if (!isset($options['creator_id'])) {
throw new MissingArgumentException('You must provide the ID of the user creating the room');
}
if (!isset($options['name'])) {
throw new MissingArgumentException('You must provide a name for the room');
}
$body = [
'name' => $options['name'],
'private' => false
];
if (isset($options['private'])) {
$body['private'] = $options['private'];
}
if (isset($options['user_ids'])) {
$body['user_ids'] = $options['user_ids'];
}
if (isset($options['custom_data'])) {
$body['custom_data'] = $options['custom_data'];
}
$token = $this->getServerToken([ 'user_id' => $options['creator_id'] ])['token'];
return $this->apiRequest([
'method' => 'POST',
'path' => '/rooms',
'jwt' => $token,
'body' => $body
]);
} | [
"public",
"function",
"createRoom",
"(",
"$",
"options",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"'creator_id'",
"]",
")",
")",
"{",
"throw",
"new",
"MissingArgumentException",
"(",
"'You must provide the ID of the user creating the room'",
")... | Creates a new room.
@param array $options The room options
[Available Options]
• creator_id (string|required): Represents the ID of the user that you want to create the room.
• name (string|optional): Represents the name with which the room is identified.
A room name must not be longer than 40 characters and can only contain lowercase letters,
numbers, underscores and hyphens.
• private (boolean|optional): Indicates if a room should be private or public. Private by default.
• user_ids (array|optional): If you wish to add users to the room at the point of creation,
you may provide their user IDs.
. custom_data (assoc array|optional): If you wish to attach some custom data to a room,
you may provide a list of key value pairs.
@return array | [
"Creates",
"a",
"new",
"room",
"."
] | 13975a4d89a109c1fe3e16e4e0441bab82ec5ad1 | https://github.com/pusher/chatkit-server-php/blob/13975a4d89a109c1fe3e16e4e0441bab82ec5ad1/src/Chatkit.php#L355-L386 | train |
pusher/chatkit-server-php | src/Chatkit.php | Chatkit.deleteRoom | public function deleteRoom($options)
{
if (!isset($options['id'])) {
throw new MissingArgumentException('You must provide the ID of the room to delete');
}
$room_id = rawurlencode($options['id']);
return $this->apiRequest([
'method' => 'DELETE',
'path' => "/rooms/$room_id",
'jwt' => $this->getServerToken()['token']
]);
} | php | public function deleteRoom($options)
{
if (!isset($options['id'])) {
throw new MissingArgumentException('You must provide the ID of the room to delete');
}
$room_id = rawurlencode($options['id']);
return $this->apiRequest([
'method' => 'DELETE',
'path' => "/rooms/$room_id",
'jwt' => $this->getServerToken()['token']
]);
} | [
"public",
"function",
"deleteRoom",
"(",
"$",
"options",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"'id'",
"]",
")",
")",
"{",
"throw",
"new",
"MissingArgumentException",
"(",
"'You must provide the ID of the room to delete'",
")",
";",
"}",... | Deletes a room | [
"Deletes",
"a",
"room"
] | 13975a4d89a109c1fe3e16e4e0441bab82ec5ad1 | https://github.com/pusher/chatkit-server-php/blob/13975a4d89a109c1fe3e16e4e0441bab82ec5ad1/src/Chatkit.php#L418-L431 | train |
pusher/chatkit-server-php | src/Chatkit.php | Chatkit.getRoomMessages | public function getRoomMessages($options)
{
if (!isset($options['room_id'])) {
throw new MissingArgumentException('You must provide the ID of the room to fetch messages from');
}
$query_params = [];
if (!empty($options['initial_id'])) {
$query_params['initial_id'] = $options['initial_id'];
}
if (!empty($options['limit'])) {
$query_params['limit'] = $options['limit'];
}
if (!empty($options['direction'])) {
$query_params['direction'] = $options['direction'];
}
$room_id = rawurlencode($options['room_id']);
return $this->apiRequestV2([
'method' => 'GET',
'path' => "/rooms/$room_id/messages",
'jwt' => $this->getServerToken()['token'],
'query' => $query_params
]);
} | php | public function getRoomMessages($options)
{
if (!isset($options['room_id'])) {
throw new MissingArgumentException('You must provide the ID of the room to fetch messages from');
}
$query_params = [];
if (!empty($options['initial_id'])) {
$query_params['initial_id'] = $options['initial_id'];
}
if (!empty($options['limit'])) {
$query_params['limit'] = $options['limit'];
}
if (!empty($options['direction'])) {
$query_params['direction'] = $options['direction'];
}
$room_id = rawurlencode($options['room_id']);
return $this->apiRequestV2([
'method' => 'GET',
'path' => "/rooms/$room_id/messages",
'jwt' => $this->getServerToken()['token'],
'query' => $query_params
]);
} | [
"public",
"function",
"getRoomMessages",
"(",
"$",
"options",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"'room_id'",
"]",
")",
")",
"{",
"throw",
"new",
"MissingArgumentException",
"(",
"'You must provide the ID of the room to fetch messages from'... | Get messages in a room
@param array $options
[Available Options]
• room_id (string|required): Represents the ID of the room that you want to get the messages for.
• initial_id (integer|optional): Starting ID of the range of messages.
• limit (integer|optional): Number of messages to return
• direction (string|optional): Order of messages - one of newer or older
@return array
@throws ChatkitException or MissingArgumentException | [
"Get",
"messages",
"in",
"a",
"room"
] | 13975a4d89a109c1fe3e16e4e0441bab82ec5ad1 | https://github.com/pusher/chatkit-server-php/blob/13975a4d89a109c1fe3e16e4e0441bab82ec5ad1/src/Chatkit.php#L537-L562 | train |
pusher/chatkit-server-php | src/Chatkit.php | Chatkit.getReadCursorsForUser | public function getReadCursorsForUser($options)
{
if (!isset($options['user_id'])) {
throw new MissingArgumentException('You must provide the ID of the user that you want the read cursors for');
}
$user_id = rawurlencode($options['user_id']);
return $this->cursorsRequest([
'method' => 'GET',
'path' => "/cursors/0/users/$user_id",
'jwt' => $this->getServerToken()['token']
]);
} | php | public function getReadCursorsForUser($options)
{
if (!isset($options['user_id'])) {
throw new MissingArgumentException('You must provide the ID of the user that you want the read cursors for');
}
$user_id = rawurlencode($options['user_id']);
return $this->cursorsRequest([
'method' => 'GET',
'path' => "/cursors/0/users/$user_id",
'jwt' => $this->getServerToken()['token']
]);
} | [
"public",
"function",
"getReadCursorsForUser",
"(",
"$",
"options",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"'user_id'",
"]",
")",
")",
"{",
"throw",
"new",
"MissingArgumentException",
"(",
"'You must provide the ID of the user that you want the... | Get all read cursors for a user
@param array $options
[Available Options]
• user_id (string|required): Represents the ID of the user that you want to get the read cursors for.
@return array
@throws ChatkitException or MissingArgumentException | [
"Get",
"all",
"read",
"cursors",
"for",
"a",
"user"
] | 13975a4d89a109c1fe3e16e4e0441bab82ec5ad1 | https://github.com/pusher/chatkit-server-php/blob/13975a4d89a109c1fe3e16e4e0441bab82ec5ad1/src/Chatkit.php#L867-L880 | train |
pusher/chatkit-server-php | src/Chatkit.php | Chatkit.getReadCursorsForRoom | public function getReadCursorsForRoom($options)
{
if (!isset($options['room_id'])) {
throw new MissingArgumentException('You must provide the ID of the room that you want the read cursors for');
}
$room_id = rawurlencode($options['room_id']);
return $this->cursorsRequest([
'method' => 'GET',
'path' => "/cursors/0/rooms/$room_id",
'jwt' => $this->getServerToken()['token']
]);
} | php | public function getReadCursorsForRoom($options)
{
if (!isset($options['room_id'])) {
throw new MissingArgumentException('You must provide the ID of the room that you want the read cursors for');
}
$room_id = rawurlencode($options['room_id']);
return $this->cursorsRequest([
'method' => 'GET',
'path' => "/cursors/0/rooms/$room_id",
'jwt' => $this->getServerToken()['token']
]);
} | [
"public",
"function",
"getReadCursorsForRoom",
"(",
"$",
"options",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"'room_id'",
"]",
")",
")",
"{",
"throw",
"new",
"MissingArgumentException",
"(",
"'You must provide the ID of the room that you want the... | Get all read cursors for a room
@param array $options
[Available Options]
• room_id (string|required): Represents the ID of the room that you want to get the read cursors for.
@return array
@throws ChatkitException or MissingArgumentException | [
"Get",
"all",
"read",
"cursors",
"for",
"a",
"room"
] | 13975a4d89a109c1fe3e16e4e0441bab82ec5ad1 | https://github.com/pusher/chatkit-server-php/blob/13975a4d89a109c1fe3e16e4e0441bab82ec5ad1/src/Chatkit.php#L891-L904 | train |
pusher/chatkit-server-php | src/Chatkit.php | Chatkit.createCurl | protected function createCurl($service_settings, $path, $jwt, $request_method, $body = null, $query_params = array())
{
$split_instance_locator = explode(':', $this->settings['instance_locator']);
$scheme = 'https';
$host = $split_instance_locator[1].'.pusherplatform.io';
$service_path_fragment = $service_settings['service_name'].'/'.$service_settings['service_version'];
$instance_id = $split_instance_locator[2];
$full_url = $scheme.'://'.$host.'/services/'.$service_path_fragment.'/'.$instance_id.$path;
$query = http_build_query($query_params);
// Passing foo = [1, 2, 3] to query params will encode it as foo[0]=1&foo[1]=2
// however, we want foo=1&foo=2 (to treat them as an array)
$query_string = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $query);
$final_url = $full_url.'?'.$query_string;
$this->log('INFO: createCurl( '.$final_url.' )');
return $this->createRawCurl($request_method, $final_url, $body, null, $jwt, true);
} | php | protected function createCurl($service_settings, $path, $jwt, $request_method, $body = null, $query_params = array())
{
$split_instance_locator = explode(':', $this->settings['instance_locator']);
$scheme = 'https';
$host = $split_instance_locator[1].'.pusherplatform.io';
$service_path_fragment = $service_settings['service_name'].'/'.$service_settings['service_version'];
$instance_id = $split_instance_locator[2];
$full_url = $scheme.'://'.$host.'/services/'.$service_path_fragment.'/'.$instance_id.$path;
$query = http_build_query($query_params);
// Passing foo = [1, 2, 3] to query params will encode it as foo[0]=1&foo[1]=2
// however, we want foo=1&foo=2 (to treat them as an array)
$query_string = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $query);
$final_url = $full_url.'?'.$query_string;
$this->log('INFO: createCurl( '.$final_url.' )');
return $this->createRawCurl($request_method, $final_url, $body, null, $jwt, true);
} | [
"protected",
"function",
"createCurl",
"(",
"$",
"service_settings",
",",
"$",
"path",
",",
"$",
"jwt",
",",
"$",
"request_method",
",",
"$",
"body",
"=",
"null",
",",
"$",
"query_params",
"=",
"array",
"(",
")",
")",
"{",
"$",
"split_instance_locator",
... | Utility function used to create the curl object setup to interact with the Pusher API | [
"Utility",
"function",
"used",
"to",
"create",
"the",
"curl",
"object",
"setup",
"to",
"interact",
"with",
"the",
"Pusher",
"API"
] | 13975a4d89a109c1fe3e16e4e0441bab82ec5ad1 | https://github.com/pusher/chatkit-server-php/blob/13975a4d89a109c1fe3e16e4e0441bab82ec5ad1/src/Chatkit.php#L1148-L1167 | train |
pusher/chatkit-server-php | src/Chatkit.php | Chatkit.createRawCurl | protected function createRawCurl($request_method, $url, $body = null, $content_type = null, $jwt = null, $encode_json = false)
{
// Create or reuse existing curl handle
if (null === $this->ch) {
$this->ch = curl_init();
}
if ($this->ch === false) {
throw new ConfigurationException('Could not initialise cURL!');
}
$ch = $this->ch;
// curl handle is not reusable unless reset
if (function_exists('curl_reset')) {
curl_reset($ch);
}
$headers = array();
if(!is_null($jwt)) {
array_push($headers, 'Authorization: Bearer '.$jwt);
}
if(!is_null($content_type)) {
array_push($headers, 'Content-Type: '.$content_type);
}
// Set cURL opts and execute request
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->settings['timeout']);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request_method);
if (!is_null($body)) {
if ($encode_json) {
$body = json_encode($body, JSON_ERROR_UTF8);
array_push($headers, 'Content-Type: application/json');
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
array_push($headers, 'Content-Length: '.strlen($body));
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Set custom curl options
if (!empty($this->settings['curl_options'])) {
foreach ($this->settings['curl_options'] as $option => $value) {
curl_setopt($ch, $option, $value);
}
}
return $ch;
} | php | protected function createRawCurl($request_method, $url, $body = null, $content_type = null, $jwt = null, $encode_json = false)
{
// Create or reuse existing curl handle
if (null === $this->ch) {
$this->ch = curl_init();
}
if ($this->ch === false) {
throw new ConfigurationException('Could not initialise cURL!');
}
$ch = $this->ch;
// curl handle is not reusable unless reset
if (function_exists('curl_reset')) {
curl_reset($ch);
}
$headers = array();
if(!is_null($jwt)) {
array_push($headers, 'Authorization: Bearer '.$jwt);
}
if(!is_null($content_type)) {
array_push($headers, 'Content-Type: '.$content_type);
}
// Set cURL opts and execute request
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->settings['timeout']);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request_method);
if (!is_null($body)) {
if ($encode_json) {
$body = json_encode($body, JSON_ERROR_UTF8);
array_push($headers, 'Content-Type: application/json');
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
array_push($headers, 'Content-Length: '.strlen($body));
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Set custom curl options
if (!empty($this->settings['curl_options'])) {
foreach ($this->settings['curl_options'] as $option => $value) {
curl_setopt($ch, $option, $value);
}
}
return $ch;
} | [
"protected",
"function",
"createRawCurl",
"(",
"$",
"request_method",
",",
"$",
"url",
",",
"$",
"body",
"=",
"null",
",",
"$",
"content_type",
"=",
"null",
",",
"$",
"jwt",
"=",
"null",
",",
"$",
"encode_json",
"=",
"false",
")",
"{",
"// Create or reus... | Utility function used to create the curl object with common settings. | [
"Utility",
"function",
"used",
"to",
"create",
"the",
"curl",
"object",
"with",
"common",
"settings",
"."
] | 13975a4d89a109c1fe3e16e4e0441bab82ec5ad1 | https://github.com/pusher/chatkit-server-php/blob/13975a4d89a109c1fe3e16e4e0441bab82ec5ad1/src/Chatkit.php#L1172-L1222 | train |
pusher/chatkit-server-php | src/Chatkit.php | Chatkit.execCurl | protected function execCurl($ch)
{
$headers = [];
$response = [];
curl_setopt($ch, CURLOPT_HEADERFUNCTION,
function($curl, $header) use (&$headers)
{
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) {
return $len;
}
$name = strtolower(trim($header[0]));
if (!array_key_exists($name, $headers)) {
$headers[$name] = [trim($header[1])];
} else {
$headers[$name][] = trim($header[1]);
}
return $len;
}
);
$data = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$body = empty($data) ? null : json_decode($data, true);
$response = [
'status' => $status,
'headers' => $headers,
'body' => $body
];
// inform the user of a connection failure
if ($status == 0 || $response['body'] === false) {
throw new ConnectionException(curl_error($ch));
}
// or an error response from Chatkit
if ($status >= 400) {
$this->log('ERROR: execCurl error: '.print_r($response, true));
throw (new ChatkitException($response['body']['error_description'], $status))->setBody($response['body']);
}
$this->log('INFO: execCurl response: '.print_r($response, true));
return $response;
} | php | protected function execCurl($ch)
{
$headers = [];
$response = [];
curl_setopt($ch, CURLOPT_HEADERFUNCTION,
function($curl, $header) use (&$headers)
{
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) {
return $len;
}
$name = strtolower(trim($header[0]));
if (!array_key_exists($name, $headers)) {
$headers[$name] = [trim($header[1])];
} else {
$headers[$name][] = trim($header[1]);
}
return $len;
}
);
$data = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$body = empty($data) ? null : json_decode($data, true);
$response = [
'status' => $status,
'headers' => $headers,
'body' => $body
];
// inform the user of a connection failure
if ($status == 0 || $response['body'] === false) {
throw new ConnectionException(curl_error($ch));
}
// or an error response from Chatkit
if ($status >= 400) {
$this->log('ERROR: execCurl error: '.print_r($response, true));
throw (new ChatkitException($response['body']['error_description'], $status))->setBody($response['body']);
}
$this->log('INFO: execCurl response: '.print_r($response, true));
return $response;
} | [
"protected",
"function",
"execCurl",
"(",
"$",
"ch",
")",
"{",
"$",
"headers",
"=",
"[",
"]",
";",
"$",
"response",
"=",
"[",
"]",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_HEADERFUNCTION",
",",
"function",
"(",
"$",
"curl",
",",
"$",
"header... | Utility function to execute curl and create capture response information. | [
"Utility",
"function",
"to",
"execute",
"curl",
"and",
"create",
"capture",
"response",
"information",
"."
] | 13975a4d89a109c1fe3e16e4e0441bab82ec5ad1 | https://github.com/pusher/chatkit-server-php/blob/13975a4d89a109c1fe3e16e4e0441bab82ec5ad1/src/Chatkit.php#L1236-L1284 | train |
guzzle/command | src/ServiceClient.php | ServiceClient.createCommandHandler | private function createCommandHandler()
{
return function (CommandInterface $command) {
return Promise\coroutine(function () use ($command) {
// Prepare the HTTP options.
$opts = $command['@http'] ?: [];
unset($command['@http']);
try {
// Prepare the request from the command and send it.
$request = $this->transformCommandToRequest($command);
$promise = $this->httpClient->sendAsync($request, $opts);
// Create a result from the response.
$response = (yield $promise);
yield $this->transformResponseToResult($response, $request, $command);
} catch (\Exception $e) {
throw CommandException::fromPrevious($command, $e);
}
});
};
} | php | private function createCommandHandler()
{
return function (CommandInterface $command) {
return Promise\coroutine(function () use ($command) {
// Prepare the HTTP options.
$opts = $command['@http'] ?: [];
unset($command['@http']);
try {
// Prepare the request from the command and send it.
$request = $this->transformCommandToRequest($command);
$promise = $this->httpClient->sendAsync($request, $opts);
// Create a result from the response.
$response = (yield $promise);
yield $this->transformResponseToResult($response, $request, $command);
} catch (\Exception $e) {
throw CommandException::fromPrevious($command, $e);
}
});
};
} | [
"private",
"function",
"createCommandHandler",
"(",
")",
"{",
"return",
"function",
"(",
"CommandInterface",
"$",
"command",
")",
"{",
"return",
"Promise",
"\\",
"coroutine",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"command",
")",
"{",
"// Prepare the HTTP... | Defines the main handler for commands that uses the HTTP client.
@return callable | [
"Defines",
"the",
"main",
"handler",
"for",
"commands",
"that",
"uses",
"the",
"HTTP",
"client",
"."
] | 03f4ad0724fc8d15b48459c1388c8c68ed338c3f | https://github.com/guzzle/command/blob/03f4ad0724fc8d15b48459c1388c8c68ed338c3f/src/ServiceClient.php#L162-L183 | train |
guzzle/command | src/ServiceClient.php | ServiceClient.transformResponseToResult | private function transformResponseToResult(
ResponseInterface $response,
RequestInterface $request,
CommandInterface $command
) {
$transform = $this->responseToResultTransformer;
return $transform($response, $request, $command);
} | php | private function transformResponseToResult(
ResponseInterface $response,
RequestInterface $request,
CommandInterface $command
) {
$transform = $this->responseToResultTransformer;
return $transform($response, $request, $command);
} | [
"private",
"function",
"transformResponseToResult",
"(",
"ResponseInterface",
"$",
"response",
",",
"RequestInterface",
"$",
"request",
",",
"CommandInterface",
"$",
"command",
")",
"{",
"$",
"transform",
"=",
"$",
"this",
"->",
"responseToResultTransformer",
";",
"... | Transforms a Response object, also using data from the Request object,
into a Result object.
@param ResponseInterface $response
@param RequestInterface $request
@param CommandInterface $command
@return ResultInterface | [
"Transforms",
"a",
"Response",
"object",
"also",
"using",
"data",
"from",
"the",
"Request",
"object",
"into",
"a",
"Result",
"object",
"."
] | 03f4ad0724fc8d15b48459c1388c8c68ed338c3f | https://github.com/guzzle/command/blob/03f4ad0724fc8d15b48459c1388c8c68ed338c3f/src/ServiceClient.php#L208-L216 | train |
wp-cli/checksum-command | src/Checksum_Base_Command.php | Checksum_Base_Command._read | protected static function _read( $url ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore -- Could be used in classes extending this class.
$headers = array( 'Accept' => 'application/json' );
$response = Utils\http_request(
'GET',
$url,
null,
$headers,
array( 'timeout' => 30 )
);
if ( 200 === $response->status_code ) {
return $response->body;
}
WP_CLI::error( "Couldn't fetch response from {$url} (HTTP code {$response->status_code})." );
} | php | protected static function _read( $url ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore -- Could be used in classes extending this class.
$headers = array( 'Accept' => 'application/json' );
$response = Utils\http_request(
'GET',
$url,
null,
$headers,
array( 'timeout' => 30 )
);
if ( 200 === $response->status_code ) {
return $response->body;
}
WP_CLI::error( "Couldn't fetch response from {$url} (HTTP code {$response->status_code})." );
} | [
"protected",
"static",
"function",
"_read",
"(",
"$",
"url",
")",
"{",
"// phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore -- Could be used in classes extending this class.",
"$",
"headers",
"=",
"array",
"(",
"'Accept'",
"=>",
"'application/json'",
")",
";",
"$",
"r... | Read a remote file and return its contents.
@param string $url URL of the remote file to read.
@return mixed | [
"Read",
"a",
"remote",
"file",
"and",
"return",
"its",
"contents",
"."
] | 7db66668ec116c5ccef7bc27b4354fa81b85018a | https://github.com/wp-cli/checksum-command/blob/7db66668ec116c5ccef7bc27b4354fa81b85018a/src/Checksum_Base_Command.php#L30-L43 | train |
wp-cli/checksum-command | src/Checksum_Base_Command.php | Checksum_Base_Command.get_files | protected function get_files( $path ) {
$filtered_files = array();
try {
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(
$path,
RecursiveDirectoryIterator::SKIP_DOTS
),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ( $files as $file_info ) {
$pathname = self::normalize_directory_separators( substr( $file_info->getPathname(), strlen( $path ) ) );
if ( $file_info->isFile() && $this->filter_file( $pathname ) ) {
$filtered_files[] = $pathname;
}
}
} catch ( Exception $e ) {
WP_CLI::error( $e->getMessage() );
}
return $filtered_files;
} | php | protected function get_files( $path ) {
$filtered_files = array();
try {
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(
$path,
RecursiveDirectoryIterator::SKIP_DOTS
),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ( $files as $file_info ) {
$pathname = self::normalize_directory_separators( substr( $file_info->getPathname(), strlen( $path ) ) );
if ( $file_info->isFile() && $this->filter_file( $pathname ) ) {
$filtered_files[] = $pathname;
}
}
} catch ( Exception $e ) {
WP_CLI::error( $e->getMessage() );
}
return $filtered_files;
} | [
"protected",
"function",
"get_files",
"(",
"$",
"path",
")",
"{",
"$",
"filtered_files",
"=",
"array",
"(",
")",
";",
"try",
"{",
"$",
"files",
"=",
"new",
"RecursiveIteratorIterator",
"(",
"new",
"RecursiveDirectoryIterator",
"(",
"$",
"path",
",",
"Recursi... | Recursively get the list of files for a given path.
@param string $path Root path to start the recursive traversal in.
@return array<string> | [
"Recursively",
"get",
"the",
"list",
"of",
"files",
"for",
"a",
"given",
"path",
"."
] | 7db66668ec116c5ccef7bc27b4354fa81b85018a | https://github.com/wp-cli/checksum-command/blob/7db66668ec116c5ccef7bc27b4354fa81b85018a/src/Checksum_Base_Command.php#L52-L73 | train |
wp-cli/checksum-command | src/Checksum_Plugin_Command.php | Checksum_Plugin_Command.add_error | private function add_error( $plugin_name, $file, $message ) {
$error['plugin_name'] = $plugin_name;
$error['file'] = $file;
$error['message'] = $message;
$this->errors[] = $error;
} | php | private function add_error( $plugin_name, $file, $message ) {
$error['plugin_name'] = $plugin_name;
$error['file'] = $file;
$error['message'] = $message;
$this->errors[] = $error;
} | [
"private",
"function",
"add_error",
"(",
"$",
"plugin_name",
",",
"$",
"file",
",",
"$",
"message",
")",
"{",
"$",
"error",
"[",
"'plugin_name'",
"]",
"=",
"$",
"plugin_name",
";",
"$",
"error",
"[",
"'file'",
"]",
"=",
"$",
"file",
";",
"$",
"error"... | Adds a new error to the array of detected errors.
@param string $plugin_name Name of the plugin that had the error.
@param string $file Relative path to the file that had the error.
@param string $message Message explaining the error. | [
"Adds",
"a",
"new",
"error",
"to",
"the",
"array",
"of",
"detected",
"errors",
"."
] | 7db66668ec116c5ccef7bc27b4354fa81b85018a | https://github.com/wp-cli/checksum-command/blob/7db66668ec116c5ccef7bc27b4354fa81b85018a/src/Checksum_Plugin_Command.php#L156-L161 | train |
wp-cli/checksum-command | src/Checksum_Plugin_Command.php | Checksum_Plugin_Command.get_plugin_version | private function get_plugin_version( $path ) {
if ( ! isset( $this->plugins_data ) ) {
$this->plugins_data = get_plugins();
}
if ( ! array_key_exists( $path, $this->plugins_data ) ) {
return false;
}
return $this->plugins_data[ $path ]['Version'];
} | php | private function get_plugin_version( $path ) {
if ( ! isset( $this->plugins_data ) ) {
$this->plugins_data = get_plugins();
}
if ( ! array_key_exists( $path, $this->plugins_data ) ) {
return false;
}
return $this->plugins_data[ $path ]['Version'];
} | [
"private",
"function",
"get_plugin_version",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"plugins_data",
")",
")",
"{",
"$",
"this",
"->",
"plugins_data",
"=",
"get_plugins",
"(",
")",
";",
"}",
"if",
"(",
"!",
"array... | Gets the currently installed version for a given plugin.
@param string $path Relative path to plugin file to get the version for.
@return string|false Installed version of the plugin, or false if not
found. | [
"Gets",
"the",
"currently",
"installed",
"version",
"for",
"a",
"given",
"plugin",
"."
] | 7db66668ec116c5ccef7bc27b4354fa81b85018a | https://github.com/wp-cli/checksum-command/blob/7db66668ec116c5ccef7bc27b4354fa81b85018a/src/Checksum_Plugin_Command.php#L171-L181 | train |
wp-cli/checksum-command | src/Checksum_Plugin_Command.php | Checksum_Plugin_Command.get_plugin_checksums | private function get_plugin_checksums( $plugin, $version ) {
$url = str_replace(
array(
'{slug}',
'{version}',
),
array(
$plugin,
$version,
),
$this->url_template
);
$options = array(
'timeout' => 30,
);
$headers = array(
'Accept' => 'application/json',
);
$response = Utils\http_request( 'GET', $url, null, $headers, $options );
if ( ! $response->success || 200 !== $response->status_code ) {
return false;
}
$body = trim( $response->body );
$body = json_decode( $body, true );
if ( ! is_array( $body ) || ! isset( $body['files'] ) || ! is_array( $body['files'] ) ) {
return false;
}
return $body['files'];
} | php | private function get_plugin_checksums( $plugin, $version ) {
$url = str_replace(
array(
'{slug}',
'{version}',
),
array(
$plugin,
$version,
),
$this->url_template
);
$options = array(
'timeout' => 30,
);
$headers = array(
'Accept' => 'application/json',
);
$response = Utils\http_request( 'GET', $url, null, $headers, $options );
if ( ! $response->success || 200 !== $response->status_code ) {
return false;
}
$body = trim( $response->body );
$body = json_decode( $body, true );
if ( ! is_array( $body ) || ! isset( $body['files'] ) || ! is_array( $body['files'] ) ) {
return false;
}
return $body['files'];
} | [
"private",
"function",
"get_plugin_checksums",
"(",
"$",
"plugin",
",",
"$",
"version",
")",
"{",
"$",
"url",
"=",
"str_replace",
"(",
"array",
"(",
"'{slug}'",
",",
"'{version}'",
",",
")",
",",
"array",
"(",
"$",
"plugin",
",",
"$",
"version",
",",
"... | Gets the checksums for the given version of plugin.
@param string $version Version string to query.
@param string $plugin plugin string to query.
@return bool|array False on failure. An array of checksums on success. | [
"Gets",
"the",
"checksums",
"for",
"the",
"given",
"version",
"of",
"plugin",
"."
] | 7db66668ec116c5ccef7bc27b4354fa81b85018a | https://github.com/wp-cli/checksum-command/blob/7db66668ec116c5ccef7bc27b4354fa81b85018a/src/Checksum_Plugin_Command.php#L191-L225 | train |
wp-cli/checksum-command | src/Checksum_Plugin_Command.php | Checksum_Plugin_Command.get_all_plugin_names | private function get_all_plugin_names() {
$names = array();
foreach ( get_plugins() as $file => $details ) {
$names[] = Utils\get_plugin_name( $file );
}
return $names;
} | php | private function get_all_plugin_names() {
$names = array();
foreach ( get_plugins() as $file => $details ) {
$names[] = Utils\get_plugin_name( $file );
}
return $names;
} | [
"private",
"function",
"get_all_plugin_names",
"(",
")",
"{",
"$",
"names",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"get_plugins",
"(",
")",
"as",
"$",
"file",
"=>",
"$",
"details",
")",
"{",
"$",
"names",
"[",
"]",
"=",
"Utils",
"\\",
"get_plug... | Gets the names of all installed plugins.
@return array<string> Names of all installed plugins. | [
"Gets",
"the",
"names",
"of",
"all",
"installed",
"plugins",
"."
] | 7db66668ec116c5ccef7bc27b4354fa81b85018a | https://github.com/wp-cli/checksum-command/blob/7db66668ec116c5ccef7bc27b4354fa81b85018a/src/Checksum_Plugin_Command.php#L232-L239 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.