Completed
Pull Request — development (#841)
by
unknown
06:38
created

Image_Field::get_preview_size()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Carbon_Fields\Field;
4
5
use Carbon_Fields\Exception\Incorrect_Syntax_Exception;
6
7
/**
8
 * Image field class.
9
 *
10
 * Allows selecting and saving a media attachment file,
11
 * where the image ID is saved in the database.
12
 */
13
class Image_Field extends File_Field {
14
	public $field_type = 'image';
15
16
	/**
17
	 * The size of the image preview
18
	 *
19
	 * @see set_preview_size()
20
	 * @var string|array
21
	 */
22
	protected $preview_size = [
23
		'width' => 130,
24
		'height' => 130,
25
	];
26
27
	/**
28
	 * Get the image preview size.
29
	 *
30
	 * @return  string|array
31
	 */
32
	public function get_preview_size() {
33
		return $this->preview_size;
34
	}
35
36
	/**
37
	 * Set the image preview size.
38
	 *
39
	 * @param  string|array  $size
40
	 * @return self  $this
41
	 */
42
	public function set_preview_size( $size ) {
43
		if ( is_array( $size ) ) {
44
			$this->preview_size = [
45
				'width' => $size[0],
46
				'height' => $size[1],
47
			];
48
		} else {
49
			$registered_image_sizes = get_intermediate_image_sizes();
50
			if ( ! in_array( $size, $registered_image_sizes ) ) {
51
				Incorrect_Syntax_Exception::raise( 'Image preview size is not found. Must be one of the following - ' . implode( ', ' , $registered_image_sizes ) . ' ("' . $size . '" passed).' );
52
			}
53
54
			$this->preview_size = [
55
				'width' => intval( get_option( "{$size}_size_w" ) ),
56
				'height' => intval( get_option( "{$size}_size_h" ) ),
57
			];
58
		}
59
60
		return $this;
61
	}
62
63
	/**
64
	 * {@inheritDoc}
65
	 */
66
	public function to_json( $load ) {
67
		$field_data = parent::to_json( $load );
68
69
		$field_data = array_merge( $field_data, array(
70
			'preview_size' => $this->get_preview_size(),
71
		) );
72
73
		return $field_data;
74
	}
75
}
76