Completed
Push — master ( 5cc00e...2c8285 )
by Andrii
05:27
created

SaleRepository::buildSellerCond()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
ccs 0
cts 7
cp 0
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * API for Billing
4
 *
5
 * @link      https://github.com/hiqdev/billing-hiapi
6
 * @package   billing-hiapi
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2017-2018, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\billing\hiapi\sale;
12
13
use hiqdev\php\billing\action\ActionInterface;
14
use hiqdev\php\billing\customer\CustomerInterface;
15
use hiqdev\php\billing\order\OrderInterface;
16
use hiqdev\php\billing\plan\PlanInterface;
17
use hiqdev\php\billing\sale\Sale;
18
use hiqdev\php\billing\sale\SaleInterface;
19
use hiqdev\php\billing\sale\SaleRepositoryInterface;
20
use hiqdev\yii\DataMapper\expressions\CallExpression;
21
use hiqdev\yii\DataMapper\expressions\HstoreExpression;
22
use hiqdev\yii\DataMapper\models\relations\Bucket;
23
use hiqdev\yii\DataMapper\query\Specification;
24
use hiqdev\yii\DataMapper\repositories\BaseRepository;
25
use Yii;
26
use yii\db\Query;
27
28
class SaleRepository extends BaseRepository implements SaleRepositoryInterface
29
{
30
    /** {@inheritdoc} */
31
    public $queryClass = SaleQuery::class;
32
33 View Code Duplication
    public function findId(SaleInterface $sale)
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...
34
    {
35
        if ($sale->hasId()) {
36
            return $sale->getId();
37
        }
38
        $hstore = new HstoreExpression(array_filter([
39
            'buyer'     => $sale->getCustomer()->getLogin(),
40
            'buyer_id'  => $sale->getCustomer()->getId(),
41
            'object_id' => $sale->getTarget()->getId(),
42
            'tariff_id' => $sale->getPlan()->getId(),
43
        ]));
44
        $call = new CallExpression('sale_id', [$hstore]);
45
        $command = (new Query())->select($call);
46
47
        return $command->scalar($this->db);
0 ignored issues
show
Bug introduced by
It seems like $this->db can also be of type object<hiqdev\yii\DataMa...ts\ConnectionInterface>; however, yii\db\Query::scalar() does only seem to accept object<yii\db\Connection>|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
48
    }
49
50
    /**
51
     * @param OrderInterface $order
52
     * @return Sale[]|SaleInterface[]
53
     */
54
    public function findByOrder(OrderInterface $order)
55
    {
56
        return array_map([$this, 'findByAction'], $order->getActions());
57
    }
58
59
    /**
60
     * @param ActionInterface $action
61
     * @return SaleInterface
62
     */
63
    public function findByAction(ActionInterface $action)
64
    {
65
        $client_id = $action->getCustomer()->getId();
66
        $type = $action->getTarget()->getType();
67
68
        if ($type === 'certificate') {
69
            //// XXX tmp crutch
70
            $class_id = new CallExpression('class_id', ['certificate']);
71
            $cond = empty($client_id)
72
                ? $this->buildSellerCond($action->getCustomer()->getSeller())
73
                : [
74
                    'target-id' => $class_id,
75
                    'customer-id' => $client_id,
76
                ];
77
        } elseif ($type === 'server') {
78
            $cond = [
79
                'target-id' => $action->getTarget()->getId(),
80
                'customer-id' => $client_id,
81
            ];
82
        } else {
83
            throw new \Exception('not implemented for: ' . $type);
84
        }
85
86
        $spec = Yii::createObject(Specification::class)
87
            /// XXX how to pass if we want with prices into joinPlans?
88
            ->with('plans')
89
            ->where($cond);
90
91
        return $this->findOne($spec);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression $this->findOne($spec); of type object|false adds false to the return on line 91 which is incompatible with the return type documented by hiqdev\billing\hiapi\sal...epository::findByAction of type hiqdev\php\billing\sale\SaleInterface. It seems like you forgot to handle an error condition.
Loading history...
92
    }
93
94
    protected function buildSellerCond(CustomerInterface $seller)
95
    {
96
        return [
97
            'customer-id'   => $seller->getId(),
98
            'seller-id'     => $seller->getId(),
99
        ];
100
    }
101
102
    protected function joinPlans(&$rows)
103
    {
104
        $bucket = Bucket::fromRows($rows, 'plan-id');
105
        $spec = (new Specification())
106
            ->with('prices')
107
            ->where(['id' => $bucket->getKeys()]);
108
        $raw_plans = $this->getRepository(PlanInterface::class)->queryAll($spec);
109
        /// TODO for SilverFire: try to do with bucket
110
        $plans = [];
111
        foreach ($raw_plans as $plan) {
112
            $plans[$plan['id']] = $plan;
113
        }
114
        foreach ($rows as &$sale) {
115
            $sale['plan'] = $plans[$sale['plan-id']];
116
        }
117
    }
118
119
    /**
120
     * @param SaleInterface $sale
121
     */
122 View Code Duplication
    public function save(SaleInterface $sale)
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...
123
    {
124
        $hstore = new HstoreExpression([
125
            'object_id'     => $sale->getTarget()->getId(),
126
            'contact_id'    => $sale->getCustomer()->getId(),
127
            'tariff_id'     => $sale->getPlan() ? $sale->getPlan()->getId() : null,
128
            'time'          => $sale->getTime()->format('c'),
129
        ]);
130
        $call = new CallExpression('sale_object', [$hstore]);
131
        $command = (new Query())->select($call);
132
        $sale->setId($command->scalar($this->db));
0 ignored issues
show
Bug introduced by
It seems like $this->db can also be of type object<hiqdev\yii\DataMa...ts\ConnectionInterface>; however, yii\db\Query::scalar() does only seem to accept object<yii\db\Connection>|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
133
    }
134
}
135