diff --git a/src/PostData.php b/src/PostData.php index 8f6efc1..e3a3eb2 100644 --- a/src/PostData.php +++ b/src/PostData.php @@ -6,6 +6,7 @@ use Carbon\CarbonImmutable; use Corcel\Model\Post; +use Illuminate\Support\Collection; use ReflectionClass; use ReflectionNamedType; use RuntimeException; @@ -102,7 +103,7 @@ private static function dataClass(string $postType): string if (null === $classFQN) { return static::class; } - + if (! class_exists($classFQN)) { throw new RuntimeException(sprintf('The class "%s" does not exist or is not autoloaded.', $classFQN)); } @@ -292,4 +293,53 @@ public function url(): string return \get_permalink($this->id) ?: ''; } + + public function isTopLevelParent(): bool + { + return $this->isParent() && ! $this->isChild(); + } + + public function isParent(): bool + { + return $this->children()->isNotEmpty(); + } + + /** + * @param array $args + * + * @return Collection + * */ + public function children(array $args = []): Collection + { + if (! is_post_type_hierarchical($this->postType) || ! is_numeric($this->id)) { + return collect(); + } + $args = wp_parse_args($args, [ + 'post_parent' => $this->id, + 'post_type' => $this->postType, + 'order' => 'ASC', + 'orderby' => 'menu_order', + ]); + $children = get_children($args); + + return static::collect($children, Collection::class); + } + + public function isChild(): bool + { + return null !== $this->parent(); + } + + public function parent(): ?PostData + { + if (! is_post_type_hierarchical($this->postType) || ! is_numeric($this->id)) { + return null; + } + $parent = get_post_parent($this->id); + if (null === $parent) { + return null; + } + + return static::fromPost($parent); + } }