View source  
  <?php
namespace Drupal\social_post\Entity;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\social_core\EntityUrlLanguageTrait;
use Drupal\user\RoleInterface;
use Drupal\user\UserInterface;
class Post extends ContentEntityBase implements PostInterface {
  use EntityChangedTrait;
  use EntityUrlLanguageTrait;
  
  public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
    parent::preCreate($storage_controller, $values);
    $values += [
      'user_id' => \Drupal::currentUser()
        ->id(),
    ];
  }
  
  public function getCreatedTime() {
    return $this
      ->get('created')->value;
  }
  
  public function setCreatedTime($timestamp) {
    $this
      ->set('created', $timestamp);
    return $this;
  }
  
  public function getOwner() {
    return $this
      ->get('user_id')->entity;
  }
  
  public function getOwnerId() {
    return $this
      ->get('user_id')->target_id;
  }
  
  public function setOwnerId($uid) {
    $this
      ->set('user_id', $uid);
    return $this;
  }
  
  public function setOwner(UserInterface $account) {
    $this
      ->set('user_id', $account
      ->id());
    return $this;
  }
  
  public function isPublished() {
    return (bool) $this
      ->getEntityKey('status');
  }
  
  public function setPublished($published) {
    $this
      ->set('status', $published ? NODE_PUBLISHED : NODE_NOT_PUBLISHED);
    return $this;
  }
  
  public function getType() {
    return $this
      ->bundle();
  }
  
  public function setType($type) {
    $this
      ->set('type', $type);
    return $this;
  }
  
  public function getDisplayName() {
    if ($this
      ->hasField('field_post_image') && !$this
      ->get('field_post_image')
      ->isEmpty()) {
      return t('photo');
    }
    return t('post');
  }
  
  public function getVisibility() {
    $allowed_values = $this
      ->getPostVisibilityAllowedValues();
    if ($this
      ->hasField('field_visibility')) {
      foreach ($allowed_values as $key => $allowed_value) {
        if ($this->field_visibility->value == $allowed_value['value']) {
          
          $visibility = $this
            ->getDefaultVisibilityByLabel($allowed_value['label']);
          
          if (!$visibility) {
            $roles = $this
              ->entityTypeManager()
              ->getStorage('user_role')
              ->getQuery()
              ->condition('label', $allowed_value['label'])
              ->execute();
            $role_id = reset($roles);
            
            if (!empty($role_id)) {
              $visibility = $role_id;
            }
          }
        }
      }
    }
    return $visibility;
  }
  
  public function getDefaultVisibilityByLabel($label, $reverse = FALSE) {
    $default_visibilities = [
      [
        'id' => 'community',
        'label' => 'Community',
      ],
      [
        'id' => 'public',
        'label' => 'Public',
      ],
      [
        'id' => 'group',
        'label' => 'Group members',
      ],
    ];
    if ($reverse) {
      foreach ($default_visibilities as $visibility) {
        if ($visibility['id'] == $label) {
          return $visibility['label'];
        }
      }
    }
    else {
      foreach ($default_visibilities as $visibility) {
        if ($visibility['label'] == $label) {
          return $visibility['id'];
        }
      }
    }
  }
  
  private function getPostVisibilityAllowedValues() {
    
    $post_storage = 'field.storage.post.field_visibility';
    $config = \Drupal::configFactory()
      ->getEditable($post_storage);
    return $config
      ->getOriginal('settings.allowed_values');
  }
  
  public function setVisibility($visibility) {
    $allowed_values = $this
      ->getPostVisibilityAllowedValues();
    $visibility_label = $this
      ->getDefaultVisibilityByLabel($visibility, TRUE);
    if (!$visibility_label) {
      
      $role = $this
        ->entityTypeManager()
        ->getStorage('user_role')
        ->load($visibility);
      if ($role instanceof RoleInterface) {
        foreach ($allowed_values as $key => $value) {
          if ($value['label'] === $role
            ->label()) {
            $this
              ->set('field_visibility', $key);
          }
        }
      }
    }
    else {
      foreach ($allowed_values as $key => $allowed_value) {
        if ($visibility_label == $allowed_value['label']) {
          $this
            ->set('field_visibility', (int) $allowed_value['value']);
        }
      }
    }
    return $this;
  }
  
  public function getCacheContexts() {
    $defaults = parent::getCacheContexts();
    
    if (!in_array('user', $defaults)) {
      $defaults[] = 'user';
    }
    return $defaults;
  }
  
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);
    $fields['id'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('ID'))
      ->setDescription(t('The ID of the Post entity.'))
      ->setReadOnly(TRUE);
    $fields['uuid'] = BaseFieldDefinition::create('uuid')
      ->setLabel(t('UUID'))
      ->setDescription(t('The UUID of the Post entity.'))
      ->setReadOnly(TRUE);
    $fields['user_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Authored by'))
      ->setDescription(t('The user ID of author of the Post entity.'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'user')
      ->setSetting('handler', 'default')
      ->setDefaultValueCallback('Drupal\\node\\Entity\\Node::getCurrentUserId')
      ->setTranslatable(TRUE)
      ->setDisplayOptions('view', [
      'label' => 'hidden',
      'type' => 'author',
      'weight' => 0,
    ])
      ->setDisplayOptions('form', [
      'type' => 'entity_reference_autocomplete',
      'weight' => 5,
      'settings' => [
        'match_operator' => 'CONTAINS',
        'size' => '60',
        'autocomplete_type' => 'tags',
        'placeholder' => '',
      ],
    ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);
    $fields['status'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Published'))
      ->setDefaultValue(TRUE);
    $fields['status']
      ->setDisplayOptions('form', [
      'type' => 'boolean_checkbox',
      'settings' => [
        'display_label' => TRUE,
      ],
      'weight' => 20,
    ])
      ->setDisplayConfigurable('form', TRUE);
    $fields['langcode'] = BaseFieldDefinition::create('language')
      ->setLabel(t('Language code'))
      ->setDescription(t('The language code for the Post entity.'))
      ->setDisplayOptions('form', [
      'type' => 'language_select',
      'weight' => 10,
    ])
      ->setDisplayConfigurable('form', TRUE);
    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created'))
      ->setDescription(t('The time that the entity was created.'));
    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time that the entity was last edited.'));
    return $fields;
  }
}