PagePropsIdDatabase::getWhere()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace IdGenerator\PackagePrivate;
4
5
use Wikimedia\Rdbms\IDatabase;
6
7
class PagePropsIdDatabase implements IdDatabase {
8
9
	private const FAKE_PAGE_ID = -42;
10
11
	/**
12
	 * @var IDatabase
13
	 */
14
	private $database;
15
16 3
	public function getNewId( IDatabase $database, string $type ): int {
17 3
		$this->database = $database;
18
19 3
		$id = $this->getId( $type );
20
21 3
		$this->storeId( $type, $id );
22
23 3
		return $id;
24
	}
25
26 3
	private function getId( string $type ): int {
27 3
		$currentId = $this->database->selectRow(
28 3
			'page_props',
29 3
			'pp_value',
30 3
			$this->getWhere( $type ),
31 3
			__METHOD__,
32 3
			[ 'FOR UPDATE' ]
33
		);
34
35 3
		if ( is_object( $currentId ) ) {
36 2
			return (int)$currentId->pp_value + 1;
37
		}
38
39 3
		return 1;
40
	}
41
42 3
	private function storeId( string $type, int $id ): bool {
43 3
		if ( $id === 1 ) {
44 3
			return $this->database->insert(
45 3
				'page_props',
46 3
				$this->getInsertValues( $type, $id )
47
			);
48
		}
49
50 2
		return $this->database->update(
51 2
			'page_props',
52 2
			[ 'pp_value' => $id ],
53 2
			$this->getWhere( $type )
54
		);
55
	}
56
57 3
	private function getInsertValues( string $idType, int $id ): array {
58 3
		$values = $this->getWhere( $idType );
59 3
		$values['pp_value'] = $id;
60 3
		return $values;
61
	}
62
63 3
	private function getWhere( string $idType ): array {
64
		return [
65 3
			'pp_page' => self::FAKE_PAGE_ID,
66 3
			'pp_propname' => $this->makePropertyName( $idType )
67
		];
68
	}
69
70 3
	private function makePropertyName( string $idType ): string {
71 3
		return 'id_' . $idType;
72
	}
73
74
}
75