RateFactory::make()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
/**
4
 * This file is part of laravel-quota
5
 *
6
 * (c) David Faith <[email protected]>
7
 *
8
 * Full copyright and license information is available
9
 * in the LICENSE file distributed with this source code.
10
 */
11
12
namespace Projectmentor\Quota\Factories;
13
14
use bandwidthThrottle\tokenBucket\Rate;
15
use Projectmentor\Quota\Contracts\FactoryInterface;
16
use Projectmentor\Quota\Contracts\PayloadInterface;
17
18
/**
19
 * This is the token-bucket Rate factory class.
20
 *
21
 * @author David Faith <[email protected]>
22
 */
23
class RateFactory implements FactoryInterface
24
{
25
    /**
26
     * Make a new rate instance.
27
     *
28
     * TODO: abstract the return value via contract
29
     *
30
     * @param \Projectmentor\Quota\Contracts\PayloadInterface $data
31
     * @return \bandwidthThrottle\tokenBucket\Rate
32
     */
33 1
    public function make(PayloadInterface $data)
34
    {
35 1
        return new Rate($data->getlimit(), $data->getPeriod());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Projectmentor\Quota\Contracts\PayloadInterface as the method getlimit() does only exist in the following implementations of said interface: Projectmentor\Quota\Stubs\RateData.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
Bug introduced by
It seems like you code against a concrete implementation and not the interface Projectmentor\Quota\Contracts\PayloadInterface as the method getPeriod() does only exist in the following implementations of said interface: Projectmentor\Quota\Stubs\RateData.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
Bug Best Practice introduced by
The return type of return new \bandwidthThr...), $data->getPeriod()); (bandwidthThrottle\tokenBucket\Rate) is incompatible with the return type declared by the interface Projectmentor\Quota\Cont...\FactoryInterface::make of type Projectmentor\Quota\Contracts\QuotaInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
36
    }
37
38
    /**
39
     * Retrieve value for constant defined in Rate::class.
40
     * Convienience method.
41
     *
42
     * @param string $key constant name
43
     * @return string constant value
0 ignored issues
show
Documentation introduced by
Should the return type not be integer|double|string|boolean?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
44
     * @throws InvalidArgumentException
45
     */
46 1
    public function getConstant($key)
47
    {
48 1
        $constants = $this->getConstants();
49 1
        if (array_key_exists($key, $constants)) {
50 1
            return $constants[$key];
51
        } else {
52 1
            throw new \InvalidArgumentException(
53 1
                __CLASS__.'::'.__FUNCTION__.
54 1
                ' Invalid constant. Got: ' . $key .
55 1
                ' Expected: ' . print_r($constants, 1)
56 1
            );
57
        }
58
    }
59
60
    /**
61
     * Retrieve an array of constants defined in Rate::class.
62
     * Convienience method.
63
     *
64
     * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,integer|double|string|boolean>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
65
     */
66 2
    public function getConstants()
67
    {
68 2
        $reflect = new \ReflectionClass(Rate::class);
69 2
        return $reflect->getConstants();
70
    }
71
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
72