• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PHP-Alchemist / coreFiles / 15332630374

29 May 2025 08:12PM UTC coverage: 95.979% (-0.5%) from 96.481%
15332630374

Pull #13

github

web-flow
Merge 59769f3a2 into 49fb8b28c
Pull Request #13: json to class functionality

28 of 32 new or added lines in 2 files covered. (87.5%)

549 of 572 relevant lines covered (95.98%)

4.84 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.96
/src/Services/JsonMapper.php
1
<?php
2

3
namespace PHPAlchemist\Services;
4

5
use PHPAlchemist\Exceptions\BadJsonException;
6

7
class JsonMapper
8
{
9
    public function map(string $json, string $class) : object
5✔
10
    {
11
        if (!$this->validateJson($json)) {
5✔
12
            throw new BadJsonException();
2✔
13
        }
14

15
        $newObject = new $class();
3✔
16
        if (is_callable([$newObject, 'hydrate'])) {
3✔
NEW
17
            $newObject->hydrateFromJson($json);
×
18

NEW
19
            return $newObject;
×
20
        }
21

22
        $jsonDecodedData = json_decode($json, true);
3✔
23
        foreach ($jsonDecodedData as $key => $value) {
3✔
24
            if (!property_exists($newObject, $key)) {
3✔
NEW
25
                continue;
×
26
            }
27

28
            if (is_callable([$newObject, 'set'.ucfirst($key)])) {
3✔
29
                $newObject->{'set'.ucfirst($key)}($value);
3✔
30
            } elseif (property_exists($newObject, $key)) {
3✔
31
                $newObject->{$key} = $value;
3✔
32
            }
33
        }
34

35
        return $newObject;
2✔
36
    }
37

38
    protected function validateJson(string $json) : bool
5✔
39
    {
40
        if (!is_string($json) || strpos($json, '{') !== 0) {
5✔
41
            return false;
1✔
42
        }
43

44
        $validation = json_encode(json_decode($json, true));
4✔
45
        if ($validation !== $json) {
4✔
46
            return false;
1✔
47
        }
48

49
        return true;
3✔
50
    }
51
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc