Merge pull request #5247 from open-sausages/pulls/4.0/changesets

API Implement ChangeSets for batch publishing
This commit is contained in:
Hamish Friedlander 2016-04-04 18:59:25 +12:00
commit db7c3ab4d8
26 changed files with 1376 additions and 120 deletions

View File

@ -25,18 +25,22 @@ abstract class CMSBatchAction extends Object {
/**
* Run this action for the given set of pages.
* Return a set of status-updated JavaScript to return to the CMS.
*
* @param SS_List $objs
* @return string
*/
abstract public function run(SS_List $objs);
/**
* Helper method for responding to a back action request
* @param $successMessage string - The message to return as a notification.
* @param string $successMessage The message to return as a notification.
* Can have up to two %d's in it. The first will be replaced by the number of successful
* changes, the second by the number of failures
* @param $status array - A status array like batchactions builds. Should be
* @param array $status A status array like batchactions builds. Should be
* key => value pairs, the key can be any string: "error" indicates errors, anything
* else indicates a type of success. The value is an array. We don't care what's in it,
* we just use count($value) to find the number of items that succeeded or failed
* @return string
*/
public function response($successMessage, $status) {
$count = 0;
@ -69,10 +73,12 @@ abstract class CMSBatchAction extends Object {
* Helper method for processing batch actions.
* Returns a set of status-updating JavaScript to return to the CMS.
*
* @param $objs The SS_List of objects to perform this batch action
* @param SS_List $objs The SS_List of objects to perform this batch action
* on.
* @param $helperMethod The method to call on each of those objects.
* @return JSON encoded map in the following format:
* @param string $helperMethod The method to call on each of those objects.
* @param string $successMessage
* @param array $arguments
* @return string JSON encoded map in the following format:
* {
* 'modified': {
* 3: {'TreeTitle': 'Page3'},
@ -117,10 +123,11 @@ abstract class CMSBatchAction extends Object {
/**
* Helper method for applicablePages() methods. Acts as a skeleton implementation.
*
* @param $ids The IDs passed to applicablePages
* @param $methodName The canXXX() method to call on each page to check if the action is applicable
* @param $checkStagePages Set to true if you want to check stage pages
* @param $checkLivePages Set to true if you want to check live pages (e.g, for deleted-from-draft)
* @param array $ids The IDs passed to applicablePages
* @param string $methodName The canXXX() method to call on each page to check if the action is applicable
* @param bool $checkStagePages Set to true if you want to check stage pages
* @param bool $checkLivePages Set to true if you want to check live pages (e.g, for deleted-from-draft)
* @return array
*/
public function applicablePagesHelper($ids, $methodName, $checkStagePages = true, $checkLivePages = true) {
if(!is_array($ids)) user_error("Bad \$ids passed to applicablePagesHelper()", E_USER_WARNING);
@ -141,7 +148,7 @@ abstract class CMSBatchAction extends Object {
}
$onlyOnLive = array_keys($onlyOnLive);
if($checkLivePages && $onlyOnLive && $managedClass::has_extension('Versioned')) {
if($checkLivePages && $onlyOnLive && Object::has_extension($managedClass, 'Versioned')) {
// Get the pages that only exist on live (deleted from stage)
$livePages = Versioned::get_by_stage($managedClass, "Live")->byIDs($onlyOnLive);
foreach($livePages as $obj) {

View File

@ -670,29 +670,36 @@ class SapphireTest extends PHPUnit_Framework_TestCase {
* @param mixed $dataObjectSet The {@link SS_List} to test.
*/
public function assertDOSEquals($matches, $dataObjectSet) {
if(!$dataObjectSet) return;
// Extract dataobjects
$extracted = array();
foreach($dataObjectSet as $item) $extracted[] = $item->toMap();
foreach($matches as $match) {
$matched = false;
foreach($extracted as $i => $item) {
if($this->dataObjectArrayMatch($item, $match)) {
// Remove it from $extracted so that we don't get duplicate mapping.
unset($extracted[$i]);
$matched = true;
break;
}
if($dataObjectSet) {
foreach ($dataObjectSet as $item) {
/** @var DataObject $item */
$extracted[] = $item->toMap();
}
}
// We couldn't find a match - assertion failed
$this->assertTrue(
$matched,
"Failed asserting that the SS_List contains an item matching "
. var_export($match, true) . "\n\nIn the following SS_List:\n"
. $this->DOSSummaryForMatch($dataObjectSet, $match)
);
// Check all matches
if($matches) {
foreach ($matches as $match) {
$matched = false;
foreach ($extracted as $i => $item) {
if ($this->dataObjectArrayMatch($item, $match)) {
// Remove it from $extracted so that we don't get duplicate mapping.
unset($extracted[$i]);
$matched = true;
break;
}
}
// We couldn't find a match - assertion failed
$this->assertTrue(
$matched,
"Failed asserting that the SS_List contains an item matching "
. var_export($match, true) . "\n\nIn the following SS_List:\n"
. $this->DOSSummaryForMatch($dataObjectSet, $match)
);
}
}
// If we have leftovers than the DOS has extra data that shouldn't be there
@ -975,22 +982,41 @@ class SapphireTest extends PHPUnit_Framework_TestCase {
/**
* Create a member and group with the given permission code, and log in with it.
* Returns the member ID.
*
* @param string|array $permCode Either a permission, or list of permissions
* @return int Member ID
*/
public function logInWithPermission($permCode = "ADMIN") {
if(!isset($this->cache_generatedMembers[$permCode])) {
$group = Injector::inst()->create('Group');
if(is_array($permCode)) {
$permArray = $permCode;
$permCode = implode('.', $permCode);
} else {
$permArray = array($permCode);
}
// Check cached member
if(isset($this->cache_generatedMembers[$permCode])) {
$member = $this->cache_generatedMembers[$permCode];
} else {
// Generate group with these permissions
$group = Group::create();
$group->Title = "$permCode group";
$group->write();
$permission = Injector::inst()->create('Permission');
$permission->Code = $permCode;
$permission->write();
$group->Permissions()->add($permission);
// Create each individual permission
foreach($permArray as $permArrayItem) {
$permission = Permission::create();
$permission->Code = $permArrayItem;
$permission->write();
$group->Permissions()->add($permission);
}
$member = DataObject::get_one('Member', array(
'"Member"."Email"' => "$permCode@example.org"
));
if(!$member) $member = Injector::inst()->create('Member');
if (!$member) {
$member = Member::create();
}
$member->FirstName = $permCode;
$member->Surname = "User";
@ -1000,9 +1026,8 @@ class SapphireTest extends PHPUnit_Framework_TestCase {
$this->cache_generatedMembers[$permCode] = $member;
}
$this->cache_generatedMembers[$permCode]->logIn();
return $this->cache_generatedMembers[$permCode]->ID;
$member->logIn();
return $member->ID;
}
/**

View File

@ -117,8 +117,14 @@ The usual call to `DataObject->write()` will write to whatever stage is currentl
`<class>_versions` table. To avoid this, use [api:Versioned::writeWithoutVersion()] instead.
To move a saved version from one stage to another, call [writeToStage(<stage>)](api:Versioned->writeToStage()) on the
object. The process of moving a version to a different stage is also called "publishing", so we've created a shortcut
for this: `publish(<from-stage>, <to-stage>)`.
object. The process of moving a version to a different stage is also called "publishing". This can be
done via one of several ways:
* `copyVersionToStage` which will allow you to specify a source (which could be either a version
number, or a stage), as well as a destination stage.
* `publishSingle` Publishes this record to live from the draft.
* `publishRecursive` Publishes this record, and any dependant objects this record may refer to.
See "DataObject ownership" for reference on dependant objects.
:::php
$record = Versioned::get_by_stage('MyRecord', 'Stage')->byID(99);
@ -127,7 +133,7 @@ for this: `publish(<from-stage>, <to-stage>)`.
// and write a row to `MyRecord_versions`.
$record->write();
// will copy the saved record information to the `MyRecord_Live` table
$record->publish('Stage', 'Live');
$record->publishRecursive();
Similarly, an "unpublish" operation does the reverse, and removes a record from a specific stage.

View File

@ -112,7 +112,7 @@ end of each test.
for($i=0; $i<100; $i++) {
$page = new Page(array('Title' => "Page $i"));
$page->write();
$page->publish('Stage', 'Live');
$page->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
}
// set custom configuration for the test.

View File

@ -275,7 +275,7 @@ publish a page, which requires a method call.
$blueprint = Injector::inst()->create('FixtureBlueprint', 'Member');
$blueprint->addCallback('afterCreate', function($obj, $identifier, $data, $fixtures) {
$obj->publish('Stage', 'Live');
$obj->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
});
$page = $factory->define('Page', $blueprint);

View File

@ -40,6 +40,7 @@
* `CMSBatchAction_Delete` and `CMSMain::delete` are no longer deprecated.
* `CMSBatchAction_DeleteFromLive` is removed.
* `CMSMain.enabled_legacy_actions` config is removed.
* `DataObject::can` has new method signature with `$context` parameter.
## New API
@ -87,6 +88,7 @@
* `$versionableExtensions` is now `private static` instead of `protected static`
* `hasStages` is addded to check if an object has a given stage.
* `stageTable` is added to get the table for a given class and stage.
* `ChangeSet` and `ChangeSetItem` have been added for batch publishing of versioned dataobjects.
### Front-end build tooling for CMS interface
@ -702,6 +704,17 @@ For instance:
}
Additionally, the following api methods have been added:
* `Versioned::publishRecursive` Publishes this object, and all owned objects
* `Versioned::publishSingle` Publishes this object, but not owned objects
* `Versioned::copyVersionToStage` Replaces the old `publish` method.
These methods are deprecated:
* `Versioned::publish` Replaced by `Versioned::copyVersionToStage`
* `Versioned::doPublish` Replaced by `Versioned::publishRecursive`
### Implementation of ownership API
In order to support the recursive publishing of dataobjects, a new API has been developed to allow
@ -710,6 +723,14 @@ developers to declare dependencies between objects. See the
By default all versioned dataobjects will automatically publish objects that they own.
### ChangeSet batch publishing
ChangeSet objects have been added, which allow groups of objects to be published in
a single atomic transaction.
This API will utilise the ownership API to ensure that changes to any object include
all necessary changes to owners or owned entities within the same changeset.
### New `[image]` shortcode in `HTMLText` fields
The new Ownership API relies on relationships between objects.

View File

@ -757,7 +757,7 @@ class File extends DataObject implements ShortcodeHandler, AssetContainer {
// Relies on Parent() returning the stage record
$parent = $this->Parent();
if($parent && $parent->exists()) {
$parent->doPublish();
$parent->publishRecursive();
}
}

View File

@ -79,7 +79,7 @@ class FileMigrationHelper extends Object {
// Save and publish
$file->write();
$file->doPublish();
$file->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
return true;
}

View File

@ -260,7 +260,7 @@ class Folder extends File {
// No publishing UX for folders, so just cascade changes live
if(Versioned::get_stage() === Versioned::DRAFT) {
$this->publish(Versioned::DRAFT, Versioned::LIVE);
$this->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
}
// Update draft version of all child records

View File

@ -2796,10 +2796,11 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
* @param string $perm The permission to be checked, such as 'View'.
* @param Member $member The member whose permissions need checking. Defaults to the currently logged
* in user.
* @param array $context Additional $context to pass to extendedCan()
*
* @return boolean True if the the member is allowed to do the given action
*/
public function can($perm, $member = null) {
public function can($perm, $member = null, $context = array()) {
if(!isset($member)) {
$member = Member::currentUser();
}

View File

@ -272,4 +272,11 @@ class UnsavedRelationList extends ArrayList implements Relation {
public function dbObject($fieldName) {
return singleton($this->dataClass)->dbObject($fieldName);
}
protected function extractValue($item, $key) {
if(is_numeric($item)) {
$item = DataObject::get_by_id($this->dataClass, $item);
}
return parent::extractValue($item, $key);
}
}

View File

@ -0,0 +1,331 @@
<?php
// namespace SilverStripe\Framework\Model\Versioning
/**
* The ChangeSet model tracks several VersionedAndStaged objects for later publication as a single
* atomic action
*
* @method HasManyList Changes()
* @method Member Owner()
* @property string $Name
* @property string $State
*
* @package framework
* @subpackage model
*/
class ChangeSet extends DataObject {
private static $singular_name = 'Campaign';
private static $plural_name = 'Campaigns';
/** An active changeset */
const STATE_OPEN = 'open';
/** A changeset which is reverted and closed */
const STATE_REVERTED = 'reverted';
/** A changeset which is published and closed */
const STATE_PUBLISHED = 'published';
private static $db = array(
'Name' => 'Varchar',
'State' => "Enum('open,published,reverted')",
);
private static $has_many = array(
'Changes' => 'ChangeSetItem',
);
private static $defaults = array(
'State' => 'open'
);
private static $has_one = array(
'Owner' => 'Member',
);
/**
* Default permission to require for publishers.
* Publishers must either be able to use the campaign admin, or have all admin access.
*
* Also used as default permission for ChangeSetItem default permission.
*
* @config
* @var array
*/
private static $required_permission = array('CMS_ACCESS_CampaignAdmin', 'CMS_ACCESS_LeftAndMain');
/**
* Publish this changeset, then closes it.
*
* @throws Exception
*/
public function publish() {
// Logical checks prior to publish
if($this->State !== static::STATE_OPEN) {
throw new BadMethodCallException(
"ChangeSet can't be published if it has been already published or reverted."
);
}
if(!$this->isSynced()) {
throw new ValidationException(
"ChangeSet does not include all necessary changes and cannot be published."
);
}
if(!$this->canPublish()) {
throw new Exception("The current member does not have permission to publish this ChangeSet.");
}
DB::get_conn()->withTransaction(function(){
foreach($this->Changes() as $change) {
/** @var ChangeSetItem $change */
$change->publish();
}
$this->State = static::STATE_PUBLISHED;
$this->write();
});
}
/**
* Add a new change to this changeset. Will automatically include all owned
* changes as those are dependencies of this item.
*
* @param DataObject $object
*/
public function addObject(DataObject $object) {
if(!$this->isInDB()) {
throw new BadMethodCallException("ChangeSet must be saved before adding items");
}
$references = [
'ObjectID' => $object->ID,
'ObjectClass' => $object->ClassName
];
// Get existing item in case already added
$item = $this->Changes()->filter($references)->first();
if (!$item) {
$item = new ChangeSetItem($references);
$this->Changes()->add($item);
}
$item->ReferencedBy()->removeAll();
$item->Added = ChangeSetItem::EXPLICITLY;
$item->write();
$this->sync();
}
/**
* Remove an item from this changeset. Will automatically remove all changes
* which own (and thus depend on) the removed item.
*
* @param DataObject $object
*/
public function removeObject(DataObject $object) {
$item = ChangeSetItem::get()->filter([
'ObjectID' => $object->ID,
'ObjectClass' => $object->ClassName,
'ChangeSetID' => $this->ID
])->first();
if ($item) {
// TODO: Handle case of implicit added item being removed.
$item->delete();
}
$this->sync();
}
protected function implicitKey($item) {
if ($item instanceof ChangeSetItem) return $item->ObjectClass.'.'.$item->ObjectID;
return $item->ClassName.'.'.$item->ID;
}
protected function calculateImplicit() {
/** @var string[][] $explicit List of all items that have been explicitly added to this ChangeSet */
$explicit = array();
/** @var string[][] $referenced List of all items that are "referenced" by items in $explicit */
$referenced = array();
/** @var string[][] $references List of which explicit items reference each thing in referenced */
$references = array();
foreach ($this->Changes()->filter(['Added' => ChangeSetItem::EXPLICITLY]) as $item) {
$explicitKey = $this->implicitKey($item);
$explicit[$explicitKey] = true;
foreach ($item->findReferenced() as $referee) {
$key = $this->implicitKey($referee);
$referenced[$key] = [
'ObjectID' => $referee->ID,
'ObjectClass' => $referee->ClassName
];
$references[$key][] = $item->ID;
}
}
/** @var string[][] $explicit List of all items that are either in $explicit, $referenced or both */
$all = array_merge($referenced, $explicit);
/** @var string[][] $implicit Anything that is in $all, but not in $explicit, is an implicit inclusion */
$implicit = array_diff_key($all, $explicit);
foreach($implicit as $key => $object) {
$implicit[$key]['ReferencedBy'] = $references[$key];
}
return $implicit;
}
/**
* Add implicit changes that should be included in this changeset
*
* When an item is created or changed, all it's owned items which have
* changes are implicitly added
*
* When an item is deleted, it's owner (even if that owner does not have changes)
* is implicitly added
*/
public function sync() {
// Start a transaction (if we can)
DB::get_conn()->withTransaction(function() {
// Get the implicitly included items for this ChangeSet
$implicit = $this->calculateImplicit();
// Adjust the existing implicit ChangeSetItems for this ChangeSet
foreach ($this->Changes()->filter(['Added' => ChangeSetItem::IMPLICITLY]) as $item) {
$objectKey = $this->implicitKey($item);
// If a ChangeSetItem exists, but isn't in $implicit, it's no longer required, so delete it
if (!array_key_exists($objectKey, $implicit)) {
$item->delete();
}
// Otherwise it is required, so update ReferencedBy and remove from $implicit
else {
$item->ReferencedBy()->setByIDList($implicit[$objectKey]['ReferencedBy']);
unset($implicit[$objectKey]);
}
}
// Now $implicit is all those items that are implicitly included, but don't currently have a ChangeSetItem.
// So create new ChangeSetItems to match
foreach ($implicit as $key => $props) {
$item = new ChangeSetItem($props);
$item->Added = ChangeSetItem::IMPLICITLY;
$item->ChangeSetID = $this->ID;
$item->ReferencedBy()->setByIDList($props['ReferencedBy']);
$item->write();
}
});
}
/** Verify that any objects in this changeset include all owned changes */
public function isSynced() {
$implicit = $this->calculateImplicit();
// Check the existing implicit ChangeSetItems for this ChangeSet
foreach ($this->Changes()->filter(['Added' => ChangeSetItem::IMPLICITLY]) as $item) {
$objectKey = $this->implicitKey($item);
// If a ChangeSetItem exists, but isn't in $implicit -> validation failure
if (!array_key_exists($objectKey, $implicit)) return false;
// Exists, remove from $implicit
unset($implicit[$objectKey]);
}
// If there's anything left in $implicit -> validation failure
return empty($implicit);
}
public function canView($member = null) {
return $this->can(__FUNCTION__, $member);
}
public function canEdit($member = null) {
return $this->can(__FUNCTION__, $member);
}
public function canCreate($member = null, $context = array()) {
return $this->can(__FUNCTION__, $member, $context);
}
public function canDelete($member = null) {
return $this->can(__FUNCTION__, $member);
}
/**
* Check if this item is allowed to be published
*
* @param Member $member
* @return bool
*/
public function canPublish($member = null) {
// All changes must be publishable
foreach($this->Changes() as $change) {
/** @var ChangeSetItem $change */
if(!$change->canPublish($member)) {
return false;
}
}
// Default permission
return $this->can(__FUNCTION__, $member);
}
/**
* Check if this changeset (if published) can be reverted
*
* @param Member $member
* @return bool
*/
public function canRevert($member = null) {
// All changes must be publishable
foreach($this->Changes() as $change) {
/** @var ChangeSetItem $change */
if(!$change->canRevert($member)) {
return false;
}
}
// Default permission
return $this->can(__FUNCTION__, $member);
}
/**
* Default permissions for this changeset
*
* @param string $perm
* @param Member $member
* @param array $context
* @return bool
*/
public function can($perm, $member = null, $context = array()) {
if(!$member) {
$member = Member::currentUser();
}
// 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, $this->config()->required_permission);
}
}

View File

@ -0,0 +1,281 @@
<?php
// namespace SilverStripe\Framework\Model\Versioning
/**
* A single line in a changeset
*
* @property string $ReferencedBy
* @property string $Added
* @property string $ObjectClass
* @property int $ObjectID
* @method ManyManyList ReferencedBy() List of explicit items that require this change
* @method ManyManyList References() List of implicit items required by this change
* @method ChangeSet ChangeSet()
*/
class ChangeSetItem extends DataObject {
const EXPLICITLY = 'explicitly';
const IMPLICITLY = 'implicitly';
/** Represents an object deleted */
const CHANGE_DELETED = 'deleted';
/** Represents an object which was modified */
const CHANGE_MODIFIED = 'modified';
/** Represents an object added */
const CHANGE_CREATED = 'created';
/** Represents an object which hasn't been changed directly, but owns a modified many_many relationship. */
//const CHANGE_MANYMANY = 'manymany';
/**
* Represents that an object has not yet been changed, but
* should be included in this changeset as soon as any changes exist
*/
const CHANGE_NONE = 'none';
private static $db = array(
'VersionBefore' => 'Int',
'VersionAfter' => 'Int',
'Added' => "Enum('explicitly, implicitly', 'implicitly')"
);
private static $has_one = array(
'ChangeSet' => 'ChangeSet',
'Object' => 'DataObject',
);
private static $many_many = array(
'ReferencedBy' => 'ChangeSetItem'
);
private static $belongs_many_many = array(
'References' => 'ChangeSetItem.ReferencedBy'
);
private static $indexes = array(
'ObjectUniquePerChangeSet' => array(
'type' => 'unique',
'value' => '"ObjectID", "ObjectClass", "ChangeSetID"'
)
);
/**
* Get the type of change: none, created, deleted, modified, manymany
*
* @return string
*/
public function getChangeType() {
// Get change versions
if($this->VersionBefore || $this->VersionAfter) {
$draftVersion = $this->VersionAfter; // After publishing draft was written to stage
$liveVersion = $this->VersionBefore; // The live version before the publish
} else {
$draftVersion = Versioned::get_versionnumber_by_stage(
$this->ObjectClass, Versioned::DRAFT, $this->ObjectID, false
);
$liveVersion = Versioned::get_versionnumber_by_stage(
$this->ObjectClass, Versioned::LIVE, $this->ObjectID, false
);
}
// Version comparisons
if ($draftVersion == $liveVersion) {
return self::CHANGE_NONE;
} elseif (!$liveVersion) {
return self::CHANGE_CREATED;
} elseif (!$draftVersion) {
return self::CHANGE_DELETED;
} else {
return self::CHANGE_MODIFIED;
}
}
/**
* Find version of this object in the given stage
*
* @param string $stage
* @return Versioned|DataObject
*/
private function getObjectInStage($stage) {
return Versioned::get_by_stage($this->ObjectClass, $stage)->byID($this->ObjectID);
}
/**
* Get all implicit objects for this change
*
* @return SS_List
*/
public function findReferenced() {
if($this->getChangeType() === ChangeSetItem::CHANGE_DELETED) {
// If deleted from stage, need to look at live record
return $this->getObjectInStage(Versioned::LIVE)->findOwners(false);
} else {
// If changed on stage, look at owned objects there
return $this->getObjectInStage(Versioned::DRAFT)->findOwned()->filterByCallback(function ($owned) {
/** @var Versioned|DataObject $owned */
return $owned->stagesDiffer(Versioned::DRAFT, Versioned::LIVE);
});
}
}
/**
* Publish this item, then close it.
*
* Note: Unlike Versioned::doPublish() and Versioned::doUnpublish, this action is not recursive.
*/
public function publish() {
// Logical checks prior to publish
if(!$this->canPublish()) {
throw new Exception("The current member does not have permission to publish this ChangeSetItem.");
}
if($this->VersionBefore || $this->VersionAfter) {
throw new BadMethodCallException("This ChangeSetItem has already been published");
}
// 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
);
switch($this->getChangeType()) {
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();
break;
}
}
$this->write();
}
/** Reverts this item, then close it. **/
public function revert() {
user_error('Not implemented', E_USER_ERROR);
}
public function canView($member = null) {
return $this->can(__FUNCTION__, $member);
}
public function canEdit($member = null) {
return $this->can(__FUNCTION__, $member);
}
public function canCreate($member = null, $context = array()) {
return $this->can(__FUNCTION__, $member, $context);
}
public function canDelete($member = null) {
return $this->can(__FUNCTION__, $member);
}
/**
* Check if the BeforeVersion of this changeset can be restored to draft
*
* @param Member $member
* @return bool
*/
public function canRevert($member) {
// Just get the best version as this object may not even exist on either stage anymore.
/** @var Versioned|DataObject $object */
$object = Versioned::get_latest_version($this->ObjectClass, $this->ObjectID);
if(!$object) {
return false;
}
// Check change type
switch($this->getChangeType()) {
case static::CHANGE_CREATED: {
// Revert creation by deleting from stage
if(!$object->canDelete($member)) {
return false;
}
break;
}
default: {
// All other actions are typically editing draft stage
if(!$object->canEdit($member)) {
return false;
}
break;
}
}
// If object can be published/unpublished let extensions deny
return $this->can(__FUNCTION__, $member);
}
/**
* Check if this ChangeSetItem can be published
*
* @param Member $member
* @return bool
*/
public function canPublish($member = null) {
// 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 || !$object->canUnpublish($member)) {
return false;
}
break;
}
default: {
/** @var Versioned|DataObject $object */
$object = Versioned::get_by_stage($this->ObjectClass, Versioned::DRAFT)->byID($this->ObjectID);
if(!$object || !$object->canPublish($member)) {
return false;
}
break;
}
}
// If object can be published/unpublished let extensions deny
return $this->can(__FUNCTION__, $member);
}
/**
* Default permissions for this ChangeSetItem
*
* @param string $perm
* @param Member $member
* @param array $context
* @return bool
*/
public function can($perm, $member = null, $context = array()) {
if(!$member) {
$member = Member::currentUser();
}
// 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()->required_permission);
}
}

View File

@ -1444,11 +1444,43 @@ class Versioned extends DataExtension implements TemplateGlobalProvider {
}
/**
* Provides a simple doPublish action for Versioned dataobjects
* @deprecated 4.0..5.0
*/
public function doPublish() {
Deprecation::notice('5.0', 'Use publishRecursive instead');
return $this->owner->publishRecursive();
}
/**
* Publish this object and all owned objects to Live
*
* @return bool
*/
public function publishRecursive() {
$owner = $this->owner;
if(!$owner->publishSingle()) {
return false;
}
// Publish owned objects
foreach ($owner->findOwned(false) as $object) {
/** @var Versioned|DataObject $object */
$object->publishRecursive();
}
// Unlink any objects disowned as a result of this action
// I.e. objects which aren't owned anymore by this record, but are by the old live record
$owner->unlinkDisownedObjects(Versioned::DRAFT, Versioned::LIVE);
return true;
}
/**
* Publishes this object to Live, but doesn't publish owned objects.
*
* @return bool True if publish was successful
*/
public function doPublish() {
public function publishSingle() {
$owner = $this->owner;
if(!$owner->canPublish()) {
return false;
@ -1456,28 +1488,11 @@ class Versioned extends DataExtension implements TemplateGlobalProvider {
$owner->invokeWithExtensions('onBeforePublish');
$owner->write();
$owner->publish(static::DRAFT, static::LIVE);
$owner->copyVersionToStage(static::DRAFT, static::LIVE);
$owner->invokeWithExtensions('onAfterPublish');
return true;
}
/**
* Trigger publishing of owned objects
*/
public function onAfterPublish() {
$owner = $this->owner;
// Publish owned objects
foreach ($owner->findOwned(false) as $object) {
/** @var Versioned|DataObject $object */
$object->doPublish();
}
// Unlink any objects disowned as a result of this action
// I.e. objects which aren't owned anymore by this record, but are by the old live record
$owner->unlinkDisownedObjects(Versioned::DRAFT, Versioned::LIVE);
}
/**
* Set foreign keys of has_many objects to 0 where those objects were
* disowned as a result of a partial publish / unpublish.
@ -1628,7 +1643,7 @@ class Versioned extends DataExtension implements TemplateGlobalProvider {
}
$owner->invokeWithExtensions('onBeforeRevertToLive');
$owner->publish("Live", "Stage", false);
$owner->copyVersionToStage(static::LIVE, static::DRAFT, false);
$owner->invokeWithExtensions('onAfterRevertToLive');
return true;
}
@ -1653,6 +1668,14 @@ class Versioned extends DataExtension implements TemplateGlobalProvider {
$owner->unlinkDisownedObjects(Versioned::LIVE, Versioned::DRAFT);
}
/**
* @deprecated 4.0..5.0
*/
public function publish($fromStage, $toStage, $createNewVersion = false) {
Deprecation::notice('5.0', 'Use copyVersionToStage instead');
$this->owner->copyVersionToStage($fromStage, $toStage, $createNewVersion);
}
/**
* Move a database record from one stage to the other.
*
@ -1661,7 +1684,7 @@ class Versioned extends DataExtension implements TemplateGlobalProvider {
* @param bool $createNewVersion Set this to true to create a new version number.
* By default, the existing version number will be copied over.
*/
public function publish($fromStage, $toStage, $createNewVersion = false) {
public function copyVersionToStage($fromStage, $toStage, $createNewVersion = false) {
$owner = $this->owner;
$owner->invokeWithExtensions('onBeforeVersionedPublish', $fromStage, $toStage, $createNewVersion);
@ -1787,7 +1810,7 @@ class Versioned extends DataExtension implements TemplateGlobalProvider {
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('Stage');
static::set_stage(static::DRAFT);
$owner = $this->owner;
$list = DataObject::get(get_class($owner), $filter, $sort, $join, $limit);
@ -2047,7 +2070,7 @@ class Versioned extends DataExtension implements TemplateGlobalProvider {
*/
public static function get_versionnumber_by_stage($class, $stage, $id, $cache = true) {
$baseClass = ClassInfo::baseDataClass($class);
$stageTable = ($stage == 'Stage') ? $baseClass : "{$baseClass}_{$stage}";
$stageTable = ($stage == static::DRAFT) ? $baseClass : "{$baseClass}_{$stage}";
// cached call
if($cache && isset(self::$cache_versionnumber[$baseClass][$stage][$id])) {
@ -2104,7 +2127,7 @@ class Versioned extends DataExtension implements TemplateGlobalProvider {
}
$baseClass = ClassInfo::baseDataClass($class);
$stageTable = ($stage == 'Stage') ? $baseClass : "{$baseClass}_{$stage}";
$stageTable = ($stage == static::DRAFT) ? $baseClass : "{$baseClass}_{$stage}";
$versions = DB::prepared_query("SELECT \"ID\", \"Version\" FROM \"$stageTable\" $filter", $parameters)->map();
@ -2184,7 +2207,7 @@ class Versioned extends DataExtension implements TemplateGlobalProvider {
public function doRollbackTo($version) {
$owner = $this->owner;
$owner->extend('onBeforeRollback', $version);
$owner->publish($version, "Stage", true);
$owner->copyVersionToStage($version, static::DRAFT, true);
$owner->writeWithoutVersion();
$owner->extend('onAfterRollback', $version);
}

View File

@ -114,7 +114,8 @@ class VersionedGridFieldItemRequest extends GridFieldDetailForm_ItemRequest {
* @return SS_HTTPResponse
*/
public function doPublish($data, $form) {
$record = $this->getRecord();
/** @var Versioned|DataObject $record */
$record = $this->getRecord();
$isNewRecord = $record->ID == 0;
// Check permission
@ -126,7 +127,7 @@ class VersionedGridFieldItemRequest extends GridFieldDetailForm_ItemRequest {
try {
// Initial save and reload
$record = $this->saveFormIntoRecord($data, $form);
$record->doPublish();
$record->publishRecursive();
} catch(ValidationException $e) {
return $this->generateValidationResponse($form, $e);

View File

@ -26,7 +26,7 @@ class AssetControlExtensionTest extends SapphireTest {
$object1->Header->setFromLocalFile($fish1, 'Header/MyObjectHeader.jpg');
$object1->Download->setFromString('file content', 'Documents/File.txt');
$object1->write();
$object1->doPublish();
$object1->publishSingle();
$object2 = new AssetControlExtensionTest_Object();
$object2->Title = 'Unversioned';
@ -37,7 +37,7 @@ class AssetControlExtensionTest extends SapphireTest {
$object3->Title = 'Archived';
$object3->Header->setFromLocalFile($fish1, 'Archived/MyObjectHeader.jpg');
$object3->write();
$object3->doPublish();
$object3->publishSingle();
}
public function tearDown() {
@ -170,8 +170,8 @@ class AssetControlExtensionTest extends SapphireTest {
$this->assertEquals(AssetStore::VISIBILITY_PROTECTED, $object3->Header->getVisibility());
// Publish changes to versioned records
$object1->doPublish();
$object3->doPublish();
$object1->publishSingle();
$object3->publishSingle();
// After publishing, old object1 is deleted, but since object3 has archiving enabled,
// the orphaned file is intentionally left in the protected store

View File

@ -50,7 +50,7 @@ class FileTest extends SapphireTest {
'ErrorCode' => 404
));
$page->write();
$page->publish('Stage', 'Live');
$page->copyVersionToStage('Stage', 'Live');
}
}
@ -234,9 +234,10 @@ class FileTest extends SapphireTest {
}
public function testSetNameChangesFilesystemOnWrite() {
/** @var File $file */
$file = $this->objFromFixture('File', 'asdf');
$this->logInWithPermission('ADMIN');
$file->doPublish();
$file->publishRecursive();
$oldTuple = $file->File->getValue();
// Rename
@ -266,7 +267,7 @@ class FileTest extends SapphireTest {
);
// After publish
$file->doPublish();
$file->publishRecursive();
$this->assertFalse(
$this->getAssetStore()->exists($oldTuple['Filename'], $oldTuple['Hash']),
'Old file is finally removed after publishing new file'
@ -280,7 +281,7 @@ class FileTest extends SapphireTest {
public function testSetParentIDChangesFilesystemOnWrite() {
$file = $this->objFromFixture('File', 'asdf');
$this->logInWithPermission('ADMIN');
$file->doPublish();
$file->publishRecursive();
$subfolder = $this->objFromFixture('Folder', 'subfolder');
$oldTuple = $file->File->getValue();
@ -312,7 +313,7 @@ class FileTest extends SapphireTest {
);
// After publish
$file->doPublish();
$file->publishSingle();
$this->assertFalse(
$this->getAssetStore()->exists($oldTuple['Filename'], $oldTuple['Hash']),
'Old file is finally removed after publishing new file'
@ -408,9 +409,10 @@ class FileTest extends SapphireTest {
}
public function testDeleteFile() {
/** @var File $file */
$file = $this->objFromFixture('File', 'asdf');
$this->logInWithPermission('ADMIN');
$file->doPublish();
$file->publishSingle();
$tuple = $file->File->getValue();
// Before delete

View File

@ -111,14 +111,16 @@ class FolderTest extends SapphireTest {
$folder2 = $this->objFromFixture('Folder', 'folder2');
// Publish file1
/** @var File $file1 */
$file1 = DataObject::get_by_id('File', $this->idFromFixture('File', 'file1-folder1'), false);
$file1->doPublish();
$file1->publishRecursive();
// set ParentID. This should cause updateFilesystem to be called on all children
$folder1->ParentID = $folder2->ID;
$folder1->write();
// Check if the file in the folder moved along
/** @var File $file1Draft */
$file1Draft = Versioned::get_by_stage('File', Versioned::DRAFT)->byID($file1->ID);
$this->assertFileExists(AssetStoreTest_SpyStore::getLocalPath($file1Draft));
@ -135,6 +137,7 @@ class FolderTest extends SapphireTest {
);
// Published (live) version remains in the old location
/** @var File $file1Live */
$file1Live = Versioned::get_by_stage('File', Versioned::LIVE)->byID($file1->ID);
$this->assertEquals(
ASSETS_PATH . '/FolderTest/FileTest-folder1/55b443b601/File1.txt',
@ -142,7 +145,7 @@ class FolderTest extends SapphireTest {
);
// Publishing the draft to live should move the new file to the public store
$file1Draft->doPublish();
$file1Draft->publishRecursive();
$this->assertEquals(
ASSETS_PATH . '/FolderTest/FileTest-folder2/FileTest-folder1/55b443b601/File1.txt',
AssetStoreTest_SpyStore::getLocalPath($file1Draft)

View File

@ -0,0 +1,76 @@
<?php
class ChangeSetItemTest_Versioned extends DataObject {
private static $db = [
'Foo' => 'Int'
];
private static $extensions = [
"Versioned"
];
function canEdit($member = null) { return true; }
}
/**
* @package framework
* @subpackage tests
*/
class ChangeSetItemTest extends SapphireTest {
protected $extraDataObjects = [
'ChangeSetItemTest_Versioned'
];
function testChangeType() {
$object = new ChangeSetItemTest_Versioned(['Foo' => 1]);
$object->write();
$item = new ChangeSetItem([
'ObjectID' => $object->ID,
'ObjectClass' => $object->ClassName
]);
$this->assertEquals(
ChangeSetItem::CHANGE_CREATED, $item->ChangeType,
'New objects that aren\'t yet published should return created'
);
$object->publishRecursive();
$this->assertEquals(
ChangeSetItem::CHANGE_NONE, $item->ChangeType,
'Objects that have just been published should return no change'
);
$object->Foo += 1;
$object->write();
$this->assertEquals(
ChangeSetItem::CHANGE_MODIFIED, $item->ChangeType,
'Object that have unpublished changes written to draft should show as modified'
);
$object->publishRecursive();
$this->assertEquals(
ChangeSetItem::CHANGE_NONE, $item->ChangeType,
'Objects that have just been published should return no change'
);
// We need to use a copy, because ID is set to 0 by delete, causing the following unpublish to fail
$objectCopy = clone $object; $objectCopy->delete();
$this->assertEquals(
ChangeSetItem::CHANGE_DELETED, $item->ChangeType,
'Objects that have been deleted from draft (but not yet unpublished) should show as deleted'
);
$object->doUnpublish();
$this->assertEquals(
ChangeSetItem::CHANGE_NONE, $item->ChangeType,
'Objects that have been deleted and then unpublished should return no change'
);
}
}

View File

@ -0,0 +1,441 @@
<?php
/**
* Provides a set of targettable permissions for tested models
*
* @mixin Versioned
* @mixin DataObject
*/
trait ChangeSetTest_Permissions {
public function canEdit($member = null) {
return $this->can(__FUNCTION__, $member);
}
public function canDelete($member = null) {
return $this->can(__FUNCTION__, $member);
}
public function canCreate($member = null, $context = array()) {
return $this->can(__FUNCTION__, $member, $context);
}
public function canPublish($member = null, $context = array()) {
return $this->can(__FUNCTION__, $member, $context);
}
public function canUnpublish($member = null, $context = array()) {
return $this->can(__FUNCTION__, $member, $context);
}
public function can($perm, $member = null, $context = array()) {
$perms = [
"PERM_{$perm}",
'CAN_ALL',
];
return Permission::checkMember($member, $perms);
}
}
/**
* @mixin Versioned
*/
class ChangeSetTest_Base extends DataObject implements TestOnly {
use ChangeSetTest_Permissions;
private static $db = [
'Foo' => 'Int',
];
private static $has_many = [
'Mids' => 'ChangeSetTest_Mid',
];
private static $owns = [
'Mids',
];
private static $extensions = [
"Versioned",
];
}
/**
* @mixin Versioned
*/
class ChangeSetTest_Mid extends DataObject implements TestOnly {
use ChangeSetTest_Permissions;
private static $db = [
'Bar' => 'Int',
];
private static $has_one = [
'Base' => 'ChangeSetTest_Base',
'End' => 'ChangeSetTest_End',
];
private static $owns = [
'End',
];
private static $extensions = [
"Versioned",
];
}
/**
* @mixin Versioned
*/
class ChangeSetTest_End extends DataObject implements TestOnly {
use ChangeSetTest_Permissions;
private static $db = [
'Baz' => 'Int',
];
private static $extensions = [
"Versioned",
];
}
/**
* Test {@see ChangeSet} and {@see ChangeSetItem} models
*/
class ChangeSetTest extends SapphireTest {
protected static $fixture_file = 'ChangeSetTest.yml';
protected $extraDataObjects = [
'ChangeSetTest_Base',
'ChangeSetTest_Mid',
'ChangeSetTest_End',
];
/**
* Automatically publish all objects
*/
protected function publishAllFixtures() {
$this->logInWithPermission('ADMIN');
foreach($this->fixtureFactory->getFixtures() as $class => $fixtures) {
foreach ($fixtures as $handle => $id) {
/** @var Versioned|DataObject $object */
$object = $this->objFromFixture($class, $handle);
$object->publishSingle();
}
}
}
/**
* Check that the changeset includes the given items
*
* @param ChangeSet $cs
* @param array $match Array of object fixture keys with change type values
*/
protected function assertChangeSetLooksLike($cs, $match) {
$items = $cs->Changes()->toArray();
foreach($match as $key => $mode) {
list($class, $identifier) = explode('.', $key);
$object = $this->objFromFixture($class, $identifier);
foreach($items as $i => $item) {
if ($item->ObjectClass == $object->ClassName && $item->ObjectID == $object->ID && $item->Added == $mode) {
unset($items[$i]);
continue 2;
}
}
throw new PHPUnit_Framework_ExpectationFailedException(
'Change set didn\'t include expected item',
new \SebastianBergmann\Comparator\ComparisonFailure(array('Class' => $class, 'ID' => $object->ID, 'Added' => $mode), null, "$key => $mode", '')
);
}
if (count($items)) {
$extra = [];
foreach ($items as $item) $extra[] = ['Class' => $item->ObjectClass, 'ID' => $item->ObjectID, 'Added' => $item->Added, 'ChangeType' => $item->getChangeType()];
throw new PHPUnit_Framework_ExpectationFailedException(
'Change set included items that weren\'t expected',
new \SebastianBergmann\Comparator\ComparisonFailure(array(), $extra, '', print_r($extra, true))
);
}
}
public function testRepeatedSyncIsNOP() {
$this->publishAllFixtures();
$cs = new ChangeSet();
$cs->write();
$base = $this->objFromFixture('ChangeSetTest_Base', 'base');
$cs->addObject($base);
$cs->sync();
$this->assertChangeSetLooksLike($cs, [
'ChangeSetTest_Base.base' => ChangeSetItem::EXPLICITLY
]);
$cs->sync();
$this->assertChangeSetLooksLike($cs, [
'ChangeSetTest_Base.base' => ChangeSetItem::EXPLICITLY
]);
}
public function testSync() {
$this->publishAllFixtures();
$cs = new ChangeSet();
$cs->write();
$base = $this->objFromFixture('ChangeSetTest_Base', 'base');
$cs->addObject($base);
$cs->sync();
$this->assertChangeSetLooksLike($cs, [
'ChangeSetTest_Base.base' => ChangeSetItem::EXPLICITLY
]);
$end = $this->objFromFixture('ChangeSetTest_End', 'end1');
$end->Baz = 3;
$end->write();
$cs->sync();
$this->assertChangeSetLooksLike($cs, [
'ChangeSetTest_Base.base' => ChangeSetItem::EXPLICITLY,
'ChangeSetTest_End.end1' => ChangeSetItem::IMPLICITLY
]);
$endItem = $cs->Changes()->filter('ObjectClass', 'ChangeSetTest_End')->first();
$this->assertEquals(
[$base->ID],
$endItem->ReferencedBy()->column("ID")
);
$this->assertDOSEquals([
[
'Added' => ChangeSetItem::EXPLICITLY,
'ObjectClass' => 'ChangeSetTest_Base',
'ObjectID' => $base->ID,
'ChangeSetID' => $cs->ID
]
], $endItem->ReferencedBy());
}
/**
* Test that sync includes implicit items
*/
public function testIsSynced() {
$this->publishAllFixtures();
$cs = new ChangeSet();
$cs->write();
$base = $this->objFromFixture('ChangeSetTest_Base', 'base');
$cs->addObject($base);
$cs->sync();
$this->assertChangeSetLooksLike($cs, [
'ChangeSetTest_Base.base' => ChangeSetItem::EXPLICITLY
]);
$this->assertTrue($cs->isSynced());
$end = $this->objFromFixture('ChangeSetTest_End', 'end1');
$end->Baz = 3;
$end->write();
$this->assertFalse($cs->isSynced());
$cs->sync();
$this->assertChangeSetLooksLike($cs, [
'ChangeSetTest_Base.base' => ChangeSetItem::EXPLICITLY,
'ChangeSetTest_End.end1' => ChangeSetItem::IMPLICITLY
]);
$this->assertTrue($cs->isSynced());
}
public function testCanPublish() {
// Create changeset containing all items (unpublished)
$this->logInWithPermission('ADMIN');
$changeSet = new ChangeSet();
$changeSet->write();
$base = $this->objFromFixture('ChangeSetTest_Base', 'base');
$changeSet->addObject($base);
$changeSet->sync();
$this->assertEquals(5, $changeSet->Changes()->count());
// Test un-authenticated user cannot publish
Session::clear("loggedInAs");
$this->assertFalse($changeSet->canPublish());
// User with only one of the necessary permissions cannot publish
$this->logInWithPermission('CMS_ACCESS_CampaignAdmin');
$this->assertFalse($changeSet->canPublish());
$this->logInWithPermission('PERM_canPublish');
$this->assertFalse($changeSet->canPublish());
// Test user with the necessary minimum permissions can login
$this->logInWithPermission([
'CMS_ACCESS_CampaignAdmin',
'PERM_canPublish'
]);
$this->assertTrue($changeSet->canPublish());
}
public function testCanRevert() {
$this->markTestSkipped("Requires ChangeSet::revert to be implemented first");
}
public function testCanEdit() {
// Create changeset containing all items (unpublished)
$this->logInWithPermission('ADMIN');
$changeSet = new ChangeSet();
$changeSet->write();
$base = $this->objFromFixture('ChangeSetTest_Base', 'base');
$changeSet->addObject($base);
$changeSet->sync();
$this->assertEquals(5, $changeSet->Changes()->count());
// Check canEdit
Session::clear("loggedInAs");
$this->assertFalse($changeSet->canEdit());
$this->logInWithPermission('SomeWrongPermission');
$this->assertFalse($changeSet->canEdit());
$this->logInWithPermission('CMS_ACCESS_CampaignAdmin');
$this->assertTrue($changeSet->canEdit());
}
public function testCanCreate() {
// Check canCreate
Session::clear("loggedInAs");
$this->assertFalse(ChangeSet::singleton()->canCreate());
$this->logInWithPermission('SomeWrongPermission');
$this->assertFalse(ChangeSet::singleton()->canCreate());
$this->logInWithPermission('CMS_ACCESS_CampaignAdmin');
$this->assertTrue(ChangeSet::singleton()->canCreate());
}
public function testCanDelete() {
// Create changeset containing all items (unpublished)
$this->logInWithPermission('ADMIN');
$changeSet = new ChangeSet();
$changeSet->write();
$base = $this->objFromFixture('ChangeSetTest_Base', 'base');
$changeSet->addObject($base);
$changeSet->sync();
$this->assertEquals(5, $changeSet->Changes()->count());
// Check canDelete
Session::clear("loggedInAs");
$this->assertFalse($changeSet->canDelete());
$this->logInWithPermission('SomeWrongPermission');
$this->assertFalse($changeSet->canDelete());
$this->logInWithPermission('CMS_ACCESS_CampaignAdmin');
$this->assertTrue($changeSet->canDelete());
}
public function testCanView() {
// Create changeset containing all items (unpublished)
$this->logInWithPermission('ADMIN');
$changeSet = new ChangeSet();
$changeSet->write();
$base = $this->objFromFixture('ChangeSetTest_Base', 'base');
$changeSet->addObject($base);
$changeSet->sync();
$this->assertEquals(5, $changeSet->Changes()->count());
// Check canView
Session::clear("loggedInAs");
$this->assertFalse($changeSet->canView());
$this->logInWithPermission('SomeWrongPermission');
$this->assertFalse($changeSet->canView());
$this->logInWithPermission('CMS_ACCESS_CampaignAdmin');
$this->assertTrue($changeSet->canView());
}
public function testPublish() {
$this->publishAllFixtures();
$base = $this->objFromFixture('ChangeSetTest_Base', 'base');
$baseID = $base->ID;
$baseBefore = $base->Version;
$end1 = $this->objFromFixture('ChangeSetTest_End', 'end1');
$end1ID = $end1->ID;
$end1Before = $end1->Version;
// Create a new changest
$changeset = new ChangeSet();
$changeset->write();
$changeset->addObject($base);
$changeset->addObject($end1);
// Make a lot of changes
// - ChangeSetTest_Base.base modified
// - ChangeSetTest_End.end1 deleted
// - new ChangeSetTest_Mid added
$base->Foo = 343;
$base->write();
$baseAfter = $base->Version;
$midNew = new ChangeSetTest_Mid();
$midNew->Bar = 39;
$midNew->write();
$midNewID = $midNew->ID;
$midNewAfter = $midNew->Version;
$end1->delete();
$changeset->addObject($midNew);
// Publish
$this->logInWithPermission('ADMIN');
$this->assertTrue($changeset->canPublish());
$this->assertTrue($changeset->isSynced());
$changeset->publish();
$this->assertEquals(ChangeSet::STATE_PUBLISHED, $changeset->State);
// Check each item has the correct before/after version applied
$baseChange = $changeset->Changes()->filter([
'ObjectClass' => 'ChangeSetTest_Base',
'ObjectID' => $baseID,
])->first();
$this->assertEquals((int)$baseBefore, (int)$baseChange->VersionBefore);
$this->assertEquals((int)$baseAfter, (int)$baseChange->VersionAfter);
$this->assertEquals((int)$baseChange->VersionBefore + 1, (int)$baseChange->VersionAfter);
$this->assertEquals(
(int)$baseChange->VersionAfter,
(int)Versioned::get_versionnumber_by_stage('ChangeSetTest_Base', Versioned::LIVE, $baseID)
);
$end1Change = $changeset->Changes()->filter([
'ObjectClass' => 'ChangeSetTest_End',
'ObjectID' => $end1ID,
])->first();
$this->assertEquals((int)$end1Before, (int)$end1Change->VersionBefore);
$this->assertEquals(0, (int)$end1Change->VersionAfter);
$this->assertEquals(
0,
(int)Versioned::get_versionnumber_by_stage('ChangeSetTest_End', Versioned::LIVE, $end1ID)
);
$midNewChange = $changeset->Changes()->filter([
'ObjectClass' => 'ChangeSetTest_Mid',
'ObjectID' => $midNewID,
])->first();
$this->assertEquals(0, (int)$midNewChange->VersionBefore);
$this->assertEquals((int)$midNewAfter, (int)$midNewChange->VersionAfter);
$this->assertEquals(
(int)$midNewAfter,
(int)Versioned::get_versionnumber_by_stage('ChangeSetTest_Mid', Versioned::LIVE, $midNewID)
);
// Test trying to re-publish is blocked
$this->setExpectedException(
'BadMethodCallException',
"ChangeSet can't be published if it has been already published or reverted."
);
$changeset->publish();
}
}

View File

@ -0,0 +1,17 @@
ChangeSetTest_Base:
base:
Foo: 1
ChangeSetTest_End:
end1:
Baz: 1
end2:
Baz: 2
ChangeSetTest_Mid:
mid1:
Bar: 1
Base: =>ChangeSetTest_Base.base
End: =>ChangeSetTest_End.end1
mid2:
Bar: 2
Base: =>ChangeSetTest_Base.base
End: =>ChangeSetTest_End.end2

View File

@ -93,7 +93,9 @@ class DataDifferencerTest extends SapphireTest {
*/
class DataDifferencerTest_Object extends DataObject implements TestOnly {
private static $extensions = array('Versioned("Stage", "Live")');
private static $extensions = array(
'Versioned'
);
private static $db = array(
'Choices' => "Varchar",

View File

@ -337,7 +337,7 @@ class DataObjectLazyLoadingTest extends SapphireTest {
$obj1->PageName = "old-value";
$obj1->ExtraField = "old-value";
$obj1ID = $obj1->write();
$obj1->publish('Stage', 'Live');
$obj1->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$obj1 = VersionedLazySub_DataObject::get()->byID($obj1ID);
$this->assertEquals(

View File

@ -149,10 +149,10 @@ class HierarchyTest extends SapphireTest {
$obj2b = $this->objFromFixture('HierarchyTest_Object', 'obj2b');
// Get a published set of objects for our fixture
$obj1->publish("Stage", "Live");
$obj2->publish("Stage", "Live");
$obj2a->publish("Stage", "Live");
$obj2b->publish("Stage", "Live");
$obj1->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$obj2->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$obj2a->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$obj2b->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
// Then delete 2a from stage and move 2b to a sub-node of 1.
$obj2a->delete();
@ -536,7 +536,7 @@ class HierarchyTest_Object extends DataObject implements TestOnly {
private static $extensions = array(
'Hierarchy',
"Versioned('Stage', 'Live')",
'Versioned',
);
public function cmstreeclasses() {

View File

@ -30,7 +30,7 @@ class VersionedOwnershipTest extends SapphireTest {
if(stripos($name, '_published') !== false) {
/** @var Versioned|DataObject $object */
$object = DataObject::get($class)->byID($id);
$object->publish(Versioned::DRAFT, Versioned::LIVE);
$object->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
}
}
}
@ -277,7 +277,7 @@ class VersionedOwnershipTest extends SapphireTest {
$this->assertDOSEquals($oldLiveBanners, $parentLive->Banners());
// On publishing of owner, all children should now be updated
$parent->doPublish();
$parent->publishRecursive();
// Now check each object has the correct state
$parentDraft = Versioned::get_by_stage('VersionedOwnershipTest_Subclass', Versioned::DRAFT)
@ -325,7 +325,7 @@ class VersionedOwnershipTest extends SapphireTest {
// Second test: multi-level unpublish should recursively cascade down all owning objects
// Publish related2 again
$subclass2->doPublish();
$subclass2->publishRecursive();
$this->assertTrue($subclass2->isPublished());
$this->assertTrue($related2->isPublished());
$this->assertTrue($attachment3->isPublished());

View File

@ -65,11 +65,11 @@ class VersionedTest extends SapphireTest {
$obj = new VersionedTest_Subclass();
$obj->ExtraField = 'Foo'; // ensure that child version table gets written
$obj->write();
$obj->publish('Stage', 'Live');
$obj->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$obj->ExtraField = 'Bar'; // ensure that child version table gets written
$obj->write();
$obj->publish('Stage', 'Live');
$obj->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$versions = DB::query("SELECT COUNT(*) FROM \"VersionedTest_Subclass_versions\""
. " WHERE \"RecordID\" = '$obj->ID'")->value();
@ -92,7 +92,7 @@ class VersionedTest extends SapphireTest {
// test that it doesn't delete records that we need
$obj->write();
$obj->publish('Stage', 'Live');
$obj->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$count = DB::query("SELECT COUNT(*) FROM \"VersionedTest_Subclass_versions\""
. " WHERE \"RecordID\" = '$obj->ID'")->value();
@ -117,14 +117,14 @@ class VersionedTest extends SapphireTest {
);
// Fail publishing from live to stage
$obj->publish('Live', 'Stage');
$obj->copyVersionToStage(Versioned::LIVE, Versioned::DRAFT);
}
public function testDuplicate() {
$obj1 = new VersionedTest_Subclass();
$obj1->ExtraField = 'Foo';
$obj1->write(); // version 1
$obj1->publish('Stage', 'Live');
$obj1->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$obj1->ExtraField = 'Foo2';
$obj1->write(); // version 2
@ -217,7 +217,7 @@ class VersionedTest extends SapphireTest {
$page1->Content = 'orig';
$page1->write();
$firstVersion = $page1->Version;
$page1->publish('Stage', 'Live', false);
$page1->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE, false);
$this->assertEquals(
$firstVersion,
$page1->Version,
@ -229,7 +229,7 @@ class VersionedTest extends SapphireTest {
$secondVersion = $page1->Version;
$this->assertTrue($firstVersion < $secondVersion, 'write creates new version');
$page1->publish('Stage', 'Live', true);
$page1->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE, true);
$thirdVersion = Versioned::get_latest_version('VersionedTest_DataObject', $page1->ID)->Version;
$liveVersion = Versioned::get_versionnumber_by_stage('VersionedTest_DataObject', 'Live', $page1->ID);
$stageVersion = Versioned::get_versionnumber_by_stage('VersionedTest_DataObject', 'Stage', $page1->ID);
@ -253,12 +253,12 @@ class VersionedTest extends SapphireTest {
$page1 = $this->objFromFixture('VersionedTest_AnotherSubclass', 'subclass1');
$page1->Content = 'orig';
$page1->write();
$page1->publish('Stage', 'Live');
$page1->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$origVersion = $page1->Version;
$page1->Content = 'changed';
$page1->write();
$page1->publish('Stage', 'Live');
$page1->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$changedVersion = $page1->Version;
$page1->doRollbackTo($origVersion);
@ -287,7 +287,7 @@ class VersionedTest extends SapphireTest {
$page1->Content = 'orig';
$page1->write();
$page1->publish('Stage', 'Live');
$page1->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$this->assertEquals(1,
DB::query('SELECT COUNT(*) FROM "VersionedTest_DataObject" WHERE "ID" = '.$pageID)->value());
@ -842,7 +842,7 @@ class VersionedTest extends SapphireTest {
$record->ExtraField = "Test A";
$record->writeToStage("Stage");
$this->assertRecordHasLatestVersion($record, 1);
$record->publish("Stage", "Live");
$record->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$this->assertRecordHasLatestVersion($record, 1);
$record->Title = "Test A2";
$record->ExtraField = "Test A2";
@ -854,7 +854,7 @@ class VersionedTest extends SapphireTest {
$record->ExtraField = "Test B";
$record->writeToStage("Stage");
$this->assertRecordHasLatestVersion($record, 1);
$record->publish("Stage", "Live");
$record->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$this->assertRecordHasLatestVersion($record, 1);
$record->ExtraField = "Test B2";
$record->writeToStage("Stage");
@ -865,7 +865,7 @@ class VersionedTest extends SapphireTest {
$record->Title = "Test C";
$record->writeToStage("Stage");
$this->assertRecordHasLatestVersion($record, 1);
$record->publish("Stage", "Live");
$record->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$this->assertRecordHasLatestVersion($record, 1);
$record->Title = "Test C2";
$record->writeToStage("Stage");
@ -877,7 +877,7 @@ class VersionedTest extends SapphireTest {
$record->AnotherField = "Test A";
$record->writeToStage("Stage");
$this->assertRecordHasLatestVersion($record, 1);
$record->publish("Stage", "Live");
$record->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$this->assertRecordHasLatestVersion($record, 1);
$record->Title = "Test A2";
$record->AnotherField = "Test A2";
@ -890,7 +890,7 @@ class VersionedTest extends SapphireTest {
$record->AnotherField = "Test B";
$record->writeToStage("Stage");
$this->assertRecordHasLatestVersion($record, 1);
$record->publish("Stage", "Live");
$record->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$this->assertRecordHasLatestVersion($record, 1);
$record->AnotherField = "Test B2";
$record->writeToStage("Stage");
@ -901,7 +901,7 @@ class VersionedTest extends SapphireTest {
$record->Title = "Test C";
$record->writeToStage("Stage");
$this->assertRecordHasLatestVersion($record, 1);
$record->publish("Stage", "Live");
$record->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$this->assertRecordHasLatestVersion($record, 1);
$record->Title = "Test C2";
$record->writeToStage("Stage");
@ -915,7 +915,7 @@ class VersionedTest extends SapphireTest {
"NewField" => "Varchar",
));
VersionedTest_RelatedWithoutVersion::add_extension("Versioned('Stage', 'Live')");
VersionedTest_RelatedWithoutVersion::add_extension("Versioned");
$this->resetDBSchema(true);
$testData = new VersionedTest_RelatedWithoutVersion();
$testData->NewField = 'Test';
@ -945,7 +945,7 @@ class VersionedTest extends SapphireTest {
$this->assertFalse($private->canView());
// Writing the private page to live should be fine though
$private->publish("Stage", "Live");
$private->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$privateLive = Versioned::get_one_by_stage('VersionedTest_DataObject', 'Live', array('"ID"' => $privateID));
$this->assertTrue($private->canView());
$this->assertTrue($privateLive->canView());
@ -984,8 +984,8 @@ class VersionedTest extends SapphireTest {
$this->assertFalse($private->canViewStage('Live'));
// Writing records to live should make both stage and live modes viewable
$private->publish("Stage", "Live");
$public->publish("Stage", "Live");
$private->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$public->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
$this->assertTrue($public->canViewStage('Stage'));
$this->assertTrue($private->canViewStage('Stage'));
$this->assertTrue($public->canViewStage('Live'));
@ -1012,6 +1012,7 @@ class VersionedTest extends SapphireTest {
*
* @package framework
* @subpackage tests
* @mixin Versioned
*/
class VersionedTest_DataObject extends DataObject implements TestOnly {
private static $db = array(
@ -1021,7 +1022,7 @@ class VersionedTest_DataObject extends DataObject implements TestOnly {
);
private static $extensions = array(
"Versioned('Stage', 'Live')",
"Versioned",
);
private static $has_one = array(
@ -1046,6 +1047,9 @@ class VersionedTest_DataObject extends DataObject implements TestOnly {
}
}
/**
* @mixin Versioned
*/
class VersionedTest_WithIndexes extends DataObject implements TestOnly {
private static $db = array(
@ -1106,6 +1110,9 @@ class VersionedTest_UnversionedWithField extends DataObject implements TestOnly
private static $db = array('Version' => 'Varchar(255)');
}
/**
* @mixin Versioned
*/
class VersionedTest_SingleStage extends DataObject implements TestOnly {
private static $db = array(
'Name' => 'Varchar'
@ -1118,6 +1125,8 @@ class VersionedTest_SingleStage extends DataObject implements TestOnly {
/**
* Versioned dataobject with public stage mode
*
* @mixin Versioned
*/
class VersionedTest_PublicStage extends DataObject implements TestOnly {
private static $db = array(
@ -1144,6 +1153,9 @@ class VersionedTest_PublicStage extends DataObject implements TestOnly {
/**
* Public access is provided via extension rather than overriding canViewVersioned
*
* @mixin Versioned
* @mixin VersionedTest_PublicExtension
*/
class VersionedTest_PublicViaExtension extends DataObject implements TestOnly {