atdc/web/modules/custom/example/src/Builder/PostBuilder.php

93 lines
1.6 KiB
PHP
Raw Normal View History

2024-01-15 08:00:00 +00:00
<?php
namespace Drupal\example\Builder;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\node\Entity\Node;
use Drupal\node\NodeInterface;
2024-01-18 13:25:17 +00:00
use Drupal\taxonomy\Entity\Term;
2024-01-15 08:00:00 +00:00
final class PostBuilder {
2024-01-16 17:50:48 +00:00
private ?DrupalDateTime $created = NULL;
2024-01-15 08:00:00 +00:00
private string $title;
private bool $isPublished = TRUE;
/**
* @var string[]
*/
private array $tags = [];
2024-01-15 08:00:00 +00:00
public static function create(): self {
return new self();
}
2024-01-17 10:49:54 +00:00
public function isNotPublished(): self {
$this->isPublished = FALSE;
2024-01-17 10:49:54 +00:00
return $this;
}
2024-01-17 10:48:44 +00:00
public function isPublished(): self {
$this->isPublished = TRUE;
2024-01-17 10:48:44 +00:00
return $this;
}
2024-01-17 10:46:20 +00:00
public function setCreatedDate(string $time = 'now'): self {
2024-01-15 08:00:00 +00:00
$this->created = new DrupalDateTime($time);
return $this;
}
/**
* @param string[] $tags
*/
public function setTags(array $tags): self {
$this->tags = $tags;
return $this;
}
2024-01-17 10:46:20 +00:00
public function setTitle(string $title): self {
2024-01-15 08:00:00 +00:00
$this->title = $title;
return $this;
}
public function getPost(): NodeInterface {
$post = Node::create([
'status' => $this->isPublished,
2024-01-15 08:00:00 +00:00
'title' => $this->title,
'type' => 'post',
]);
if ($this->created !== NULL) {
$post->setCreatedTime($this->created->getTimestamp());
}
$tagTerms = [];
if ($this->tags !== []) {
foreach ($this->tags as $tag) {
$term = Term::create([
'name' => $tag,
'vid' => 'tags',
]);
$term->save();
$tagTerms[] = $term;
}
2024-01-18 13:25:17 +00:00
$post->set('field_tags', $tagTerms);
}
2024-01-18 13:25:17 +00:00
2024-01-15 08:00:00 +00:00
$post->save();
return $post;
}
}