Issues (40)

php-src/Mapping/JsonMapper.php (1 issue)

1
<?php
2
3
namespace kalanis\Restful\Mapping;
4
5
6
use kalanis\Restful\Mapping\Exceptions\MappingException;
7
use Nette\Utils\Json;
8
use Nette\Utils\JsonException;
9
10
11
/**
12
 * JsonMapper
13
 * @package kalanis\Restful\Mapping
14
 */
15 1
class JsonMapper implements IMapper
16
{
17
18
    /**
19
     * Convert array or Traversable input to string output response
20
     * @param string|object|iterable<string|int, mixed> $data
21
     * @param bool $prettyPrint
22
     * @throws MappingException
23
     * @return string
24
     */
25
    public function stringify(iterable|string|object $data, bool $prettyPrint = true): string
26
    {
27
        try {
28 1
            return Json::encode($data, $prettyPrint);
29
        } catch (JsonException $e) {
30
            throw new MappingException('Error in parsing response: ' . $e->getMessage());
31
        }
32
    }
33
34
    /**
35
     * Convert client request data to array or traversable
36
     * @param mixed $data
37
     * @throws MappingException
38
     * @return iterable<string|int, mixed>
39
     */
40
    public function parse(mixed $data): iterable
41
    {
42
        try {
43 1
            return (array) Json::decode(strval($data), true);
0 ignored issues
show
Bug Best Practice introduced by
The expression return (array)Nette\Util...de(strval($data), true) returns the type array which is incompatible with the return type mandated by kalanis\Restful\Mapping\IMapper::parse() of iterable|object|string.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
44 1
        } catch (JsonException $e) {
45 1
            throw new MappingException('Error in parsing request: ' . $e->getMessage());
46
        }
47
    }
48
}
49