Position::center()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jonasdamher\Simplifyimage\Utils;
6
7
use Jonasdamher\Simplifyimage\Core\ResponseHandler;
8
9
/**
10
 * Image crop position.
11
 */
12
class Position
13
{
14
15
	private array $positions = ['center', 'left', 'bottom', 'topRight', 'topLeft', 'top', 'right', 'bottomRight', 'bottomLeft'];
16
17
	private array $position = [
18
		'x' => 0,
19
		'y' => 0
20
	];
21
22
	private array $dimensions = [];
23
	private string $cropPosition = 'center';
24
25
	public function get(): string
26
	{
27
		return $this->cropPosition;
28
	}
29
30
	/**
31
	 * Has options center, left, right, 
32
	 * top, topLeft, topRight, 
33
	 * bottom, bottomLeft or bottomRight.
34
	 * @param string $cropPosition
35
	 */
36
	public function set(string $cropPosition)
37
	{
38
		try {
39
			if (!in_array($cropPosition, $this->positions, true)) {
40
				throw new \Exception("Don't exist position (" . $cropPosition . ')');
41
			}
42
		} catch (\Exception $e) {
43
			$cropPosition = 'center';
44
			ResponseHandler::fail($e->getMessage());
45
		} finally {
46
			$this->cropPosition = $cropPosition;
47
		}
48
	}
49
50
	private function center()
51
	{
52
		($this->dimensions['x'] >= $this->dimensions['y']) ?
53
			$this->position['x'] = ($this->dimensions['x'] - $this->dimensions['y']) / 2 :
54
			$this->position['y'] = ($this->dimensions['y'] - $this->dimensions['x']) / 2;
55
	}
56
57
	private function left()
58
	{
59
		$this->position['x'] = 0;
60
	}
61
62
	private function right()
63
	{
64
		$this->position['x'] = $this->dimensions['x'] - $this->dimensions['y'];
65
	}
66
67
	private function top()
68
	{
69
		$this->position['y'] = 0;
70
	}
71
72
	private function topLeft()
73
	{
74
		$this->position['y'] = 0;
75
		$this->position['x'] = 0;
76
	}
77
78
	private function topRight()
79
	{
80
		$this->position['y'] = 0;
81
		$this->position['x'] = $this->dimensions['x'] - $this->dimensions['y'];
82
	}
83
84
	private function bottom()
85
	{
86
		$this->position['y'] = $this->dimensions['y'] - $this->dimensions['x'];
87
	}
88
89
	private function bottomLeft()
90
	{
91
		$this->position['y'] = $this->dimensions['y'] - $this->dimensions['x'];
92
		$this->position['x'] = 0;
93
	}
94
95
	private function bottomRight()
96
	{
97
		$this->position['y'] = $this->dimensions['y'] - $this->dimensions['x'];
98
		$this->position['x'] = $this->dimensions['x'] - $this->dimensions['y'];
99
	}
100
101
	public function new(array $dimensions): array
102
	{
103
		$method = $this->get();
104
105
		if (method_exists(__CLASS__, $method)) {
106
			$this->dimensions = $dimensions;
107
			$this->$method();
108
		}
109
110
		return $this->position;
111
	}
112
}
113