Completed
Push — develop ( 1b2298...3276b8 )
by Ben
01:52
created

Query::convertBiasing()   B

Complexity

Conditions 6
Paths 18

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
c 2
b 0
f 2
dl 0
loc 26
rs 8.439
cc 6
eloc 15
nc 18
nop 1
1
<?php
2
3
namespace GroupByInc\API;
4
5
use GroupByInc\API\Model\Bias as MBias;
6
use GroupByInc\API\Model\Biasing as MBiasing;
7
use GroupByInc\API\Model\CustomUrlParam;
8
use GroupByInc\API\Model\MatchStrategy as MMatchStrategy;
9
use GroupByInc\API\Model\Navigation;
10
use GroupByInc\API\Model\PartialMatchRule as MPartialMatchRule;
11
use GroupByInc\API\Model\Refinement;
12
use GroupByInc\API\Model\Refinement\Type;
13
use GroupByInc\API\Model\RefinementRange;
14
use GroupByInc\API\Model\RefinementValue;
15
use GroupByInc\API\Model\Sort as MSort;
16
use GroupByInc\API\Request\Bias;
17
use GroupByInc\API\Request\Biasing;
18
use GroupByInc\API\Request\MatchStrategy as RMatchStrategy;
19
use GroupByInc\API\Request\PartialMatchRule as RPartialMatchRule;
20
use GroupByInc\API\Request\RefinementsRequest;
21
use GroupByInc\API\Request\Request;
22
use GroupByInc\API\Request\RestrictNavigation;
23
use GroupByInc\API\Request\SelectedRefinement;
24
use GroupByInc\API\Request\SelectedRefinementRange;
25
use GroupByInc\API\Request\SelectedRefinementValue;
26
use GroupByInc\API\Request\Sort as RSort;
27
use GroupByInc\API\Util\SerializerFactory;
28
use GroupByInc\API\Util\StringBuilder;
29
use GroupByInc\API\Util\StringUtils;
30
use JMS\Serializer\Serializer;
31
use RuntimeException;
32
33
class Symbol
34
{
35
    const TILDE = "~";
36
    const DOT = ".";
37
    const DOUBLE_DOT = "..";
38
    const EQUAL = "=";
39
    const COLON = ":";
40
    const AMPERSAND = "&";
41
    const SLASH = "/";
42
}
43
44
class Query
45
{
46
    /** @var string */
47
    private $query;
48
    /** @var int */
49
    private $skip = 0;
50
    /** @var int */
51
    private $pageSize = 10;
52
    /** @var string */
53
    private $collection;
54
    /** @var string */
55
    private $area;
56
    /** @var string */
57
    private $biasingProfile;
58
    /** @var string */
59
    private $language;
60
    /** @var MSort[] */
61
    private $sort;
62
    /** @var CustomUrlParam[] */
63
    private $customUrlParams = array();
64
    /** @var Navigation[] */
65
    private $navigations = array();
66
    /** @var string[] */
67
    private $includedNavigations = array();
68
    /** @var string[] */
69
    private $excludedNavigations = array();
70
    /** @var string[] */
71
    private $fields = array();
72
    /** @var string[] */
73
    private $orFields = array();
74
    /** @var bool */
75
    private $pruneRefinements = true;
76
    /** @var bool */
77
    private $disableAutocorrection = false;
78
    /** @var bool */
79
    private $wildcardSearchEnabled = false;
80
    // Removed until CBOR support for serialization / de-serialization improves
81
//    /** @var bool */
82
//    private $returnBinary = false;
83
    /** @var RestrictNavigation */
84
    private $restrictNavigation;
85
    /** @var MBiasing */
86
    private $biasing;
87
88
    /** @var Serializer */
89
    private $serializer;
90
91
    const TILDE_REGEX = "/~((?=[\\w]*[=:]))/";
92
93
    /**
94
     * @param mixed $request
95
     *
96
     * @return string
97
     */
98
    private function requestToJson($request)
99
    {
100
        $jsonRequest = null;
101
        try {
102
            $jsonRequest = $this->serializer->serialize($request, 'json');
103
        } catch (RuntimeException $e) {
104
            throw new RuntimeException('Unable to serialize request ' . var_dump($request));
0 ignored issues
show
Security Debugging Code introduced by
var_dump($request); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
105
        }
106
107
        return $jsonRequest;
108
    }
109
110
    /**
111
     * @param string $clientKey Your client key.
112
     *
113
     * @return string JSON representation of request to Bridge.
114
     */
115
    public function getBridgeJson($clientKey)
116
    {
117
        $data = $this->populateRequest($clientKey);
118
        return $this->requestToJson($data);
119
    }
120
121
    /**
122
     * @param string $clientKey      Your client key.
123
     * @param string $navigationName Name of the navigation to get refinements for
124
     *
125
     * @return string JSON representation of request to Bridge.
126
     */
127
    public function getBridgeRefinementsJson($clientKey, $navigationName)
128
    {
129
        $data = new RefinementsRequest();
130
        $data->originalQuery = $this->populateRequest($clientKey);
131
        $data->navigationName = $navigationName;
132
        return $this->requestToJson($data);
133
    }
134
135
    /**
136
     * @param string $clientKey
137
     *
138
     * @return Request
139
     */
140
    private function populateRequest($clientKey)
141
    {
142
        $request = new Request();
143
        $request->clientKey = $clientKey;
144
        $request->area = $this->area;
145
        $request->collection = $this->collection;
146
        $request->query = $this->query;
147
        $request->fields = $this->fields;
148
        $request->orFields = $this->orFields;
149
        $request->language = $this->language;
150
        $request->biasingProfile = $this->biasingProfile;
151
        $request->pageSize = $this->pageSize;
152
        $request->skip = $this->skip;
153
        $request->customUrlParams = $this->customUrlParams;
154
        $request->refinements = $this->generateSelectedRefinements($this->navigations);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->generateSelectedR...nts($this->navigations) of type array<integer,object<Gro...\API\Model\Refinement>> is incompatible with the declared type array<integer,object<Gro...st\SelectedRefinement>> of property $refinements.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
155
        $request->restrictNavigation = $this->restrictNavigation;
156
157
        if (!empty($this->biasing)) {
158
            $request->biasing = self::convertBiasing($this->biasing);
159
        }
160
161
        if (!empty($this->includedNavigations)) {
162
            $request->includedNavigations = $this->includedNavigations;
163
        }
164
165
        if (!empty($this->excludedNavigations)) {
166
            $request->excludedNavigations = $this->excludedNavigations;
167
        }
168
169
        $pruneRefinements = $this->pruneRefinements;
170
        if (isset($pruneRefinements) && $pruneRefinements === false) {
171
            $request->pruneRefinements = false;
172
        }
173
174
        $disableAutocorrection = $this->disableAutocorrection;
175
        if (isset($disableAutocorrection) && $disableAutocorrection === true) {
176
            $request->disableAutocorrection = true;
177
        }
178
179
        $wildcardSearchEnabled = $this->wildcardSearchEnabled;
180
        if (isset($wildcardSearchEnabled) && $wildcardSearchEnabled === true) {
181
            $request->wildcardSearchEnabled = true;
182
        }
183
184
        if (!empty($this->sort)) {
185
            foreach ($this->sort as $s) {
186
                array_push($request->sort, $this->convertSort($s));
187
            }
188
        }
189
190
//        $returnBinary = $this->returnBinary;
191
//        if (isset($returnBinary) && $returnBinary === true) {
192
//            $request->returnBinary = true;
193
//        }
194
195
        return $request;
196
    }
197
198
    /**
199
     * @param Navigation[] $navigations
200
     *
201
     * @return Refinement[]
202
     */
203
    private function generateSelectedRefinements($navigations)
204
    {
205
        $refinements = [];
206
        foreach ($navigations as $key => $navigation) {
207
            foreach ($navigation->getRefinements() as $refinement) {
208
                switch ($refinement->getType()) {
209
                    case Type::Range: {
210
                        /** @var RefinementRange $rr */
211
                        $rr = $refinement;
212
                        $selectedRefinementRange = new SelectedRefinementRange();
213
                        $selectedRefinementRange
214
                            ->setNavigationName($navigation->getName())
215
                            ->setLow($rr->getLow())
216
                            ->setHigh($rr->getHigh())
217
                            ->setExclude($rr->isExclude());
218
219
                        array_push($refinements, $selectedRefinementRange);
220
                        break;
221
                    }
222
                    case Type::Value: {
223
                        /** @var RefinementValue $rv */
224
                        $rv = $refinement;
225
                        $selectedRefinementValue = new SelectedRefinementValue();
226
                        $selectedRefinementValue
227
                            ->setNavigationName($navigation->getName())
228
                            ->setValue($rv->getValue())
229
                            ->setExclude($rv->isExclude());
230
231
                        array_push($refinements, $selectedRefinementValue);
232
                        break;
233
                    }
234
                }
235
            }
236
        }
237
        return $refinements;
238
    }
239
240
    /**
241
     * @param string $clientKey Your client key.
242
     *
243
     * @return string JSON representation of request to Bridge.
244
     */
245
    public function getBridgeJsonRefinementSearch($clientKey)
246
    {
247
        $data = new Request();
248
        $data->clientKey = $clientKey;
249
        $data->collection = $this->collection;
250
        $data->area = $this->area;
251
        $data->refinementQuery = $this->query;
252
253
        $wildcardSearchEnabled = $this->wildcardSearchEnabled;
254
        if (isset($wildcardSearchEnabled) && $wildcardSearchEnabled === true) {
255
            $data->wildcardSearchEnabled = true;
256
        }
257
258
        return $this->requestToJson($data);
259
    }
260
261
    public function __construct()
262
    {
263
        $this->serializer = SerializerFactory::build();
264
    }
265
266
    /**
267
     * @return string The current search string.
268
     */
269
    public function getQuery()
270
    {
271
        return $this->query;
272
    }
273
274
    /**
275
     * @param string $query The search string.
276
     */
277
    public function setQuery($query)
278
    {
279
        $this->query = $query;
280
    }
281
282
    /**
283
     * @return string The data sub-collection.
284
     */
285
    public function getCollection()
286
    {
287
        return $this->collection;
288
    }
289
290
    /**
291
     * @param string $collection The string representation of a collection query.
292
     */
293
    public function setCollection($collection)
294
    {
295
        $this->collection = $collection;
296
    }
297
298
    /**
299
     * @return string The area name.
300
     */
301
    public function getArea()
302
    {
303
        return $this->area;
304
    }
305
306
    /**
307
     * @param string $area The area name.
308
     */
309
    public function setArea($area)
310
    {
311
        $this->area = $area;
312
    }
313
314
    /**
315
     * @return string[] A list of metadata fields that will be returned by the search engine.
316
     */
317
    public function getFields()
318
    {
319
        return $this->fields;
320
    }
321
322
    /**
323
     * @return string[] A list of the fields that the search service will treat as OR'able.
324
     */
325
    public function getOrFields()
326
    {
327
        return $this->orFields;
328
    }
329
330
    /**
331
     * @param string[] $fields A list of case-sensitive names of the attributes to return.
332
     */
333
    public function addFields($fields)
334
    {
335
        $this->fields = array_merge($this->fields, $fields);
336
    }
337
338
    /**
339
     * @return string[] A list of which navigations to return from the bridge.
340
     */
341
    public function getIncludedNavigations()
342
    {
343
        return $this->includedNavigations;
344
    }
345
346
    /**
347
     * @param string[] $navigations A list of which navigations to return from the bridge.
348
     */
349
    public function addIncludedNavigations($navigations)
350
    {
351
        $this->includedNavigations = array_merge($this->includedNavigations, $navigations);
352
    }
353
354
    /**
355
     * @return string[] A list of which navigations to not return from the bridge.
356
     */
357
    public function getExcludedNavigations()
358
    {
359
        return $this->excludedNavigations;
360
    }
361
362
    /**
363
     * @param string[] $navigations A list of which navigations to not return from the bridge.
364
     */
365
    public function addExcludedNavigations($navigations)
366
    {
367
        $this->excludedNavigations = array_merge($this->excludedNavigations, $navigations);
368
    }
369
370
    /**
371
     * @return Navigation[]
372
     */
373
    public function &getNavigations()
374
    {
375
        return $this->navigations;
376
    }
377
378
    /**
379
     * @param Navigation[] $navigations
380
     */
381
    public function setNavigations($navigations)
382
    {
383
        $this->navigations = $navigations;
384
    }
385
386
    /**
387
     * @param string $name The case-sensitive name of the attribute to return.
388
     */
389
    public function addField($name)
390
    {
391
        array_push($this->fields, $name);
392
    }
393
394
    /**
395
     * @param string $name Field that should be treated as OR.
396
     */
397
    public function addOrField($name)
398
    {
399
        array_push($this->orFields, $name);
400
    }
401
402
    /**
403
     * @param string[] $fields A list of fields that should be treated as OR.
404
     */
405
    public function addOrFields($fields)
406
    {
407
        $this->orFields = array_merge($this->orFields, $fields);
408
    }
409
410
    /**
411
     * @param string $name  The parameter name.
412
     * @param string $value The parameter value.
413
     */
414
    public function addCustomUrlParamByName($name, $value)
415
    {
416
        $param = new CustomUrlParam();
417
        $this->addCustomUrlParam($param->setKey($name)->setValue($value));
418
    }
419
420
    /**
421
     * @param CustomUrlParam $param Set an additional parameter that can be used to trigger rules.
422
     */
423
    public function addCustomUrlParam($param)
424
    {
425
        array_push($this->customUrlParams, $param);
426
    }
427
428
    public function splitRefinements($refinementString)
429
    {
430
        if (StringUtils::isNotBlank($refinementString)) {
431
            return preg_split(self::TILDE_REGEX, $refinementString, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
432
        }
433
        return [];
434
    }
435
436
    /**
437
     * @param string $refinementString A tilde separated list of refinements.
438
     */
439
    public function addRefinementsByString($refinementString)
440
    {
441
        if ($refinementString == null) {
442
            return;
443
        }
444
445
        $refinementStrings = self::splitRefinements($refinementString);
446
        foreach ($refinementStrings as $refinementString) {
447
            if (empty($refinementString) || "=" == $refinementString) {
448
                continue;
449
            }
450
            $colon = strpos($refinementString, Symbol::COLON);
451
            $equals = strpos($refinementString, Symbol::EQUAL);
452
            //when === false, it means it did not find the substring in the string
453
            $isRange = !($colon === false) && ($equals === false);
454
455
            $refinement = null;
0 ignored issues
show
Unused Code introduced by
$refinement 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...
456
            if ($isRange) {
457
                $nameValue = explode(Symbol::COLON, $refinementString, 2);
458
                $refinement = new RefinementRange();
459
                if (StringUtils::endsWith($nameValue[1], Symbol::DOUBLE_DOT)) {
460
                    $value = explode(Symbol::DOUBLE_DOT, $nameValue[1]);
461
                    $refinement->setLow($value[0]);
462
                    $refinement->setHigh("");
463
                } else if (StringUtils::startsWith($nameValue[1], Symbol::DOUBLE_DOT)) {
464
                    $refinement->setLow("");
465
                    $value = explode(Symbol::DOUBLE_DOT, $nameValue[1]);
466
                    $refinement->setHigh($value[1]);
467
                } else {
468
                    $lowHigh = explode(Symbol::DOUBLE_DOT, $nameValue[1]);
469
                    $refinement->setLow($lowHigh[0]);
470
                    $refinement->setHigh($lowHigh[1]);
471
                }
472
            } else {
473
                $nameValue = explode(Symbol::EQUAL, $refinementString, 2);
474
                $refinement = new RefinementValue();
475
                $refinement->setValue($nameValue[1]);
476
            }
477
            if (!empty($nameValue[0])) {
478
                $this->addRefinement($nameValue[0], $refinement);
479
            }
480
        }
481
    }
482
483
    /**
484
     * @param string     $navigationName The name of the Navigation.
485
     * @param Refinement $refinement     A RefinementRange or RefinementValue object.
486
     */
487
    public function addRefinement($navigationName, $refinement)
488
    {
489
        $navigation = null;
0 ignored issues
show
Unused Code introduced by
$navigation 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...
490
        if (array_key_exists($navigationName, $this->navigations)) {
491
            $navigation = $this->navigations[$navigationName];
492
        } else {
493
            $navigation = new Navigation();
494
            $navigation->setName($navigationName)->setRange($refinement instanceof SelectedRefinementRange);
495
            $this->navigations[$navigationName] = $navigation;
496
        }
497
        $refinements = $navigation->getRefinements();
498
        array_push($refinements, $refinement);
499
        $navigation->setRefinements($refinements);
500
    }
501
502
    /**
503
     * @param string $navigationName The name of the refinement.
504
     * @param mixed  $low            The low value.
505
     * @param mixed  $high           The high value.
506
     * @param bool   $exclude        True if the results should exclude this range refinement, false otherwise.
507
     */
508
    public function addRangeRefinement($navigationName, $low, $high, $exclude = false)
509
    {
510
        $refinement = new RefinementRange();
511
        $this->addRefinement($navigationName, $refinement->setLow($low)->setHigh($high)->setExclude($exclude));
512
    }
513
514
    /**
515
     * @param string $navigationName The name of the refinement.
516
     * @param mixed  $value          The refinement value.
517
     * @param bool   $exclude        True if the results should exclude this value refinement, false otherwise.
518
     */
519
    public function addValueRefinement($navigationName, $value, $exclude = false)
520
    {
521
        $refinement = new RefinementValue();;
522
        $this->addRefinement($navigationName, $refinement->setValue($value)->setExclude($exclude));
523
    }
524
525
    /**
526
     * @return bool Are refinements with zero counts being removed.
527
     */
528
    public function isPruneRefinements()
529
    {
530
        return $this->pruneRefinements;
531
    }
532
533
    /**
534
     * @param bool $pruneRefinements Specifies whether refinements should be pruned.
535
     */
536
    public function setPruneRefinements($pruneRefinements)
537
    {
538
        $this->pruneRefinements = $pruneRefinements;
539
    }
540
541
    /**
542
     * @return MSort[] The current list of sort parameters.
543
     */
544
    public function &getSort()
545
    {
546
        return $this->sort;
547
    }
548
549
    /**
550
     * @param MSort[] $sort Any number of sort criteria.
551
     */
552
    public function setSort($sort)
553
    {
554
        $this->sort = $sort;
555
    }
556
557
    /**
558
     * @return int The number of documents to skip.
559
     */
560
    public function getSkip()
561
    {
562
        return $this->skip;
563
    }
564
565
    /**
566
     * @param int $skip The number of documents to skip.
567
     */
568
    public function setSkip($skip)
569
    {
570
        $this->skip = $skip;
571
    }
572
573
    /**
574
     * @return CustomUrlParam[] A list of custom url params.
575
     */
576
    public function getCustomUrlParams()
577
    {
578
        return $this->customUrlParams;
579
    }
580
581
    /**
582
     * @param CustomUrlParam[] $customUrlParams Set the custom url params.
583
     */
584
    public function setCustomUrlParams($customUrlParams)
585
    {
586
        $this->customUrlParams = $customUrlParams;
587
    }
588
589
//    /**
590
//     * @return bool Is return JSON set to true.
591
//     */
592
//    public function isReturnBinary()
593
//    {
594
//        return $this->returnBinary;
595
//    }
596
//
597
//    /**
598
//     * @param bool $returnBinary Whether to tell the bridge to return binary data rather than JSON.
599
//     */
600
//    public function setReturnBinary($returnBinary)
601
//    {
602
//        $this->returnBinary = $returnBinary;
603
//    }
604
605
    /**
606
     * @return string The current language restrict value.
607
     */
608
    public function getLanguage()
609
    {
610
        return $this->language;
611
    }
612
613
    /**
614
     * @param string $language The value for language restrict.
615
     */
616
    public function setLanguage($language)
617
    {
618
        $this->language = $language;
619
    }
620
621
    /**
622
     * @return string The current biasing profile name.
623
     */
624
    public function getBiasingProfile()
625
    {
626
        return $this->biasingProfile;
627
    }
628
629
    /**
630
     * @param string $biasingProfile Override the biasing profile used for this query.
631
     */
632
    public function setBiasingProfile($biasingProfile)
633
    {
634
        $this->biasingProfile = $biasingProfile;
635
    }
636
637
    /**
638
     * @return int The current page size.
639
     */
640
    public function getPageSize()
641
    {
642
        return $this->pageSize;
643
    }
644
645
    /**
646
     * @param int $pageSize The number of records to return with the query.
647
     */
648
    public function setPageSize($pageSize)
649
    {
650
        $this->pageSize = $pageSize;
651
    }
652
653
    /**
654
     * @return boolean
655
     */
656
    public function isDisableAutocorrection()
657
    {
658
        return $this->disableAutocorrection;
659
    }
660
661
    /**
662
     * @param boolean $disableAutocorrection Specifies whether the auto-correction behavior should be disabled.
663
     *                                       By default, when no results are returned for the given query (and there is
664
     *                                       a did-you-mean available), the first did-you-mean is automatically queried
665
     *                                       instead.
666
     */
667
    public function setDisableAutocorrection($disableAutocorrection)
668
    {
669
        $this->disableAutocorrection = $disableAutocorrection;
670
    }
671
672
    /**
673
     * @return boolean
674
     */
675
    public function isWildcardSearchEnabled()
676
    {
677
        return $this->wildcardSearchEnabled;
678
    }
679
680
    /**
681
     * @param boolean $wildcardSearchEnabled Indicate if the *(star) character in the search string should be treated
682
     *                                       as a wildcard prefix search. For example, `sta*` will match `star` and
683
     *                                       `start`.
684
     */
685
    public function setWildcardSearchEnabled($wildcardSearchEnabled)
686
    {
687
        $this->wildcardSearchEnabled = $wildcardSearchEnabled;
688
    }
689
690
    /**
691
     * <b>Warning</b>  This will count as two queries against your search index.
692
     *
693
     * Typically, this feature is used when you have a large number of navigation items that will overwhelm the end
694
     * user. It works by using one of the existing navigation items to decide what the query is about and fires a second
695
     * query to restrict the navigation to the most relevant set of navigation items for this search term.
696
     *
697
     * For example, if you pass in a search of `paper` and a restrict navigation of `category:2`
698
     *
699
     * The bridge will find the category navigation refinements in the first query and fire a second query for the top 2
700
     * most populous categories.  Therefore, a search for something generic like "paper" will bring back top category
701
     * matches like copy paper (1,030), paper pads (567).  The bridge will fire off the second query with the search
702
     * term, plus an OR refinement with the most likely categories.  The navigation items in the first query are
703
     * entirely replaced with the navigation items in the second query, except for the navigation that was used for the
704
     * restriction so that users still have the ability to navigate by all category types.
705
     *
706
     * @param RestrictNavigation $restrictNavigation Restriction criteria
707
     */
708
    public function setRestrictNavigation($restrictNavigation)
709
    {
710
        $this->restrictNavigation = $restrictNavigation;
711
    }
712
713
    /** @return RestrictNavigation */
714
    public function getRestrictNavigation()
715
    {
716
        return $this->restrictNavigation;
717
    }
718
719
    /**
720
     * @return MBiasing
721
     */
722
    public function getBiasing()
723
    {
724
        return $this->biasing;
725
    }
726
727
    /**
728
     * Add a biasing profile, which is defined at query time.
729
     *
730
     * @param MBiasing $biasing
731
     */
732
    public function setBiasing($biasing)
733
    {
734
        $this->biasing = $biasing;
735
    }
736
737
    /**
738
     * @param string[] $bringToTop
739
     */
740
    public function setBringToTop($bringToTop) {
741
        if (empty($this->biasing)) {
742
            $this->biasing = new MBiasing();
743
        }
744
        $this->biasing->setBringToTop($bringToTop);
745
    }
746
747
    /**
748
     * @param boolean $augment
749
     */
750
    public function setBiasingAugment($augment) {
751
        if (empty($this->biasing)) {
752
            $this->biasing = new MBiasing();
753
        }
754
        $this->biasing->setAugmentbiases($augment);
755
    }
756
757
    /**
758
     * @param float $influence
759
     */
760
    public function setInfluence($influence) {
761
        if (empty($this->biasing)) {
762
            $this->biasing = new MBiasing();
763
        }
764
        $this->biasing->setInfluence($influence);
765
    }
766
767
    /**
768
     * @return string A string representation of all of the currently set refinements.
769
     */
770 View Code Duplication
    public function getRefinementString()
0 ignored issues
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...
771
    {
772
        if (!empty($this->navigations)) {
773
            $builder = new StringBuilder();
774
            foreach ($this->navigations as $n) {
775
                foreach ($n->getRefinements() as $r) {
776
                    $builder->append(Symbol::TILDE)->append($n->getName())->append($r->toTildeString());
777
                }
778
            }
779
            if ($builder->length() > 0) {
780
                return $builder->__toString();
781
            }
782
        }
783
        return null;
784
    }
785
786
    /**
787
     * @return string A string representation of all of the currently set custom url parameters.
788
     */
789 View Code Duplication
    public function getCustomUrlParamsString()
0 ignored issues
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...
790
    {
791
        if (!empty($this->customUrlParams)) {
792
            $builder = new StringBuilder();
793
            foreach ($this->customUrlParams as $c) {
794
                $builder->append(Symbol::TILDE)->append($c->getKey())->append(Symbol::EQUAL)->append($c->getValue());
795
            }
796
            if ($builder->length() > 0) {
797
                return $builder->__toString();
798
            }
799
        }
800
        return null;
801
    }
802
803
    /**
804
     * @param MSort $sort
805
     *
806
     * @return RSort
807
     */
808
    protected static function convertSort($sort)
809
    {
810
        /** @var RSort $convertedSort */
811
        $convertedSort = null;
812
        if (!empty($sort)) {
813
            $convertedSort = new RSort();
814
            $convertedSort->setField($sort->getField());
815
            switch ($sort->getOrder()) {
816
                case MSort\Order::Ascending:
817
                    $convertedSort->setOrder(RSort\Order::Ascending);
818
                    break;
819
                case MSort\Order::Descending:
820
                    $convertedSort->setOrder(RSort\Order::Descending);
821
                    break;
822
            }
823
        }
824
        return $convertedSort;
825
    }
826
827
    /**
828
     * @param MMatchStrategy $strategy
829
     *
830
     * @return RMatchStrategy
831
     */
832
    protected static function convertPartialMatchStrategy($strategy)
833
    {
834
        /** @var RMatchStrategy $convertedStrategy */
835
        $convertedStrategy = null;
836
        if (!empty($strategy)) {
837
            $rules = $strategy->getRules();
838
            if (!empty($rules)) {
839
                $convertedStrategy = new RMatchStrategy();
840
                /** @var MPartialMatchRule $r */
841
                foreach ($rules as $r) {
842
                    array_push($rules, Query::convertPartialMatchRule($r));
843
                }
844
                $strategy->setRules($rules);
845
            }
846
        }
847
        return $convertedStrategy;
848
    }
849
850
    /**
851
     * @param MPartialMatchRule $rule
852
     *
853
     * @return RPartialMatchRule
854
     */
855
    protected static function convertPartialMatchRule($rule)
856
    {
857
        /** @var RPartialMatchRule $convertedRule */
858
        $convertedRule = null;
859
        if (!empty($rule)) {
860
            $convertedRule = new RPartialMatchRule();
861
            $convertedRule->setTerms($rule->getTerms())
862
                ->setTermsGreaterThan($rule->getTermsGreaterThan())
863
                ->setMustMatch($rule->getMustMatch())
864
                ->setPercentage($rule->isPercentage());
865
        }
866
        return $convertedRule;
867
    }
868
869
    /**
870
     * @param MBias $bias
871
     *
872
     * @return Bias
873
     */
874
    protected static function convertBias($bias)
875
    {
876
        return (new MBias())->setName($bias->getName())->setContent($bias->getStrength())->setStrength($bias->getStrength());
877
    }
878
879
    /**
880
     * @param MBias[] $biases
881
     *
882
     * @return Bias[]
883
     */
884
    protected static function convertBiases($biases)
885
    {
886
        return array_map('self::convertBias', $biases);
887
    }
888
889
    /**
890
     * @param MBiasing $biasing
891
     *
892
     * @return Biasing
893
     */
894
    protected static function convertBiasing($biasing)
895
    {
896
        /** @var Biasing $convertedBiasing */
897
        $convertedBiasing = new Biasing();
898
899
        /** @var  $hasData */
900
        $hasData = false;
901
902
        if (!empty($biasing)) {
903
            // != must be used because empty() only accepts variables in PHP 5.4
904
            if($biasing->getBringToTop() != array()) {
905
                $convertedBiasing->setBringToTop($biasing->getBringToTop());
906
                $hasData = true;
907
            }
908
            if($biasing->getBiases() != array()) {
909
                $convertedBiasing->setBiases(self::convertBiases($biasing->getBiases()));
910
                $convertedBiasing->setAugmentBiases($convertedBiasing->isAugmentBiases());
911
                $hasData = true;
912
            }
913
            if($biasing->getInfluence() !== null) {
914
                $convertedBiasing->setInfluence($biasing->getInfluence());
915
                $hasData = true;
916
            }
917
        }
918
        return $hasData ? $convertedBiasing : null;
919
    }
920
921
}
922