Completed
Push — dev2 ( 306460...f2bafb )
by Gordon
11:37
created

testSimilarChangeMaxDocFreq()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 27
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20
Metric Value
dl 0
loc 27
ccs 0
cts 24
cp 0
rs 8.5806
cc 4
eloc 19
nc 6
nop 0
crap 20
1
<?php
2
use SilverStripe\Elastica\ElasticSearcher;
3
use Elastica\Type;
4
class ElasticSearcherUnitTest extends ElasticsearchBaseTest {
5
	public static $fixture_file = 'elastica/tests/lotsOfPhotos.yml';
6
7
	public static $ignoreFixtureFileFor = array('testResultsForEmptySearch');
8
9
	public function setUp() {
10
		parent::setUp();
11
	}
12
13
	public function tearDown() {
14
		parent::tearDown();
15
	}
16
17
18
	public function testSuggested() {
19
		$es = new ElasticSearcher();
20
		$locale = \i18n::default_locale();
21
		$es->setLocale($locale);
22
		$es->setClasses('FlickrPhotoTO');
23
		$fields = array('Title' => 1, 'Description' => 1);
24
		$results = $es->search('New Zealind', $fields, true);
25
		$this->assertEquals(100, $results->getTotalItems());
26
		$this->assertEquals('New Zealand', $es->getSuggestedQuery());
27
	}
28
29
30
	public function testResultsForEmptySearch() {
31
		$es = new ElasticSearcher();
32
33
		$es->hideResultsForEmptySearch();
34
		$this->assertFalse($es->getShowResultsForEmptySearch());
35
36
		$es->showResultsForEmptySearch();
37
		$this->assertTrue($es->getShowResultsForEmptySearch());
38
	}
39
40
41
	public function testMoreLikeThisSinglePhoto() {
42
		$fp = $this->objFromFixture('FlickrPhotoTO', 'photo0076');
43
		$es = new ElasticSearcher();
44
		$locale = \i18n::default_locale();
45
		$es->setLocale($locale);
46
		$es->setClasses('FlickrPhotoTO');
47
48
		$fields = array('Description.standard' => 1, 'Title.standard' => 1);
49
		$results = $es->moreLikeThis($fp, $fields, true);
0 ignored issues
show
Bug introduced by
It seems like $fp defined by $this->objFromFixture('F...rPhotoTO', 'photo0076') on line 42 can be null; however, SilverStripe\Elastica\El...earcher::moreLikeThis() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
50
51
		$terms = $results->getList()->MoreLikeThisTerms;
0 ignored issues
show
Bug introduced by
Accessing MoreLikeThisTerms on the interface SS_List suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
52
53
		$fieldNamesReturned = array_keys($terms);
54
		$fieldNames = array_keys($fields);
55
		sort($fieldNames);
56
		sort($fieldNamesReturned);
57
58
		$this->assertEquals($fieldNames, $fieldNamesReturned);
59
60
		//FIXME - this seems anomolyous, check in more detail
61
		$expected = array('texas');
62
		$this->assertEquals($expected, $terms['Title.standard']);
63
64
		$expected = array('collection', 'company', 'degolyer', 'everett', 'file', 'high',
65
			'information', 'new', 'orleans', 'pacific', 'photographs', 'railroad', 'resolution',
66
			'see', 'southern', 'texas', 'view');
67
68
69
70
		$actual = $terms['Description.standard'];
71
		sort($expected);
72
		sort($actual);
73
74
75
		$this->assertEquals($expected, $actual);
76
	}
77
78
79
80
	public function testSimilarNoWeighting() {
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
81
		$fp = $this->objFromFixture('FlickrPhotoTO', 'photo0076');
82
		$es = new ElasticSearcher();
83
		$es->setClasses('FlickrPhotoTO');
84
		$fields = array('Title.standard', 'Description.standard');
85
		try {
86
			$paginated = $es->moreLikeThis($fp, $fields, true);
0 ignored issues
show
Unused Code introduced by
$paginated is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Bug introduced by
It seems like $fp defined by $this->objFromFixture('F...rPhotoTO', 'photo0076') on line 81 can be null; however, SilverStripe\Elastica\El...earcher::moreLikeThis() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
87
			$this->fail('Query has no weight and thus should have failed');
88
		} catch (InvalidArgumentException $e) {
89
			$this->assertEquals('Fields must be of the form fieldname => weight', $e->getMessage());
90
		}
91
	}
92
93
94
	public function testSimilarWeightingNotNumeric() {
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
95
		$fp = $this->objFromFixture('FlickrPhotoTO', 'photo0076');
96
		$es = new ElasticSearcher();
97
		$es->setClasses('FlickrPhotoTO');
98
		$fields = array('Title.standard' => 4, 'Description.standard' => 'not numeric');
99
		try {
100
			$paginated = $es->moreLikeThis($fp, $fields, true);
0 ignored issues
show
Unused Code introduced by
$paginated is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Bug introduced by
It seems like $fp defined by $this->objFromFixture('F...rPhotoTO', 'photo0076') on line 95 can be null; however, SilverStripe\Elastica\El...earcher::moreLikeThis() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
101
			$this->fail('Query has non numeric weight and thus should have failed');
102
		} catch (InvalidArgumentException $e) {
103
			$this->assertEquals('Fields must be of the form fieldname => weight', $e->getMessage());
104
		}
105
	}
106
107
108
	public function testSimilarToNonSearchable() {
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
109
		$m = Member::get()->first(); // this is not by default Searchable
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $m. Configured minimum length is 2.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
110
		$es = new ElasticSearcher();
111
		$es->setClasses('FlickrPhotoTO');
112
		$fields = array('Title.standard' => 4, 'Description.standard' => 2);
113
		try {
114
			$paginated = $es->moreLikeThis($m, $fields, true);
0 ignored issues
show
Unused Code introduced by
$paginated is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Bug introduced by
It seems like $m defined by \Member::get()->first() on line 109 can be null; however, SilverStripe\Elastica\El...earcher::moreLikeThis() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
115
			$this->fail('Querying for a non searchable object, thus should have failed');
116
		} catch (InvalidArgumentException $e) {
117
			$this->assertEquals('Objects of class Member are not searchable', $e->getMessage());
118
		}
119
	}
120
121
	public function testSimilarGood() {
122
		$fp = $this->objFromFixture('FlickrPhotoTO', 'photo0076');
123
		$es = new ElasticSearcher();
124
		$es->setClasses('FlickrPhotoTO');
125
		$fields = array('Title.standard' => 1, 'Description.standard' => 1);
126
		$paginated = $es->moreLikeThis($fp, $fields, true);
0 ignored issues
show
Bug introduced by
It seems like $fp defined by $this->objFromFixture('F...rPhotoTO', 'photo0076') on line 122 can be null; however, SilverStripe\Elastica\El...earcher::moreLikeThis() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
127
128
		$results = $paginated->getList()->toArray();
129
130
		// FIXME - this test appears fragile due to sharding issues with more like this
131
		$ctr = 0;
132
		if ($ctr < 9) {
133
			$this->assertStringStartsWith(
0 ignored issues
show
Bug introduced by
The method assertStringStartsWith() does not seem to exist on object<ElasticSearcherUnitTest>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
134
				'[Texas and New Orleans, Southern Pacific',
135
				$results[$ctr]->Title
136
			);
137
			$ctr++;
138
		}
139
	}
140
141
142
	// if this is not set to unbounded, zero, a conditional is triggered to add max doc freq to the request
143
	public function testSimilarChangeMaxDocFreq() {
144
		$fp = $this->objFromFixture('FlickrPhotoTO', 'photo0076');
145
		$es = new ElasticSearcher();
146
		$es->setMaxDocFreq(4);
147
		$es->setClasses('FlickrPhotoTO');
148
		$fields = array('Title.standard' => 1, 'Description.standard' => 1);
149
		$paginated = $es->moreLikeThis($fp, $fields, true);
0 ignored issues
show
Bug introduced by
It seems like $fp defined by $this->objFromFixture('F...rPhotoTO', 'photo0076') on line 144 can be null; however, SilverStripe\Elastica\El...earcher::moreLikeThis() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
150
		$results = $paginated->getList()->toArray();
151
152
		foreach ($results as $result) {
153
			error_log($result->Title);
154
		}
155
156
		$ctr = 0;
157
		foreach ($results as $result) {
158
			$ctr++;
159
			if ($ctr < 9) {
160
				$this->assertStringStartsWith(
0 ignored issues
show
Bug introduced by
The method assertStringStartsWith() does not seem to exist on object<ElasticSearcherUnitTest>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
161
					'[Texas and New Orleans, Southern Pacific',
162
					$result->Title
163
				);
164
			}
165
166
		}
167
		$this->assertEquals(14, $paginated->getTotalItems());
168
		$this->makeCode($paginated);
169
	}
170
171
172
	public function testSimilarNullFields() {
173
		$fp = $this->objFromFixture('FlickrPhotoTO', 'photo0076');
174
		$es = new ElasticSearcher();
175
		$es->setClasses('FlickrPhotoTO');
176
		try {
177
			$paginated = $es->moreLikeThis($fp, null, true);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Unused Code introduced by
$paginated is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Bug introduced by
It seems like $fp defined by $this->objFromFixture('F...rPhotoTO', 'photo0076') on line 173 can be null; however, SilverStripe\Elastica\El...earcher::moreLikeThis() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
178
		} catch (InvalidArgumentException $e) {
179
			$this->assertEquals('Fields cannot be null', $e->getMessage());
180
		}
181
	}
182
183
184
	public function testSimilarNullItem() {
185
		$es = new ElasticSearcher();
186
		$es->setClasses('FlickrPhotoTO');
187
		$fields = array('Title.standard' => 1, 'Description.standard' => 1);
188
189
		try {
190
			$paginated = $es->moreLikeThis(null, $fields, true);
0 ignored issues
show
Unused Code introduced by
$paginated is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
191
		} catch (InvalidArgumentException $e) {
192
			$this->assertEquals('A searchable item cannot be null', $e->getMessage());
193
		}
194
	}
195
196
197
198
	public function testHighlightsAsIfCMSEdited() {
199
		$es = new ElasticSearcher();
200
		$locale = \i18n::default_locale();
201
		$es->setLocale($locale);
202
		$es->setClasses('FlickrPhotoTO');
203
204
		$filter = array('ClazzName' => 'FlickrPhotoTO', 'Name' => 'Title');
205
		$titleField = SearchableField::get()->filter($filter)->first();
206
		$titleField->ShowHighlights = true;
207
		$titleField->write();
208
209
		$filter = array('ClazzName' => 'FlickrPhotoTO', 'Name' => 'Description');
210
		$nameField = SearchableField::get()->filter($filter)->first();
211
		$nameField->ShowHighlights = true;
212
		$nameField->write();
213
214
		$fields = array('Title' => 1, 'Description' => 1);
215
		$query = 'New Zealand';
216
		$paginated = $es->search($query, $fields);
217
		$ctr = 0;
218
219
		foreach ($paginated->getList()->toArray() as $result) {
220
			$ctr++;
221
			foreach ($result->SearchHighlightsByField->Description_standard->getIterator() as $highlight) {
222
				$snippet = $highlight->Snippet;
223
				$snippet = strtolower($snippet);
224
				$wordFound = false;
225
				$lcquery = explode(' ', strtolower($query));
226
				foreach ($lcquery as $part) {
227
					$bracketed = '<strong class="hl">' . $part . '</strong>';
228
					if (strpos($snippet, $bracketed) > 0) {
229
						$wordFound = true;
230
					}
231
				}
232
				$this->assertTrue($wordFound, 'Highlight should have been found');
233
			}
234
		}
235
	}
236
237
238
	public function testHighlightPassingFields() {
239
		$es = new ElasticSearcher();
240
		$es->setClasses('FlickrPhotoTO');
241
		$es->setHighlightedFields(array('Title', 'Title.standard', 'Description'));
242
243
		$fields = array('Title' => 1, 'Description' => 1);
244
		$query = 'New Zealand';
245
		$paginated = $es->search($query, $fields);
246
		$ctr = 0;
247
248
		foreach ($paginated->getList()->toArray() as $result) {
249
			$ctr++;
250
251
			foreach ($result->SearchHighlightsByField->Description->getIterator() as $highlight) {
252
				$snippet = $highlight->Snippet;
253
				$snippet = strtolower($snippet);
254
				$wordFound = false;
255
				$lcquery = explode(' ', strtolower($query));
256
				foreach ($lcquery as $part) {
257
					$bracketed = '<strong class="hl">' . $part . '</strong>';
258
					if (strpos($snippet, $bracketed) > 0) {
259
						$wordFound = true;
260
					}
261
				}
262
				$this->assertTrue($wordFound, 'Highlight should have been found');
263
			}
264
		}
265
	}
266
267
268
	public function testAutoCompleteGood() {
269
		$es = new ElasticSearcher();
270
		$es->setClasses('FlickrPhotoTO');
271
		$fields = array('Title' => 1, 'Description' => 1);
0 ignored issues
show
Unused Code introduced by
$fields is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
272
		$query = 'Lond';
273
		$results = $es->autocomplete_search($query, 'Title');
274
		$this->assertEquals(7, $results->getTotalItems());
275
		foreach ($results->toArray() as $result) {
276
			$this->assertTrue(strpos($result->Title, $query) > 0);
277
		}
278
	}
279
280
281 View Code Duplication
	private function makeCode($paginated) {
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
282
		$results = $paginated->getList()->toArray();
283
		$ctr = 0;
284
		echo '$result = $paginated->getList()->toArray();' . "\n";
285
		foreach ($results as $result) {
286
			echo '$this->assertEquals("' . $result->Title . '", $results[' . $ctr . ']->Title);' . "\n";
287
			$ctr++;
288
		}
289
	}
290
291
}
292