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

OpenFoodFacts   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 53.33%

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 4
dl 0
loc 62
ccs 16
cts 30
cp 0.5333
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A barcode() 0 14 4
A find() 0 27 5
A __call() 0 4 1
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