Completed
Push — develop ( c614b1...023ff7 )
by David
03:14
created

Wordlift_Image_Service::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Services: Image Service.
4
 *
5
 * Add support for 16x9, 4x3 and 1x1 images as requested by Google specs.
6
 *
7
 * @see https://github.com/insideout10/wordlift-plugin/issues/830.
8
 * @see https://developers.google.com/search/docs/data-types/article.
9
 *
10
 * @since 3.19.4
11
 * @package Wordlift
12
 * @subpackage Wordlift/includes
13
 */
14
15
/**
16
 * Define the Wordlift_Image_Service class.
17
 *
18
 * @since 3.19.4
19
 */
20
class Wordlift_Image_Service {
21
22
	/**
23
	 * The image ratios and sizes.
24
	 *
25
	 * @since 3.19.4
26
	 * @access public
27
	 * @var array $sizes The image ratios and sizes.
28
	 */
29
	public static $sizes = array(
30
		'16x9' => array( 1200, 675 ),
31
		'4x3'  => array( 1200, 900 ),
32
		'1x1'  => array( 1200, 1200 ),
33
	);
34
35
	/**
36
	 * Create a {@link Wordlift_Image_Service} instance.
37
	 *
38
	 * @since 3.19.4
39
	 */
40
	public function __construct() {
41
42
		// Add hook to define the image sizes. Since we're a plugin, we cannot use the
43
		// `after_theme_setup` hook.
44
		add_action( 'init', array( $this, 'after_theme_setup' ) );
45
46
	}
47
48
	/**
49
	 * Hook `after_theme_setup`: add our own image sizes.
50
	 *
51
	 * @since 3.19.4
52
	 */
53
	public function after_theme_setup() {
54
55
		foreach ( self::$sizes as $ratio => $sizes ) {
56
			add_image_size( "wl-$ratio", $sizes[0], $sizes[1], true );
57
		}
58
59
	}
60
61
	/**
62
	 * Get the sources for the specified attachment.
63
	 *
64
	 * @since 3.19.4
65
	 *
66
	 * @param int   $attachment_id The attachment id.
67
	 *
68
	 * @return array {
69
	 * An array of image sources.
70
	 *
71
	 * @type string $url The attachment URL.
72
	 * @type int    $width The attachment width.
73
	 * @type int    $height The attachment height.
74
	 * }
75
	 */
76
	public static function get_sources( $attachment_id ) {
77
78
		// Get the source for the specified image sizes.
79
		$sources = array_map( function ( $ratio ) use ( $attachment_id ) {
80
81
			// Get the source of the specified ratio.
82
			$source = wp_get_attachment_image_src( $attachment_id, "wl-$ratio" );
83
84
			// Get the size for the specified ratio.
85
			$size = Wordlift_Image_Service::$sizes[ $ratio ];
86
87
			// Check that the source has an image, and the required size.
88
			if ( empty( $source[0] ) || $size[0] !== $source[1] || $size[1] !== $source[2] ) {
89
				return null;
90
			}
91
92
			// Return the source.
93
			return $source;
94
		}, array_keys( self::$sizes ) );
95
96
		// Filter unavailable sources.
97
		$sources_1200 = array_filter( $sources );
98
99
		// Make the results unique.
100
		return $sources_1200;
101
	}
102
103
}
104