RegionBranchStoreUrlJson::findByRegion()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 9
rs 10
1
<?php
2
3
4
namespace talismanfr\rosselhozbank\stores;
5
6
7
use talismanfr\rosselhozbank\dto\RegionBranch;
8
use talismanfr\rosselhozbank\shared\UrlValue;
9
use talismanfr\rosselhozbank\stores\contracts\RegionBranchStore;
10
11
class RegionBranchStoreUrlJson implements RegionBranchStore
12
{
13
14
15
    private $url;
16
17
    /** @var RegionBranch[]|null */
18
    private $all=null;
19
20
    /**
21
     * RegionBranchStoreUrlJson constructor.
22
     * @param $url
23
     */
24
    public function __construct(?UrlValue $url=null)
25
    {
26
        $this->url = $url;
27
        if(empty($this->url)){
28
            $this->url=new UrlValue('https://www.rshb.ru/promo/smb/rko-partner/js/region.json');
29
        }
30
    }
31
32
33
    /**
34
     * @inheritDoc
35
     * @return RegionBranch[]
36
     */
37
    public function findAll(): array
38
    {
39
        if($this->all){
40
            return $this->all;
41
        }
42
43
44
        $resource=file_get_contents($this->url->__toString());
45
        if(empty($resource)){
46
            return [];
47
        }
48
49
        try{
50
            $resource=json_decode($resource,true);
51
            if(!$resource){
52
                return [];
53
            }
54
        }catch (\Exception $e){
55
            return [];
56
        }
57
        foreach ($resource as $item){
58
            $this->all[]=new RegionBranch(
59
                (int)$item['id'],
60
                $item['origName'],
61
                $item['newName']
62
            );
63
        }
64
        return $this->all;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->all could return the type null which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
65
    }
66
67
    /**
68
     * @inheritDoc
69
     */
70
    public function findByRegion(string $region): ?RegionBranch
71
    {
72
        foreach ($this->findAll() as $regionBranch){
73
            if($regionBranch->getRegionName()==$region){
74
                return $regionBranch;
75
            }
76
        }
77
78
        return null;
79
    }
80
81
    public function findById(int $id): ?RegionBranch
82
    {
83
        foreach ($this->findAll() as $regionBranch){
84
            if($regionBranch->getId()==$id){
85
                return $regionBranch;
86
            }
87
        }
88
89
        return null;
90
    }
91
}