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