Test Failed
Pull Request — master (#7)
by Eddie
15:37
created

OpenFoodFacts::barcode()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 6.9849

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 3
cts 7
cp 0.4286
rs 9.7998
c 0
b 0
f 0
cc 4
nc 6
nop 1
crap 6.9849
1
<?php
2
3
namespace OpenFoodFacts\Laravel;
4
5
use Illuminate\Contracts\Container\Container;
6
use Illuminate\Support\Collection;
7
use InvalidArgumentException;
8
use OpenFoodFacts\Exception\ProductNotFoundException;
9
10
class OpenFoodFacts extends OpenFoodFactsApiWrapper
11
{
12
    protected $max_results;
13
14 3
    public function __construct(Container $app)
15
    {
16 3
        parent::__construct([
17 3
            'geography' =>  $app['config']->get('openfoodfacts.geography'),
18 3
            'app' =>  $app['config']->get('app.name'),
19 3
        ], $app['cache.store']);
20
21 3
        $this->max_results = $app['config']->get('openfoodfacts.max_results', 1000);
22 3
    }
23
24 1
    public function barcode($value)
25
    {
26 1
        if (empty($value)) {
27 1
            throw new InvalidArgumentException("Argument must represent a barcode");
28
        }
29
30
        try {
31
            $doc = $this->api->getProduct($value);
32
33
            return empty($doc->code) ? [] : reset($doc);
34
        } catch (ProductNotFoundException $notFoundException) {
35
            return [];
36
        }
37
    }
38
39 2
    public function find($searchterm)
40
    {
41 2
        if (empty($searchterm)) {
42 1
            throw new InvalidArgumentException("Specify a search term to find data for matching products");
43
        }
44
45 1
        $products = Collection::make();
46 1
        $page = 0;
47
48
        do {
49 1
            $pageResults = $this->api->search($searchterm, ++$page, 100);
50
            $totalMatches = $pageResults->searchCount();
51
52
            if ($this->max_results > 0 && $totalMatches > $this->max_results) {
53
                throw new \Exception("ERROR: {$totalMatches} results found, while buffer limited to {$this->max_results}. Please narrow your search.");
54
            }
55
56
            $pages = (int)ceil($totalMatches / $pageResults->getPageSize());
57
58
            $products = $products->concat(iterator_to_array($pageResults));
59
60
        } while ($page < $pages);
61
62
        return $products->map(function ($product) {
63
            return reset($product);
64
        });
65
    }
66
67
    public function __call($method, $parameters)
68
    {
69
        return $this->api->$method(...$parameters);
70
    }
71
}
72