Completed
Push — dev2 ( 26ca88...f79151 )
by Gordon
03:18
created

TranslatableUnitTest::testSimilarGood()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 26
Code Lines 22

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 26
rs 8.8571
cc 3
eloc 22
nc 4
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
			echo $field->getName();
29
			$result[$field->getName()] = $field->Value();
30
		}
31
32
		$expected = array('q' => '', 'searchlocale' => 'en_US');
33
		$this->assertEquals($expected, $result);
34
35
	}
36
37
38
	public function testHighlightPassingFields() {
39
		if (!class_exists('Translatable')) {
40
			$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...
41
		}
42
43
		$es = new ElasticSearcher();
44
		$es->setClasses('FlickrPhotoTO');
45
46
		$es->setHighlightedFields(array('Title', 'Title.standard', 'Description'));
47
48
		$fields = array('Title' => 1, 'Description' => 1);
49
		$query = 'New Zealand';
50
		$paginated = $es->search($query, $fields);
51
		$ctr = 0;
52
53
		foreach ($paginated->getList()->toArray() as $result) {
54
			$ctr++;
55
56
			foreach ($result->SearchHighlightsByField->Description->getIterator() as $highlight) {
57
				$snippet = $highlight->Snippet;
58
				$snippet = strtolower($snippet);
59
				$wordFound = false;
60
				$lcquery = explode(' ', strtolower($query));
61
				foreach ($lcquery as $part) {
62
					$bracketed = '<strong class="hl">'.$part.'</strong>';
63
					if (strpos($snippet, $bracketed) > 0) {
64
						$wordFound = true;
65
					}
66
				}
67
				$this->assertTrue($wordFound,'Highlight should have been found');
68
			}
69
		}
70
	}
71
72
73
	public function testAutoCompleteGood() {
74
		if (!class_exists('Translatable')) {
75
			$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...
76
		}
77
78
		$es = new ElasticSearcher();
79
		$es->setClasses('FlickrPhotoTO');
80
		$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...
81
		$query = 'Lond';
82
		$results = $es->autocomplete_search($query, 'Title');
83
		$this->assertEquals(7, $results->getTotalItems());
84
		foreach ($results->toArray() as $result) {
85
			$this->assertTrue(strpos($result->Title, $query) > 0);
86
		}
87
	}
88
89
90
91
92
// ---------------------
93
94
	// FIXME - this test is shardy unfortunately
95
	public function testMoreLikeThisSinglePhoto() {
96
		if (!class_exists('Translatable')) {
97
			$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...
98
		}
99
100
		$fp = $this->objFromFixture('FlickrPhotoTO', 'photo0076');
101
102
		echo "FP: Original title: {$fp->Title}\n";
103
		$es = new ElasticSearcher();
104
		$locale = \i18n::default_locale();
105
		$es->setLocale($locale);
106
		$es->setClasses('FlickrPhotoTO');
107
108
		$fields = array('Description.standard' => 1,'Title.standard' => 1);
109
		$results = $es->moreLikeThis($fp, $fields, true);
110
111
		echo "RESULTS:\n";
112
		foreach ($results as $result) {
113
			echo "-\t{$result->Title}\n";
114
		}
115
116
		$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...
117
118
		$fieldNamesReturned = array_keys($terms);
119
		$fieldNames = array_keys($fields);
120
		sort($fieldNames);
121
		sort($fieldNamesReturned);
122
123
		$this->assertEquals($fieldNames, $fieldNamesReturned);
124
125
		//FIXME - this seems anomolyous, check in more detail
126
		$expected = array('texas');
127
		$this->assertEquals($expected, $terms['Title.standard']);
128
129
		$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...
130
			'high', 'collection', 'pacific', 'orleans', 'degolyer', 'southern', 'everett',
131
			'railroad', 'texas');
132
133
		$expected = array('collection', 'company', 'degolyer', 'everett', 'file', 'high',
134
			'information', 'new', 'orleans', 'pacific', 'photographs', 'railroad', 'resolution',
135
			'see', 'southern', 'texas', 'view');
136
137
138
139
		$actual = $terms['Description.standard'];
140
		sort($expected);
141
		sort($actual);
142
143
144
		$this->assertEquals($expected, $actual);
145
	}
146
147
148
149
150
	/*
151
	test blank fields
152
	test fields with no weighting (ie not associative)
153
154
	 */
155
156
	public function testSimilarGood() {
157
		if (!class_exists('Translatable')) {
158
			$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...
159
		}
160
161
		$fp = $this->objFromFixture('FlickrPhotoTO', 'photo0076');
162
		$es = new ElasticSearcher();
163
		$es->setClasses('FlickrPhotoTO');
164
		$fields = array('Title.standard' => 1, 'Description.standard' => 1);
165
		$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 161 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...
166
		foreach ($paginated->getList() as $result) {
167
			echo $result->ID. ' : '.$result->Title."\n";
168
		}
169
		$this->assertEquals(32, $paginated->getTotalItems());
170
		$results = $paginated->getList()->toArray();
171
		$this->assertEquals("[Texas and New Orleans, Southern Pacific Railroad Station, Stockdale, Texas]", $results[0]->Title);
172
		$this->assertEquals("[Texas and New Orleans, Southern Pacific Railroad Station, Taft, Texas]", $results[1]->Title);
173
		$this->assertEquals("[Texas and New Orleans, Southern Pacific Railroad Station, Sierra Blanca, Texas]", $results[2]->Title);
174
		$this->assertEquals("[Texas and New Orleans, Southern Pacific Freight Station, Waxahachie, Texas]", $results[3]->Title);
175
		$this->assertEquals("[Texas and New Orleans, Southern Pacific Passenger Station, Waxahachie, Texas]", $results[4]->Title);
176
		$this->assertEquals("[Texas and New Orleans, Southern Pacific, Tower No. 63, Mexia, Texas]", $results[5]->Title);
177
		$this->assertEquals("[Texas and New Orleans, Southern Pacific, Eakin Street Yard Office, Dallas, Texas]", $results[6]->Title);
178
		$this->assertEquals("[Texas and New Orleans, Southern Pacific Locomotive Scrap Line, Englewood Yards, Houston, Texas]", $results[7]->Title);
179
		$this->assertEquals("[Texas and New Orleans, Southern Pacific, Switchman's Tower, San Antonio, Texas]", $results[8]->Title);
180
		$this->assertEquals("Flash Light view in new Subterranean", $results[9]->Title);
181
	}
182
183
184
	/*
185
	FIXME - this is not working, not sure why.  Trying to complete coverage of ReindexTask
186
	 */
187
	public function testBulkIndexing() {
188
		if (!class_exists('Translatable')) {
189
			$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...
190
		}
191
192
		//Reset the index, so that nothing has been indexed
193
		$this->service->reset();
194
195
		//Number of requests indexing wise made to Elasticsearch server
196
		$reqs = $this->service->getIndexingRequestCtr();
197
198
		$task = new ReindexTask($this->service);
199
200
		// null request is fine as no parameters used
201
		$task->run(null);
202
203
		//Check that the number of indexing requests has increased by 2
204
		$deltaReqs = $this->service->getIndexingRequestCtr() - $reqs;
205
		//One call is made for each of Page and FlickrPhotoTO
206
		$this->assertEquals(2,$deltaReqs);
207
208
		// default installed pages plus 100 FlickrPhotoTOs
209
		$this->checkNumberOfIndexedDocuments(103);
210
	}
211
212
213
	// if this is not set to unbounded, zero, a conditional is triggered to add max doc freq to the request
214
	public function testSimilarChangeMaxDocFreq() {
215
		if (!class_exists('Translatable')) {
216
			$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...
217
		}
218
219
		$fp = $this->objFromFixture('FlickrPhotoTO', 'photo0076');
220
		$es = new ElasticSearcher();
221
		$es->setMaxDocFreq(4);
222
		$es->setClasses('FlickrPhotoTO');
223
		$fields = array('Title.standard' => 1, 'Description.standard' => 1);
224
		$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 219 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...
225
		foreach ($paginated->getList() as $result) {
226
			echo $result->ID. ' : '.$result->Title."\n";
227
		}
228
		$this->assertEquals(14, $paginated->getTotalItems());
229
		$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...
230
		$this->makeCode($paginated);
231
	}
232
233
234
	public function testSimilarNullFields() {
235
		if (!class_exists('Translatable')) {
236
			$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...
237
		}
238
239
		$fp = $this->objFromFixture('FlickrPhotoTO', 'photo0076');
240
		$es = new ElasticSearcher();
241
		$es->setClasses('FlickrPhotoTO');
242
		try {
243
			$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 239 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...
244
		} catch (InvalidArgumentException $e) {
245
			$this->assertEquals('Fields cannot be null', $e->getMessage());
246
		}
247
	}
248
249
250
	public function testSimilarNullItem() {
251
		if (!class_exists('Translatable')) {
252
			$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...
253
		}
254
255
		$es = new ElasticSearcher();
256
		$es->setClasses('FlickrPhotoTO');
257
		$fields = array('Title.standard' => 1, 'Description.standard' => 1);
258
259
		try {
260
			$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...
261
		} catch (InvalidArgumentException $e) {
262
			$this->assertEquals('A searchable item cannot be null', $e->getMessage());
263
		}
264
	}
265
266 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...
267
		$results = $paginated->getList()->toArray();
268
		$ctr = 0;
269
		echo '$result = $paginated->getList()->toArray();'."\n";
270
		foreach ($results as $result) {
271
			echo '$this->assertEquals("'.$result->Title.'", $results['.$ctr.']->Title);'."\n";
272
			$ctr++;
273
		}
274
	}
275
276
}
277