Completed
Push — master ( c53d03...5cc00e )
by Andrii
02:37
created

SaleRepository::save()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 12
Code Lines 9

Duplication

Lines 12
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 12
loc 12
ccs 0
cts 12
cp 0
rs 9.4285
cc 2
eloc 9
nc 1
nop 1
crap 6
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\order\OrderInterface;
15
use hiqdev\php\billing\plan\PlanInterface;
16
use hiqdev\php\billing\sale\Sale;
17
use hiqdev\php\billing\sale\SaleInterface;
18
use hiqdev\php\billing\sale\SaleRepositoryInterface;
19
use hiqdev\yii\DataMapper\expressions\CallExpression;
20
use hiqdev\yii\DataMapper\expressions\HstoreExpression;
21
use hiqdev\yii\DataMapper\models\relations\Bucket;
22
use hiqdev\yii\DataMapper\query\Specification;
23
use hiqdev\yii\DataMapper\repositories\BaseRepository;
24
use Yii;
25
use yii\db\Query;
26
27
class SaleRepository extends BaseRepository implements SaleRepositoryInterface
28
{
29
    /** {@inheritdoc} */
30
    public $queryClass = SaleQuery::class;
31
32 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...
33
    {
34
        if ($sale->hasId()) {
35
            return $sale->getId();
36
        }
37
        $hstore = new HstoreExpression(array_filter([
38
            'buyer'     => $sale->getCustomer()->getLogin(),
39
            'buyer_id'  => $sale->getCustomer()->getId(),
40
            'object_id' => $sale->getTarget()->getId(),
41
            'tariff_id' => $sale->getPlan()->getId(),
42
        ]));
43
        $call = new CallExpression('sale_id', [$hstore]);
44
        $command = (new Query())->select($call);
45
46
        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...
47
    }
48
49
    /**
50
     * @param OrderInterface $order
51
     * @return Sale[]|SaleInterface[]
52
     */
53
    public function findByOrder(OrderInterface $order)
54
    {
55
        return array_map([$this, 'findByAction'], $order->getActions());
56
    }
57
58
    /**
59
     * @param ActionInterface $action
60
     * @return SaleInterface
61
     */
62
    public function findByAction(ActionInterface $action)
63
    {
64
        $client_id = $action->getCustomer()->getId();
65
        $seller_id = $action->getCustomer()->getSeller()->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 = [
72
                'target-id' => $class_id,
73
                'customer-id' => $client_id,
74
            ];
75
            if (empty($client_id)) {
76
                $cond['customer-id'] = $seller_id;
77
                $cond['seller-id'] = $seller_id;
78
            }
79
        } elseif ($type === 'server') {
80
            $cond = [
81
                'target-id' => $action->getTarget()->getId(),
82
                'customer-id' => $client_id,
83
            ];
84
        } else {
85
            throw new \Exception('not implemented for: ' . $type);
86
        }
87
88
        $spec = Yii::createObject(Specification::class)
89
            /// XXX how to pass if we want with prices into joinPlans?
90
            ->with('plans')
91
            ->where($cond);
92
93
        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 93 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...
94
    }
95
96
    protected function joinPlans(&$rows)
97
    {
98
        $bucket = Bucket::fromRows($rows, 'plan-id');
99
        $spec = (new Specification())
100
            ->with('prices')
101
            ->where(['id' => $bucket->getKeys()]);
102
        $raw_plans = $this->getRepository(PlanInterface::class)->queryAll($spec);
103
        /// TODO for SilverFire: try to do with bucket
104
        $plans = [];
105
        foreach ($raw_plans as $plan) {
106
            $plans[$plan['id']] = $plan;
107
        }
108
        foreach ($rows as &$sale) {
109
            $sale['plan'] = $plans[$sale['plan-id']];
110
        }
111
    }
112
113
    /**
114
     * @param SaleInterface $sale
115
     */
116 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...
117
    {
118
        $hstore = new HstoreExpression([
119
            'object_id'     => $sale->getTarget()->getId(),
120
            'contact_id'    => $sale->getCustomer()->getId(),
121
            'tariff_id'     => $sale->getPlan() ? $sale->getPlan()->getId() : null,
122
            'time'          => $sale->getTime()->format('c'),
123
        ]);
124
        $call = new CallExpression('sale_object', [$hstore]);
125
        $command = (new Query())->select($call);
126
        $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...
127
    }
128
}
129