Completed
Push — dev2 ( 76a09a...1cd385 )
by Gordon
14:51
created

testSimilarChangeMaxDocFreq()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 16
rs 9.4286
cc 2
eloc 12
nc 2
nop 0
1
<?php
2
use SilverStripe\Elastica\ElasticSearcher;
3
use Elastica\Type;
4
use SilverStripe\Elastica\ReindexTask;
5
6
class TranslatableUnitTest extends ElasticsearchBaseTest {
7
	public static $fixture_file = 'elastica/tests/lotsOfPhotos.yml';
8
9
	public static $ignoreFixtureFileFor = array('testResultsForEmptySearch');
10
11
	public function setUpOnce() {
12
		//Add translatable if it exists
13
		if(class_exists('Translatable')) {
14
			SiteTree::add_extension('Translatable');
15
		}
16
		parent::setUpOnce();
17
	}
18
19
	public function testElasticSearchForm() {
20
		if(!class_exists('Translatable')) {
21
			$this->markTestSkipped('Translatable not installed');
1 ignored issue
show
Bug introduced by
The method markTestSkipped() does not seem to exist on object<TranslatableUnitTest>.

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...
22
		}
23
24
		$form = new \ElasticSearchForm(new \Controller(), 'TestForm');
25
		$fields = $form->Fields();
26
		$result = array();
27
		foreach($fields as $field) {
0 ignored issues
show
Bug introduced by
The expression $fields of type object<FieldList>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
28
			$result[$field->getName()] = $field->Value();
29
		}
30
31
		$expected = array('q' => '', 'searchlocale' => 'en_US');
32
		$this->assertEquals($expected, $result);
33
34
	}
35
36
37
	public function testHighlightPassingFields() {
38
		if(!class_exists('Translatable')) {
39
			$this->markTestSkipped('Translatable not installed');
1 ignored issue
show
Bug introduced by
The method markTestSkipped() does not seem to exist on object<TranslatableUnitTest>.

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...
40
		}
41
42
		$es = new ElasticSearcher();
43
		$es->setClasses('FlickrPhotoTO');
44
45
		$es->setHighlightedFields(array('Title', 'Title.standard', 'Description'));
46
47
		$fields = array('Title' => 1, 'Description' => 1);
48
		$query = 'New Zealand';
49
		$paginated = $es->search($query, $fields);
50
		$ctr = 0;
51
52
		foreach($paginated->getList()->toArray() as $result) {
53
			$ctr++;
54
55
			foreach($result->SearchHighlightsByField->Description->getIterator() as $highlight) {
56
				$snippet = $highlight->Snippet;
57
				$snippet = strtolower($snippet);
58
				$wordFound = false;
59
				$lcquery = explode(' ', strtolower($query));
60
				foreach($lcquery as $part) {
61
					$bracketed = '<strong class="hl">' . $part . '</strong>';
62
					if(strpos($snippet, $bracketed) > 0) {
63
						$wordFound = true;
64
					}
65
				}
66
				$this->assertTrue($wordFound, 'Highlight should have been found');
67
			}
68
		}
69
	}
70
71
72
	public function testAutoCompleteGood() {
73
		if(!class_exists('Translatable')) {
74
			$this->markTestSkipped('Translatable not installed');
1 ignored issue
show
Bug introduced by
The method markTestSkipped() does not seem to exist on object<TranslatableUnitTest>.

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...
75
		}
76
77
		$es = new ElasticSearcher();
78
		$es->setClasses('FlickrPhotoTO');
79
		$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...
80
		$query = 'Lond';
81
		$results = $es->autocomplete_search($query, 'Title');
82
		$this->assertEquals(7, $results->getTotalItems());
83
		foreach($results->toArray() as $result) {
84
			$this->assertTrue(strpos($result->Title, $query) > 0);
85
		}
86
	}
87
88
89
90
91
// ---------------------
92
93
	// FIXME - this test is shardy unfortunately
94
	public function testMoreLikeThisSinglePhoto() {
95
		if(!class_exists('Translatable')) {
96
			$this->markTestSkipped('Translatable not installed');
1 ignored issue
show
Bug introduced by
The method markTestSkipped() does not seem to exist on object<TranslatableUnitTest>.

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...
97
		}
98
99
		$fp = $this->objFromFixture('FlickrPhotoTO', 'photo0076');
100
		$es = new ElasticSearcher();
101
		$locale = \i18n::default_locale();
102
		$es->setLocale($locale);
103
		$es->setClasses('FlickrPhotoTO');
104
105
		$fields = array('Description.standard' => 1,'Title.standard' => 1);
106
		$results = $es->moreLikeThis($fp, $fields, true);
1 ignored issue
show
Bug introduced by
It seems like $fp defined by $this->objFromFixture('F...rPhotoTO', 'photo0076') on line 99 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...
107
108
		$terms = $results->getList()->MoreLikeThisTerms;
1 ignored issue
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...
109
110
		$fieldNamesReturned = array_keys($terms);
111
		$fieldNames = array_keys($fields);
112
		sort($fieldNames);
113
		sort($fieldNamesReturned);
114
115
		$this->assertEquals($fieldNames, $fieldNamesReturned);
116
117
		//FIXME - this seems anomolyous, check in more detail
118
		$expected = array('texas');
119
		$this->assertEquals($expected, $terms['Title.standard']);
120
121
		$expected = array('new', 'see', 'photographs', 'information', 'resolution', 'company', 'view',
0 ignored issues
show
Unused Code introduced by
$expected 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...
122
			'high', 'collection', 'pacific', 'orleans', 'degolyer', 'southern', 'everett',
123
			'railroad', 'texas');
124
125
		$expected = array('collection', 'company', 'degolyer', 'everett', 'file', 'high',
126
			'information', 'new', 'orleans', 'pacific', 'photographs', 'railroad', 'resolution',
127
			'see', 'southern', 'texas', 'view');
128
129
130
131
		$actual = $terms['Description.standard'];
132
		sort($expected);
133
		sort($actual);
134
135
136
		$this->assertEquals($expected, $actual);
137
	}
138
139
140
141
142
	/*
143
	test blank fields
144
	test fields with no weighting (ie not associative)
145
146
	 */
147
148
	public function testSimilarGood() {
149
		if(!class_exists('Translatable')) {
150
			$this->markTestSkipped('Translatable not installed');
1 ignored issue
show
Bug introduced by
The method markTestSkipped() does not seem to exist on object<TranslatableUnitTest>.

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...
151
		}
152
153
		$fp = $this->objFromFixture('FlickrPhotoTO', 'photo0076');
154
		$es = new ElasticSearcher();
155
		$es->setClasses('FlickrPhotoTO');
156
		$fields = array('Title.standard' => 1, 'Description.standard' => 1);
157
		$paginated = $es->moreLikeThis($fp, $fields, true);
1 ignored issue
show
Bug introduced by
It seems like $fp defined by $this->objFromFixture('F...rPhotoTO', 'photo0076') on line 153 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...
158
159
		$this->assertEquals(32, $paginated->getTotalItems());
160
		$results = $paginated->getList()->toArray();
161
		$this->assertEquals("[Texas and New Orleans, Southern Pacific Railroad Station, Stockdale, Texas]", $results[0]->Title);
162
		$this->assertEquals("[Texas and New Orleans, Southern Pacific Railroad Station, Taft, Texas]", $results[1]->Title);
163
		$this->assertEquals("[Texas and New Orleans, Southern Pacific Railroad Station, Sierra Blanca, Texas]", $results[2]->Title);
164
		$this->assertEquals("[Texas and New Orleans, Southern Pacific Freight Station, Waxahachie, Texas]", $results[3]->Title);
165
		$this->assertEquals("[Texas and New Orleans, Southern Pacific Passenger Station, Waxahachie, Texas]", $results[4]->Title);
166
		$this->assertEquals("[Texas and New Orleans, Southern Pacific, Tower No. 63, Mexia, Texas]", $results[5]->Title);
167
		$this->assertEquals("[Texas and New Orleans, Southern Pacific, Eakin Street Yard Office, Dallas, Texas]", $results[6]->Title);
168
		$this->assertEquals("[Texas and New Orleans, Southern Pacific Locomotive Scrap Line, Englewood Yards, Houston, Texas]", $results[7]->Title);
169
		$this->assertEquals("[Texas and New Orleans, Southern Pacific, Switchman's Tower, San Antonio, Texas]", $results[8]->Title);
170
		$this->assertEquals("Flash Light view in new Subterranean", $results[9]->Title);
171
	}
172
173
174
	/*
175
	FIXME - this is not working, not sure why.  Trying to complete coverage of ReindexTask
176
	 */
177
	public function testBulkIndexing() {
178
		if(!class_exists('Translatable')) {
179
			$this->markTestSkipped('Translatable not installed');
1 ignored issue
show
Bug introduced by
The method markTestSkipped() does not seem to exist on object<TranslatableUnitTest>.

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...
180
		}
181
182
		//Reset the index, so that nothing has been indexed
183
		$this->service->reset();
184
185
		//Number of requests indexing wise made to Elasticsearch server
186
		$reqs = $this->service->getIndexingRequestCtr();
187
188
		$task = new ReindexTask($this->service);
189
190
		// null request is fine as no parameters used
191
		$task->run(null);
192
193
		//Check that the number of indexing requests has increased by 2
194
		$deltaReqs = $this->service->getIndexingRequestCtr() - $reqs;
195
		//One call is made for each of Page and FlickrPhotoTO
196
		$this->assertEquals(2, $deltaReqs);
197
198
		// default installed pages plus 100 FlickrPhotoTOs
199
		$this->checkNumberOfIndexedDocuments(103);
200
	}
201
202
203
	// if this is not set to unbounded, zero, a conditional is triggered to add max doc freq to the request
204
	public function testSimilarChangeMaxDocFreq() {
205
		if(!class_exists('Translatable')) {
206
			$this->markTestSkipped('Translatable not installed');
1 ignored issue
show
Bug introduced by
The method markTestSkipped() does not seem to exist on object<TranslatableUnitTest>.

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...
207
		}
208
209
		$fp = $this->objFromFixture('FlickrPhotoTO', 'photo0076');
210
		$es = new ElasticSearcher();
211
		$es->setMaxDocFreq(4);
212
		$es->setClasses('FlickrPhotoTO');
213
		$fields = array('Title.standard' => 1, 'Description.standard' => 1);
214
		$paginated = $es->moreLikeThis($fp, $fields, true);
1 ignored issue
show
Bug introduced by
It seems like $fp defined by $this->objFromFixture('F...rPhotoTO', 'photo0076') on line 209 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...
215
216
		$this->assertEquals(14, $paginated->getTotalItems());
217
		$results = $paginated->getList()->toArray();
0 ignored issues
show
Unused Code introduced by
$results 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...
218
		$this->makeCode($paginated);
219
	}
220
221
222
	public function testSimilarNullFields() {
223
		if(!class_exists('Translatable')) {
224
			$this->markTestSkipped('Translatable not installed');
1 ignored issue
show
Bug introduced by
The method markTestSkipped() does not seem to exist on object<TranslatableUnitTest>.

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...
225
		}
226
227
		$fp = $this->objFromFixture('FlickrPhotoTO', 'photo0076');
228
		$es = new ElasticSearcher();
229
		$es->setClasses('FlickrPhotoTO');
230
		try {
231
			$paginated = $es->moreLikeThis($fp, null, true);
1 ignored issue
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 227 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...
232
		} catch (InvalidArgumentException $e) {
233
			$this->assertEquals('Fields cannot be null', $e->getMessage());
234
		}
235
	}
236
237
238
	public function testSimilarNullItem() {
239
		if(!class_exists('Translatable')) {
240
			$this->markTestSkipped('Translatable not installed');
1 ignored issue
show
Bug introduced by
The method markTestSkipped() does not seem to exist on object<TranslatableUnitTest>.

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...
241
		}
242
243
		$es = new ElasticSearcher();
244
		$es->setClasses('FlickrPhotoTO');
245
		$fields = array('Title.standard' => 1, 'Description.standard' => 1);
246
247
		try {
248
			$paginated = $es->moreLikeThis(null, $fields, true);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a object<DataObject>.

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...
249
		} catch (InvalidArgumentException $e) {
250
			$this->assertEquals('A searchable item cannot be null', $e->getMessage());
251
		}
252
	}
253
254 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...
255
		$results = $paginated->getList()->toArray();
256
		$ctr = 0;
257
		echo '$result = $paginated->getList()->toArray();' . "\n";
258
		foreach($results as $result) {
259
			echo '$this->assertEquals("' . $result->Title . '", $results[' . $ctr . ']->Title);' . "\n";
260
			$ctr++;
261
		}
262
	}
263
264
}
265