Completed
Push — master ( aebdf5...2497c6 )
by Jeroen De
02:33 queued 11s
created

PagePropsIdDatabase::getId()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2.004

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 9
cts 10
cp 0.9
rs 9.7666
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2.004
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 1
	public function getNewId( IDatabase $database, string $type ): int {
17 1
		$this->database = $database;
18
19 1
		$id = $this->getId( $type );
20
21 1
		$this->storeId( $type, $id );
22
23 1
		return $id;
24
	}
25
26 1
	private function getId( string $type ): int {
27 1
		$currentId = $this->database->selectRow(
28 1
			'page_props',
29 1
			'pp_value',
30 1
			$this->getWhere( $type ),
31 1
			__METHOD__,
32 1
			[ 'FOR UPDATE' ]
33
		);
34
35 1
		if ( is_object( $currentId ) ) {
36
			return (int)$currentId->pp_value + 1;
37
		}
38
39 1
		return 1;
40
	}
41
42 1
	private function storeId( string $type, int $id ): bool {
43 1
		if ( $id === 1 ) {
44 1
			return $this->database->insert(
45 1
				'page_props',
46 1
				$this->getInsertValues( $type, $id )
47
			);
48
		}
49
50
		return $this->database->update(
51
			'page_props',
52
			[ 'pp_value' => $id ],
53
			$this->getWhere( $type )
54
		);
55
	}
56
57 1
	private function getInsertValues( string $idType, int $id ): array {
58 1
		$values = $this->getWhere( $idType );
59 1
		$values['pp_value'] = $id;
60 1
		return $values;
61
	}
62
63 1
	private function getWhere( string $idType ): array {
64
		return [
65 1
			'pp_page' => self::FAKE_PAGE_ID,
66 1
			'pp_propname' => $this->makePropertyName( $idType )
67
		];
68
	}
69
70 1
	private function makePropertyName( string $idType ): string {
71 1
		return 'id_' . $idType;
72
	}
73
74
}
75