Completed
Push — master ( c82baa...ed63c5 )
by Andrii
06:43
created

BillRepository   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 13

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 13
dl 0
loc 54
ccs 0
cts 41
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 12 1
A saveReal() 0 4 1
B save() 0 26 5
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\bill;
12
13
use DateTime;
14
use hiqdev\php\billing\bill\BillInterface;
15
use hiqdev\php\billing\customer\Customer;
16
use hiqdev\php\billing\target\Target;
17
use hiqdev\php\billing\type\Type;
18
use hiqdev\php\units\Quantity;
19
use hiqdev\yii\DataMapper\expressions\CallExpression;
20
use hiqdev\yii\DataMapper\expressions\HstoreExpression;
21
use Money\Currency;
22
use Money\Money;
23
use yii\db\Query;
24
25
class BillRepository extends \hiqdev\yii\DataMapper\repositories\BaseRepository
26
{
27
    public function create(array $row)
28
    {
29
        $row['type'] = $this->createEntity(Type::class, $row['type']);
0 ignored issues
show
Documentation Bug introduced by
The method createEntity does not exist on object<hiqdev\billing\hiapi\bill\BillRepository>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
30
        $row['time'] = new DateTime($row['time']);
31
        $row['quantity'] = Quantity::create('megabyte', $row['quantity']['quantity']);
32
        $currency = new Currency(strtoupper($row['sum']['currency']));
33
        $row['sum'] = new Money($row['sum']['amount'], $currency);
34
        $row['customer'] = $this->createEntity(Customer::class, $row['customer']);
0 ignored issues
show
Documentation Bug introduced by
The method createEntity does not exist on object<hiqdev\billing\hiapi\bill\BillRepository>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
35
        $row['target'] = $this->createEntity(Target::class, $row['target']);
0 ignored issues
show
Documentation Bug introduced by
The method createEntity does not exist on object<hiqdev\billing\hiapi\bill\BillRepository>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
36
37
        return parent::create($row);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class hiqdev\yii\DataMapper\repositories\BaseRepository as the method create() does only exist in the following sub-classes of hiqdev\yii\DataMapper\repositories\BaseRepository: hiqdev\billing\hiapi\bill\BillRepository, hiqdev\billing\hiapi\rep...ries\CustomerRepository, hiqdev\billing\hiapi\vo\...TimeImmutableRepository. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
38
    }
39
40
    /**
41
     * XXX TO BE REMOVED
42
     */
43
    public function saveReal(BillInterface $bill)
44
    {
45
        return $this->save($bill, true);
46
    }
47
48
    /**
49
     * @param BillInterface $bill
50
     * @param bool $isReal XXX TO BE REMOVED
51
     */
52
    public function save(BillInterface $bill, $isReal = false)
53
    {
54
        $hstore = new HstoreExpression([
55
            'id'            => $bill->getId(),
56
            'object_id'     => $bill->getTarget()->getId(),
57
            'tariff_id'     => $bill->getPlan() ? $bill->getPlan()->getId() : null,
58
            'type_id'       => $bill->getType()->getId(),
59
            'type'          => $bill->getType()->getName(),
60
            'buyer_id'      => $bill->getCustomer()->getId(),
61
            'buyer'         => $bill->getCustomer()->getLogin(),
62
            'currency'      => $bill->getSum()->getCurrency()->getCode(),
63
            'sum'           => $bill->getSum()->getAmount() * -1,
64
            'quantity'      => $bill->getQuantity()->getQuantity(),
65
            'time'          => $bill->getTime()->format('c'),
66
            'label'         => $bill->getComment() ?: null,
0 ignored issues
show
Bug introduced by
The method getComment() does not seem to exist on object<hiqdev\php\billing\bill\BillInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
67
            'is_finished'   => $bill->getIsFinished(),
68
            'increment'     => true,
69
        ]);
70
        $call = new CallExpression('set_bill' . ($isReal ? '' : '2'), [$hstore]);
71
        $command = (new Query())->select($call);
72
        $bill->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...
73
        foreach ($bill->getCharges() as $charge) {
74
            $charge->setBill($bill);
75
            $this->em->save($charge);
76
        }
77
    }
78
}
79