You are here

public function ReadingTime::collectWords in Node read time 8

Gets the fields from allowed types.

Parameters

object $entity: The Entity that should be checked for textfields.

Return value

\Drupal\node_read_time\Calculate\ReadingTime Returns this class object.

File

src/Calculate/ReadingTime.php, line 126

Class

ReadingTime
Calculates the reading time of a node.

Namespace

Drupal\node_read_time\Calculate

Code

public function collectWords($entity) {
  $entity_fields = !empty($entity) ? $entity
    ->getFieldDefinitions() : NULL;
  $allowedTypes = [
    'text',
    'text_long',
    'text_with_summary',
    'string_long',
    'entity_reference_revisions',
  ];
  if ($entity_fields) {

    // Clean the unnecessary fields.
    foreach ($entity_fields as $k => $field) {
      if (!in_array($field
        ->getType(), $allowedTypes)) {
        unset($entity_fields[$k]);
      }

      // Remove revision fields.
      if (strpos($k, 'revision') !== FALSE) {
        unset($entity_fields[$k]);
      }
    }
    foreach ($entity_fields as $k => $field) {
      if (!empty($entity
        ->get($k)
        ->getValue()[0]['value'])) {
        $this->words .= $entity
          ->get($k)
          ->getValue()[0]['value'];
      }
      elseif ($field
        ->getType() == 'entity_reference_revisions') {
        $fieldStorage = $entity_fields[$k]
          ->get('fieldStorage');
        if ($fieldStorage) {
          $entityType = $fieldStorage
            ->get('settings')['target_type'];
          $list = $entity
            ->get($k)
            ->getValue();
          foreach ($list as $item) {
            $referenceRevisionEntity = $this->entityTypeManager
              ->getStorage($entityType)
              ->load($item['target_id']);
            $this
              ->collectWords($referenceRevisionEntity);
          }
        }
      }
    }
  }
  return $this;
}