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

55 lines
960 B
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;
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;
public static function create(): self {
return new self();
}
2024-01-17 10:49:54 +00:00
public function isNotPublished(): self {
return $this;
}
2024-01-17 10:48:44 +00:00
public function isPublished(): self {
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;
}
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([
'title' => $this->title,
'type' => 'post',
]);
if ($this->created !== NULL) {
$post->setCreatedTime($this->created->getTimestamp());
}
2024-01-15 08:00:00 +00:00
$post->save();
return $post;
}
}