Completed
Push — master ( 9c7fd0...afc45c )
by Andrii
10:58
created

BillRepository::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 9
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 3
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, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\billing\hiapi\repositories;
12
13
use DateTime;
14
use hiqdev\yii\DataMapper\expressions\CallExpression;
15
use hiqdev\yii\DataMapper\expressions\HstoreExpression;
16
use hiqdev\php\billing\bill\BillInterface;
17
use hiqdev\php\billing\bill\BillFactoryInterface;
18
use hiqdev\php\billing\customer\Customer;
19
use hiqdev\php\billing\target\Target;
20
use hiqdev\php\billing\type\Type;
21
use hiqdev\php\units\Quantity;
22
use Money\Currency;
23
use Money\Money;
24
use yii\db\Query;
25
26
class BillRepository extends \hiqdev\yii\DataMapper\repositories\BaseRepository
27
{
28
    public function create(array $row)
29
    {
30
        $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\hi...itories\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...
31
        $row['time'] = new DateTime($row['time']);
32
        $row['quantity'] = Quantity::create('megabyte', $row['quantity']['quantity']);
33
        $currency = new Currency(strtoupper($row['sum']['currency']));
34
        $row['sum'] = new Money($row['sum']['amount'], $currency);
35
        $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\hi...itories\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
        $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\hi...itories\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...
37
38
        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\repositories\BillRepository, hiqdev\billing\hiapi\rep...ries\CustomerRepository, hiqdev\billing\hiapi\sale\SaleRepository, 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...
39
    }
40
41
    public function save(BillInterface $bill)
42
    {
43
        $hstore = new HstoreExpression([
44
            'id'            => $bill->getId(),
45
            'object_id'     => $bill->getTarget()->getId(),
46
            'tariff_id'     => $bill->getPlan()->getId(),
47
            'type_id'       => $bill->getType()->getId(),
48
            'type'          => $bill->getType()->getName(),
49
            'buyer_id'      => $bill->getCustomer()->getId(),
50
            'buyer'         => $bill->getCustomer()->getLogin(),
51
            'currency'      => $bill->getSum()->getCurrency()->getCode(),
52
            'sum'           => $bill->getSum()->getAmount() * -1,
53
            'quantity'      => $bill->getQuantity()->getQuantity(),
54
            'time'          => $bill->getTime()->format('c'),
55
            'is_finished'   => $bill->getIsFinished(),
56
            'increment'     => true,
57
        ]);
58
        $call = new CallExpression('set_bill2', [$hstore]);
59
        $command = (new Query())->select($call);
60
        $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...
61
        foreach ($bill->getCharges() as $charge) {
62
            $charge->setBill($bill);
63
            $this->em->save($charge);
64
        }
65
    }
66
}
67