1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace GeminiLabs\Castor; |
4
|
|
|
|
5
|
|
|
use GeminiLabs\Castor\Helpers\PostMeta; |
6
|
|
|
use GeminiLabs\Castor\Helpers\Utility; |
7
|
|
|
|
8
|
|
|
class Image |
9
|
|
|
{ |
10
|
|
|
public $image; |
11
|
|
|
|
12
|
|
|
protected $postmeta; |
13
|
|
|
protected $utility; |
14
|
|
|
|
15
|
|
|
public function __construct( PostMeta $postmeta, Utility $utility ) |
16
|
|
|
{ |
17
|
|
|
$this->postmeta = $postmeta; |
18
|
|
|
$this->utility = $utility; |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param int|string $attachment |
23
|
|
|
* |
24
|
|
|
* @return self |
25
|
|
|
*/ |
26
|
|
|
public function get( $attachment ) |
27
|
|
|
{ |
28
|
|
|
if( !( $attachment = $this->normalize( $attachment )))return; |
29
|
|
|
if( $thumbnail = wp_get_attachment_image_src( $attachment, 'thumbnail' )) { |
30
|
|
|
$medium = $this->normalizeSrc( wp_get_attachment_image_src( $attachment, 'medium' ), $thumbnail ); |
31
|
|
|
$large = $this->normalizeSrc( wp_get_attachment_image_src( $attachment, 'large' ), $medium ); |
32
|
|
|
|
33
|
|
|
$this->image = (object) [ |
34
|
|
|
'alt' => wp_strip_all_tags( get_post_meta( $attachment, '_wp_attachment_image_alt', true ), true ), |
35
|
|
|
'caption' => wp_get_attachment_caption( $attachment ), |
36
|
|
|
'copyright' => wp_strip_all_tags( get_post_meta( $attachment, '_copyright', true ), true ), |
37
|
|
|
'ID' => $attachment, |
38
|
|
|
'large' => $large, |
39
|
|
|
'medium' => $medium, |
40
|
|
|
'permalink' => get_attachment_link( $attachment ), |
41
|
|
|
'thumbnail' => $this->normalizeSrc( $thumbnail ), |
42
|
|
|
]; |
43
|
|
|
} |
44
|
|
|
return $this; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public function render( $size = 'large' ) |
48
|
|
|
{ |
49
|
|
|
if( $this->image ) { |
50
|
|
|
return wp_get_attachment_image( $this->image->ID, $size ); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
protected function normalize( $attachmentId ) |
55
|
|
|
{ |
56
|
|
|
if( !filter_var( $attachmentId, FILTER_VALIDATE_INT )) { |
57
|
|
|
$attachmentId = $this->postmeta->get( $attachmentId ); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$attachment = get_post( $attachmentId ); |
61
|
|
|
|
62
|
|
|
if( is_null( $attachment ) || $attachment->post_type != 'attachment' )return; |
63
|
|
|
|
64
|
|
|
return $attachment->ID; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @param mixed $fallback |
69
|
|
|
* |
70
|
|
|
* @return array |
71
|
|
|
*/ |
72
|
|
|
protected function normalizeSrc( array $image, $fallback = false ) |
73
|
|
|
{ |
74
|
|
|
if( is_array( $fallback ) && count( array_diff( $image, $fallback )) < 2 ) { |
75
|
|
|
$image = $fallback; |
76
|
|
|
} |
77
|
|
|
return [ |
78
|
|
|
'url' => $image[0], |
79
|
|
|
'width' => $image[1], |
80
|
|
|
'height' => $image[2], |
81
|
|
|
]; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|