feat: add new methods for Attachment type (#12)

Reviewed-on: https://codeberg.org/vlw/wp/pulls/12
This commit is contained in:
Victor Westerlund 2026-02-22 11:04:10 +01:00
parent 1296208866
commit 1ff1e1aabe

View file

@ -2,6 +2,9 @@
namespace vlw\WP\Posts\Type; namespace vlw\WP\Posts\Type;
use Exception;
use vlw\MimeTypes\MimeTypes;
use vlw\WP\Posts\Post; use vlw\WP\Posts\Post;
use vlw\WP\Posts\PostMeta; use vlw\WP\Posts\PostMeta;
use function vlw\WP\Support\slugify; use function vlw\WP\Support\slugify;
@ -13,8 +16,9 @@
class Attachment { class Attachment {
private const META_KEY_THUMBNAIL_ID = "_thumbnail_id"; private const META_KEY_THUMBNAIL_ID = "_thumbnail_id";
private const META_KEY_FEATURED_MEDIA = "_featured_media"; 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 * Return featured media for a Post if it exists
@ -73,6 +77,7 @@
$post->post_title = slugify($title); $post->post_title = slugify($title);
$post->guid = $url; $post->guid = $url;
$post->post_status = "inherit";
$post->post_type = "attachment"; $post->post_type = "attachment";
return new static($post->id); return new static($post->id);
@ -82,20 +87,45 @@
$this->post = new Post($id); $this->post = new Post($id);
} }
public string|false $content {
get => file_get_contents($this->post->guid);
}
/**
* Set the pathname for this Attachemnt to a file on disk
*
* @param string $pathname
* @return void
*/
public function set_attached_file(string $pathname): void {
PostMeta::new($this->post, self::META_KEY_WP_ATTACHED_FILE, $pathname);
}
/**
* Set Attachemnt data from a file on disk
*
* @param string $file
* @return void
*/
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 * Make this Attachment the featured media of a Post
* *
* @param Post $post * @param Post $post
* @return object * @return object
*/ */
public function set_post_featured(Post $post): object { public function set_post_featured(Post $post): void {
return (object) [ PostMeta::new($post, self::META_KEY_THUMBNAIL_ID, $this->id);
"thumbnail" => 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}\";}");
"featured_media" => PostMeta::new($post, self::META_KEY_FEATURED_MEDIA, "a:1:{i:0;s:3:\"{$this->id}\";}")
];
}
public string|false $content { $this->post->post_parent = $post;
get => file_get_contents($this->post->guid);
} }
} }