You are here

public function BlogapiCommunicator::setPostCategories in Blog API 8

Callback for saving tags on a node.

Parameters

$nid: The node ID.

$username: Drupal username.

$pass: Drupal password.

$data: The taxonomy data.

Return value

object|bool Either error os a success bool.

File

src/BlogapiCommunicator.php, line 405

Class

BlogapiCommunicator
Class BlogapiCommunicator.

Namespace

Drupal\blogapi

Code

public function setPostCategories($nid, $username, $pass, $data) {

  // Check user authentication.
  $user = $this
    ->authenticate($username, $pass, TRUE);
  if (!$user) {
    return $this
      ->returnXmlError(self::BLOGAPI_XML_ERROR_AUTH);
  }

  // Check if the node exists.
  $node = $this->entityTypeManager
    ->getStorage('node')
    ->load($nid);
  if (!$node) {
    return $this
      ->returnXmlError(self::BLOGAPI_XML_ERROR_NODE_NOT_FOUND, $nid);
  }

  // Check node access for the loaded user.
  if (!$node
    ->access('update', $user)) {
    return $this
      ->returnXmlError(self::BLOGAPI_XML_ERROR_NODE_UPDATE, $nid);
  }
  if (!$this
    ->checkUserNodeAccess($user, $node)) {
    return $this
      ->returnXmlError(self::BLOGAPI_XML_ERROR_NODE_UPDATE, $nid);
  }
  $content_type = $node
    ->getType();
  $field_storage = [];
  $taxonomy_fields = $this
    ->getTaxonomyFields($node);

  // Get the primary taxonomy field from the module settings page.
  $taxonomy_primary_field = $this->blogapiConfig
    ->get('taxonomy_' . $content_type);
  $primary_field_bundles = [];
  if (!is_null($taxonomy_primary_field)) {
    $primary_field_bundles = $this
      ->getCtFieldTargetBundles($content_type, $taxonomy_primary_field);
  }
  foreach ($data as $item) {
    $term = Term::load($item['categoryId']);
    $vocab = $term
      ->getVocabularyId();

    // Try to save the taxonomy term in the primary
    // taxonomy field from the settings form.
    if (in_array($vocab, $primary_field_bundles)) {
      $field_storage[$taxonomy_primary_field][] = $term
        ->id();
    }
    else {
      foreach ($taxonomy_fields as $tax_field) {
        $bundles = $this
          ->getCtFieldTargetBundles($content_type, $tax_field);
        if (in_array($vocab, $bundles)) {
          $field_storage[$tax_field][] = $term
            ->id();
          break;
        }
      }
    }
  }
  if (!empty($field_storage)) {
    foreach ($field_storage as $field_id => $tags) {
      $node
        ->set($field_id, $tags);
    }
    $node
      ->save();
  }
  return TRUE;
}