summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/SQLStore/QueryEngine/DescriptionInterpreters/ComparatorMapper.php
blob: e32ac8c29c267be1c0cc9142bdf6800e4dae3fba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php

namespace SMW\SQLStore\QueryEngine\DescriptionInterpreters;

use RuntimeException;
use SMW\Query\Language\ValueDescription;
use SMWDIUri as DIUri;

/**
 * @license GNU GPL v2+
 * @since 2.2
 *
 * @author mwjames
 */
class ComparatorMapper {

	/**
	 * @since 2.2
	 *
	 * @param ValueDescription $description
	 * @param string &$value
	 *
	 * @return string
	 * @throws RuntimeException
	 */
	public function mapComparator( ValueDescription $description, &$value ) {

		$comparatorMap = [
			SMW_CMP_EQ   => '=',
			SMW_CMP_LESS => '<',
			SMW_CMP_GRTR => '>',
			SMW_CMP_LEQ  => '<=',
			SMW_CMP_GEQ  => '>=',
			SMW_CMP_NEQ  => '!=',
			SMW_CMP_LIKE => ' LIKE ',
			SMW_CMP_PRIM_LIKE => ' LIKE ',
			SMW_CMP_NLKE => ' NOT LIKE ',
			SMW_CMP_PRIM_NLKE => ' NOT LIKE '
		];

		$comparator = $description->getComparator();

		if ( !isset( $comparatorMap[$comparator] ) ) {
			throw new RuntimeException( "Unsupported comparator $comparator in value description." );
		}

		if ( $comparator === SMW_CMP_LIKE || $comparator === SMW_CMP_NLKE || $comparator === SMW_CMP_PRIM_LIKE || $comparator === SMW_CMP_PRIM_NLKE ) {

			if ( $description->getDataItem() instanceof DIUri ) {
				$value = str_replace( [ 'http://', 'https://', '%2A' ], [ '*', '*', '*' ], $value );
			}

			// Escape to prepare string matching:
			$value = str_replace(
				[ '\\', '%', '_', '*', '?' ],
				[ '\\\\', '\%', '\_', '%', '_' ],
				$value
			);
		}

		return $comparatorMap[$comparator];
	}

}