QueryEncoder::encode()   A
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 15
cts 15
cp 1
rs 9.552
c 0
b 0
f 0
cc 4
nc 8
nop 1
crap 4
1
<?php
2
3
namespace SEQL;
4
5
use SMWQuery as Query;
6
7
/**
8
 * @license GNU GPL v2+
9
 * @since 1.0
10
 *
11
 * @author mwjames
12
 */
13
class QueryEncoder {
14
15
	/**
16
	 * @since 1.0
17
	 *
18
	 * @param Query $query
19
	 *
20
	 * @return string
21
	 */
22 5
	public static function rawUrlEncode( Query $query ) {
23 5
		return rawurlencode( self::encode( $query ) );
24
	}
25
26
	/**
27
	 * @since 1.0
28
	 *
29
	 * @param Query $query
30
	 *
31
	 * @return string
32
	 */
33 5
	public static function encode( Query $query ) {
34 5
		$serialized = array();
35
36 5
		$serialized['conditions'] = $query->getQueryString();
37
38 5
		$serialized['parameters'] = array(
39 5
			'limit=' . $query->getLimit(),
40 5
			'offset=' . $query->getOffset(),
41 5
			'mainlabel=' . $query->getMainlabel(),
42
		//	'source=' . $query->getQuerySource()
43
		);
44
45 5
		list( $serialized['sort'], $serialized['order'] ) = self::doSerializeSortKeys( $query );
46 5
		$serialized['printouts'] = self::doSerializePrintouts( $query );
47
48 5
		$encoded = $serialized['conditions'] . '|' .
49 5
			( $serialized['printouts'] !== array() ? implode( '|', $serialized['printouts'] ) . '|' : '' ) .
50 5
			implode( '|', $serialized['parameters'] ) .
51 5
			( $serialized['sort'] !==  array() ? '|sort=' . implode( ',', $serialized['sort'] ) : '' ) .
52 5
			( $serialized['order'] !== array() ? '|order=' . implode( ',', $serialized['order'] ) : '' );
53
54 5
		return $encoded;
55
	}
56
57 5
	private static function doSerializePrintouts( $query ) {
58
59 5
		$printouts = array();
60
61 5
		foreach ( $query->getExtraPrintouts() as $printout ) {
62 2
			$serialization = $printout->getSerialisation();
63 2
			if ( $serialization !== '?#' ) {
64
				// #show adds an extra = at the end which is interpret as
65
				// requesting an empty result hence it is removed
66 2
				$printouts[] = substr( $serialization, -1 ) === '=' ? substr( $serialization, 0, -1 ) : $serialization;
67 2
			}
68 5
		}
69
70 5
		return $printouts;
71
	}
72
73 5
	private static function doSerializeSortKeys( $query ) {
74
75 5
		$sort = array();
76 5
		$order = array();
77
78 5
		foreach ( $query->getSortKeys() as $key => $value ) {
79
80 2
			if ( $key === '' ) {
81
				continue;
82
			}
83
84 2
			$sort[] = $key;
85 2
			$order[] = strtolower( $value );
86 5
		}
87
88 5
		return array( $sort, $order );
89
	}
90
91
}
92