Skip to content

Instantly share code, notes, and snippets.

@bendubuisson
Last active August 30, 2017 08:09
Show Gist options
  • Save bendubuisson/fde1999ae6e2871817fa724088cb79a1 to your computer and use it in GitHub Desktop.
Save bendubuisson/fde1999ae6e2871817fa724088cb79a1 to your computer and use it in GitHub Desktop.
Trait for non versioned SilverStripe 4 DataObjects. Files associated to DataObjects that are non-versioned do not get published by default.
<?php
namespace MyProject\Traits;
use SilverStripe\Assets\Image;
/**
* Class PublishRelatedFilesTrait
* @package MyProject\Traits
*/
trait PublishRelatedFilesTrait
{
/**
* Publish our dependent objects.
*/
public function onAfterWrite()
{
$hasOnes = $this->stat('has_one');
foreach ($hasOnes as $relation => $class) {
if ($class == Image::class || $class == File::class) {
$this->publishRelatedObject($this->$relation());
}
}
$hasMultiples = array_merge($this->stat('has_many'), $this->stat('many_many'));
foreach ($hasMultiples as $relation => $class) {
if ($class == Image::class || $class == File::class) {
foreach ($this->$relation() as $object) {
$this->publishRelatedObject($object);
}
}
}
parent::onAfterWrite();
}
/**
* @param $object
*/
protected function publishRelatedObject($object)
{
if ($object && $object->exists()) {
$object->publishSingle();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment