Completed
Pull Request — master (#4)
by Evgeny
11:42
created

EnumHandler::deserialize()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4.3731

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 5
cts 7
cp 0.7143
rs 9.7998
c 0
b 0
f 0
cc 4
nc 3
nop 3
crap 4.3731
1
<?php
2
3
namespace Lamoda\AtolClient\Serializer\Handler;
4
5
use JMS\Serializer\Context;
6
use JMS\Serializer\GraphNavigator;
7
use JMS\Serializer\Handler\SubscribingHandlerInterface;
8
use JMS\Serializer\VisitorInterface;
9
use Paillechat\Enum\Enum;
10
11
/**
12
 * Adds support of "Enum" type for JMS.
13
 */
14
class EnumHandler implements SubscribingHandlerInterface
15
{
16
    private static $formats = [
17
        'atol_client',
18
    ];
19
20
    /**
21
     * {@inheritdoc}
22
     */
23 21
    public static function getSubscribingMethods()
24
    {
25 21
        $methods = [];
26
27 21
        foreach (self::$formats as $format) {
28 21
            $methods[] = [
29 21
                'type' => 'Enum',
30 21
                'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
31 21
                'format' => $format,
32 21
                'method' => 'deserialize',
33
            ];
34
35 21
            $methods[] = [
36 21
                'type' => 'Enum',
37 21
                'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
38 21
                'format' => $format,
39 21
                'method' => 'serialize',
40
            ];
41
        }
42
43 21
        return $methods;
44
    }
45
46
    /**
47
     * @param VisitorInterface $visitor
48
     * @param mixed            $data
49
     * @param array            $type
50
     *
51
     * @throws \Paillechat\Enum\Exception\EnumException
52
     *
53
     * @return Enum
54
     */
55 12
    public function deserialize(VisitorInterface $visitor, $data, array $type)
0 ignored issues
show
Unused Code introduced by
The parameter $visitor is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
56
    {
57 12
        if ($data === null) {
58
            return null;
59
        }
60
61
        // Return enum if exists:
62 12
        $class = $type['params'][0] ?? null;
63 12
        if (class_exists($class) && isset(class_parents($class)[Enum::class])) {
64 12
            return new $class($data);
65
        }
66
67
        throw new \LogicException('Enum class does not exist.');
68
    }
69
70
    /**
71
     * @param VisitorInterface $visitor
72
     * @param Enum             $enum
73
     * @param array            $type
74
     * @param Context          $context
75
     *
76
     * @throws \LogicException
77
     *
78
     * @return mixed
79
     */
80 14
    public function serialize(VisitorInterface $visitor, Enum $enum, array $type, Context $context)
81
    {
82 14
        $valueType = $type['params'][1] ?? 'string';
83 14
        switch ($valueType) {
84 14
            case 'string':
85 14
                return $visitor->visitString($enum->getValue(), $type, $context);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface JMS\Serializer\VisitorInterface as the method visitString() does only exist in the following implementations of said interface: JMS\Serializer\JsonDeserializationVisitor, JMS\Serializer\JsonSerializationVisitor, JMS\Serializer\XmlDeserializationVisitor, JMS\Serializer\XmlSerializationVisitor.

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...
86 14
            case 'integer':
87 14
                return $visitor->visitInteger($enum->getValue(), $type, $context);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface JMS\Serializer\VisitorInterface as the method visitInteger() does only exist in the following implementations of said interface: JMS\Serializer\JsonDeserializationVisitor, JMS\Serializer\JsonSerializationVisitor, JMS\Serializer\XmlDeserializationVisitor, JMS\Serializer\XmlSerializationVisitor.

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...
88
            default:
89
                throw new \LogicException('Unknown value type ');
90
        }
91
    }
92
}
93