DefaultVideoHandler.php in CMS Content Sync 2.0.x
File
src/Plugin/cms_content_sync/field_handler/DefaultVideoHandler.php
View source
<?php
namespace Drupal\cms_content_sync\Plugin\cms_content_sync\field_handler;
use Drupal\cms_content_sync\Plugin\FieldHandlerBase;
use Drupal\cms_content_sync\PullIntent;
use Drupal\cms_content_sync\PushIntent;
use Drupal\cms_content_sync\SyncIntent;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\file\Entity\File;
class DefaultVideoHandler extends FieldHandlerBase {
public static function supports($entity_type, $bundle, $field_name, FieldDefinitionInterface $field) {
$allowed = [
'video',
];
return false !== in_array($field
->getType(), $allowed);
}
public function pull(PullIntent $intent) {
$action = $intent
->getAction();
$entity = $intent
->getEntity();
if (SyncIntent::ACTION_DELETE == $action) {
return false;
}
if ($intent
->shouldMergeChanges()) {
return false;
}
$data = $intent
->getProperty($this->fieldName);
if (empty($data)) {
$entity
->set($this->fieldName, null);
}
else {
$result = [];
foreach ($data as $value) {
$meta = $intent
->getEmbeddedEntityData($value);
$file = null;
if (empty($value['uri']) || empty($value['uuid'])) {
$file = $intent
->loadEmbeddedEntity($value);
}
else {
$file = \Drupal::service('entity.repository')
->loadEntityByUuid('file', $value['uuid']);
if (empty($file)) {
$file = File::create([
'uuid' => $value['uuid'],
'uri' => $value['uri'],
'filemime' => $value['mimetype'],
'filesize' => 1,
]);
$file
->setPermanent();
$file
->save();
}
}
if ($file) {
$meta['target_id'] = $file
->id();
$result[] = $meta;
}
}
$entity
->set($this->fieldName, $result);
}
return true;
}
public function push(PushIntent $intent) {
$action = $intent
->getAction();
$entity = $intent
->getEntity();
if (SyncIntent::ACTION_DELETE == $action) {
return false;
}
$result = [];
$data = $entity
->get($this->fieldName)
->getValue();
foreach ($data as $value) {
if (empty($value['target_id'])) {
continue;
}
$file = File::load($value['target_id']);
if ($file) {
unset($value['target_id']);
$uri = $file
->getFileUri();
if ('public://' == substr($uri, 0, 9) || 'private://' == substr($uri, 0, 10)) {
$result[] = $intent
->addDependency($file, $value);
}
else {
$value['uri'] = $uri;
$value['uuid'] = $file
->uuid();
$value['mimetype'] = $file
->getMimeType();
$result[] = $value;
}
}
}
$intent
->setProperty($this->fieldName, $result);
return true;
}
}