1<?php
2
3namespace PageImages;
4
5use File;
6use JsonSerializable;
7
8/**
9 * Value object to hold information about page image candidates.
10 * @package PageImages
11 */
12class PageImageCandidate implements JsonSerializable {
13
14	/** @var string */
15	private $fileName;
16
17	/** @var int */
18	private $fullWidth = 0;
19
20	/** @var int */
21	private $fullHeight = 0;
22
23	/** @var int */
24	private $handlerWidth = 0;
25
26	/**
27	 * Private constructor.
28	 * Use self::newFromFileAndParams to instantiate.
29	 */
30	private function __construct() {
31	}
32
33	/**
34	 * @param File $file
35	 * @param array $fileParams from ParserMakeImageParams hook.
36	 * @return PageImageCandidate
37	 */
38	public static function newFromFileAndParams( File $file, array $fileParams ) : self {
39		$instance = new self();
40		$instance->fileName = $file->getTitle()->getDBkey();
41		$instance->fullWidth = $file->getWidth() ?? 0;
42		$instance->fullHeight = $file->getHeight() ?? 0;
43		if ( isset( $fileParams['handler']['width'] ) ) {
44			$instance->handlerWidth = $fileParams['handler']['width'] ?? 0;
45		}
46		return $instance;
47	}
48
49	/**
50	 * Instantiate PageImageCandidate from $json created with self::jsonSerialize
51	 *
52	 * @param array $array
53	 * @return PageImageCandidate
54	 * @internal
55	 */
56	public static function newFromArray( array $array ) : self {
57		$instance = new self();
58		$instance->fileName = $array['filename'];
59		$instance->fullWidth = $array['fullwidth'] ?? 0;
60		$instance->fullHeight = $array['fullheight'] ?? 0;
61		if ( isset( $array['handler']['width'] ) ) {
62			$instance->handlerWidth = $array['handler']['width'] ?? 0;
63		}
64		return $instance;
65	}
66
67	/**
68	 * @return string
69	 */
70	public function getFileName() : string {
71		return $this->fileName;
72	}
73
74	/**
75	 * @return int
76	 */
77	public function getFullWidth(): int {
78		return $this->fullWidth;
79	}
80
81	/**
82	 * @return int
83	 */
84	public function getFullHeight(): int {
85		return $this->fullHeight;
86	}
87
88	/**
89	 * @return int
90	 */
91	public function getHandlerWidth(): int {
92		return $this->handlerWidth;
93	}
94
95	/**
96	 * @internal
97	 * @return array
98	 */
99	public function jsonSerialize() {
100		return [
101			'filename' => $this->getFileName(),
102			'fullwidth' => $this->getFullWidth(),
103			'fullheight' => $this->getFullHeight(),
104			// Wrap in handler array for backwards-compatibility.
105			'handler' => [
106				'width' => $this->getHandlerWidth()
107			]
108		];
109	}
110}
111