diff --git a/src/Posts/Type/Attachment.php b/src/Posts/Type/Attachment.php index 9de28af..5e5cd2c 100644 --- a/src/Posts/Type/Attachment.php +++ b/src/Posts/Type/Attachment.php @@ -2,6 +2,9 @@ namespace vlw\WP\Posts\Type; + use Exception; + use vlw\MimeTypes\MimeTypes; + use vlw\WP\Posts\Post; use vlw\WP\Posts\PostMeta; use function vlw\WP\Support\slugify; @@ -13,8 +16,9 @@ class Attachment { private const META_KEY_THUMBNAIL_ID = "_thumbnail_id"; private const META_KEY_FEATURED_MEDIA = "_featured_media"; + private const META_KEY_WP_ATTACHED_FILE = "_wp_attached_file"; - private readonly Post $post; + public private(set) readonly Post $post; /** * Return featured media for a Post if it exists @@ -73,6 +77,7 @@ $post->post_title = slugify($title); $post->guid = $url; + $post->post_status = "inherit"; $post->post_type = "attachment"; return new static($post->id); @@ -82,20 +87,33 @@ $this->post = new Post($id); } + public string|false $content { + get => file_get_contents($this->post->guid); + } + + public function set_attached_file(string $pathname): void { + PostMeta::new($this->post, self::META_KEY_WP_ATTACHED_FILE, $pathname); + } + + public function set_from_file(string $file): void { + if (!is_file($file)) { + throw new Exception("No file found at location '{$file}'"); + } + + $this->post->post_mime_type = new MimeTypes()->get_type_from_file($file); + $this->set_attached_file($file); + } + /** * Make this Attachment the featured media of a Post * * @param Post $post * @return object */ - public function set_post_featured(Post $post): object { - return (object) [ - "thumbnail" => PostMeta::new($post, self::META_KEY_THUMBNAIL_ID, $this->id), - "featured_media" => PostMeta::new($post, self::META_KEY_FEATURED_MEDIA, "a:1:{i:0;s:3:\"{$this->id}\";}") - ]; - } + public function set_post_featured(Post $post): void { + PostMeta::new($post, self::META_KEY_THUMBNAIL_ID, $this->id); + PostMeta::new($post, self::META_KEY_FEATURED_MEDIA, "a:1:{i:0;s:3:\"{$this->id}\";}"); - public string|false $content { - get => file_get_contents($this->post->guid); + $this->post->post_parent = $post; } }