Skip to content

Commit

Permalink
Replace json_decode with Json::decodeAssociatively
Browse files Browse the repository at this point in the history
  • Loading branch information
LucWollants committed Aug 8, 2024
1 parent 15b8464 commit 0c7d36e
Show file tree
Hide file tree
Showing 18 changed files with 52 additions and 53 deletions.
10 changes: 4 additions & 6 deletions src/Deserializer/JSONDeserializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace CultuurNet\UDB3\Deserializer;

use JsonException;
use CultuurNet\UDB3\Json;

class JSONDeserializer implements DeserializerInterface
{
Expand All @@ -22,12 +22,10 @@ public function __construct(bool $assoc = false)
*/
public function deserialize(string $data)
{
$data = json_decode($data, $this->assoc);

if (null === $data) {
throw new JsonException('Invalid JSON');
if ($this->assoc) {
return Json::decodeAssociatively($data);
}

return $data;
return Json::decode($data);
}
}
4 changes: 2 additions & 2 deletions src/EventSourcing/DBAL/AggregateAwareDBALEventStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,8 @@ private function deserializeEvent(array $row): DomainMessage
return new DomainMessage(
$row['uuid'],
(int) $row['playhead'],
$this->metadataSerializer->deserialize(json_decode($row['metadata'], true)),
$this->payloadSerializer->deserialize(json_decode($row['payload'], true)),
$this->metadataSerializer->deserialize(Json::decodeAssociatively($row['metadata'])),
$this->payloadSerializer->deserialize(Json::decodeAssociatively($row['payload'])),
DateTime::fromString($row['recorded_on'])
);
}
Expand Down
5 changes: 3 additions & 2 deletions src/EventSourcing/DBAL/EventStream.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Broadway\Domain\DomainMessage;
use Broadway\EventSourcing\EventStreamDecorator;
use Broadway\Serializer\Serializer;
use CultuurNet\UDB3\Json;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver\Statement;
use Doctrine\DBAL\DBALException;
Expand Down Expand Up @@ -180,8 +181,8 @@ private function deserializeEvent(array $row): DomainMessage
return new DomainMessage(
$row['uuid'],
(int) $row['playhead'],
$this->metadataSerializer->deserialize(json_decode($row['metadata'], true)),
$this->payloadSerializer->deserialize(json_decode($row['payload'], true)),
$this->metadataSerializer->deserialize(Json::decodeAssociatively($row['metadata'])),
$this->payloadSerializer->deserialize(Json::decodeAssociatively($row['payload'])),
DateTime::fromString($row['recorded_on'])
);
}
Expand Down
11 changes: 7 additions & 4 deletions src/Model/Import/DecodedDocument.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@

namespace CultuurNet\UDB3\Model\Import;

use CultuurNet\UDB3\Json;
use CultuurNet\UDB3\ReadModel\JsonDocument;
use InvalidArgumentException;
use JsonException;

class DecodedDocument
{
Expand Down Expand Up @@ -53,10 +56,10 @@ public function toJsonDocument(): JsonDocument

public static function fromJson(string $id, string $json): self
{
$body = json_decode($json, true);

if (is_null($body)) {
throw new \InvalidArgumentException('The given JSON is not valid and can not be decoded.');
try {
$body = Json::decodeAssociatively($json);
} catch (JsonException $e) {
throw new InvalidArgumentException('The given JSON is not valid and can not be decoded.');
}

return new self($id, $body);
Expand Down
8 changes: 2 additions & 6 deletions src/Offer/IriOfferIdentifierJSONDeserializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

use CultuurNet\UDB3\Deserializer\DeserializerInterface;
use CultuurNet\UDB3\Deserializer\MissingValueException;
use CultuurNet\UDB3\Json;
use CultuurNet\UDB3\Model\ValueObject\Web\Url;
use JsonException;

/**
* @deprecated
Expand All @@ -27,11 +27,7 @@ public function __construct(IriOfferIdentifierFactoryInterface $iriOfferIdentifi

public function deserialize(string $data): IriOfferIdentifier
{
$data = json_decode($data, true);

if (null === $data) {
throw new JsonException('Invalid JSON');
}
$data = Json::decodeAssociatively($data);

if (!isset($data['@id'])) {
throw new MissingValueException('Missing property "@id".');
Expand Down
2 changes: 1 addition & 1 deletion src/Role/ReadModel/Labels/LabelRolesProjector.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ private function getDocument(UUID $uuid): ?JsonDocument
*/
private function getRoleDetails(JsonDocument $document)
{
return json_decode($document->getRawBody(), true);
return Json::decodeAssociatively($document->getRawBody());
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Role/ReadModel/Labels/RoleLabelsProjector.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ private function getDocument(UUID $uuid): ?JsonDocument
*/
private function getLabelDetails(JsonDocument $document)
{
return json_decode($document->getRawBody(), true);
return Json::decodeAssociatively($document->getRawBody());
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Role/ReadModel/Users/RoleUsersProjector.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,6 @@ private function getDocument(UUID $uuid): ?JsonDocument
*/
private function getUserIdentityDetails(JsonDocument $document): array
{
return json_decode($document->getRawBody(), true);
return Json::decodeAssociatively($document->getRawBody());
}
}
8 changes: 4 additions & 4 deletions src/Role/ReadModel/Users/UserRolesProjector.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public function applyUserAdded(UserAdded $userAdded): void
);
}

$roles = json_decode($document->getRawBody(), true);
$roles = Json::decodeAssociatively($document->getRawBody());
$roles[$roleId] = $roleDetails;

$document = $document->withAssocBody($roles);
Expand All @@ -73,7 +73,7 @@ public function applyUserRemoved(UserRemoved $userRemoved): void
return;
}

$roles = json_decode($document->getRawBody(), true);
$roles = Json::decodeAssociatively($document->getRawBody());
unset($roles[$roleId]);

$document = $document->withAssocBody($roles);
Expand All @@ -99,13 +99,13 @@ public function applyRoleDetailsProjectedToJSONLD(RoleDetailsProjectedToJSONLD $

$roleDetails = $roleDetailsDocument->getBody();

$roleUsers = json_decode($roleUsersDocument->getRawBody(), true);
$roleUsers = Json::decodeAssociatively($roleUsersDocument->getRawBody());
$roleUserIds = array_keys($roleUsers);

foreach ($roleUserIds as $roleUserId) {
$userRolesDocument = $this->repository->fetch($roleUserId);

$userRoles = json_decode($userRolesDocument->getRawBody(), true);
$userRoles = Json::decodeAssociatively($userRolesDocument->getRawBody());
$userRoles[$roleId] = $roleDetails;

$userRolesDocument = $userRolesDocument->withAssocBody($userRoles);
Expand Down
3 changes: 2 additions & 1 deletion src/User/Auth0/Auth0ManagementTokenGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace CultuurNet\UDB3\User\Auth0;

use CultuurNet\UDB3\Json;
use CultuurNet\UDB3\User\ManagementToken\ManagementToken;
use CultuurNet\UDB3\User\ManagementToken\ManagementTokenGenerator;
use DateTimeImmutable;
Expand Down Expand Up @@ -37,7 +38,7 @@ public function newToken(): ManagementToken
]
);

$res = json_decode($response->getBody()->getContents(), true);
$res = Json::decodeAssociatively($response->getBody()->getContents());

return new ManagementToken(
$res['access_token'],
Expand Down
2 changes: 1 addition & 1 deletion src/User/ManagementToken/CacheRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public function token(): ?ManagementToken
return null;
}

$tokenAsArray = json_decode($this->cache->fetch(self::TOKEN_KEY), true);
$tokenAsArray = Json::decodeAssociatively($this->cache->fetch(self::TOKEN_KEY));

return new ManagementToken(
$tokenAsArray['token'],
Expand Down
6 changes: 3 additions & 3 deletions tests/BackwardsCompatiblePayloadSerializerFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public function it_handles_main_language(
Language $expectedMainLanguage
): void {
$serialized = file_get_contents($sampleFile);
$decoded = json_decode($serialized, true);
$decoded = Json::decodeAssociatively($serialized);

/** @var EventCreated|PlaceCreated|OrganizerCreatedWithUniqueWebsite $created */
$created = $this->serializer->deserialize($decoded);
Expand Down Expand Up @@ -482,7 +482,7 @@ public function it_replaces_missing_availability_dates_with_null_on_booking_info
$sampleFile = $this->sampleDir . 'serialized_event_booking_info_updated_without_availability.json';

$serialized = file_get_contents($sampleFile);
$decoded = json_decode($serialized, true);
$decoded = Json::decodeAssociatively($serialized);

/* @var BookingInfoUpdated $bookingInfoUpdated */
$bookingInfoUpdated = $this->serializer->deserialize($decoded);
Expand Down Expand Up @@ -684,7 +684,7 @@ private function assertTypedIdReplacedWithItemId(string $type, string $sampleFil
private function assertKeywordReplacedWithLabel(string $sampleFile): void
{
$serialized = file_get_contents($sampleFile);
$decoded = json_decode($serialized, true);
$decoded = Json::decodeAssociatively($serialized);
$keyword = $decoded['payload']['keyword'];

/** @var AbstractLabelEvent $abstractLabelEvent */
Expand Down
2 changes: 1 addition & 1 deletion tests/Deserializer/JSONDeserializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public function setUp(): void
public function itThrowsJsonExceptionForInvalidJson(): void
{
$this->expectException(JsonException::class);
$this->expectExceptionMessage('Invalid JSON');
$this->expectExceptionMessage('Syntax error');

$this->deserializer->deserialize(
'{
Expand Down
5 changes: 3 additions & 2 deletions tests/Http/Assert/JsonEquals.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace CultuurNet\UDB3\Http\Assert;

use CultuurNet\UDB3\Json;
use PHPUnit\Framework\TestCase;

class JsonEquals
Expand All @@ -21,8 +22,8 @@ public function __construct(TestCase $testCase)

public function assert(string $expectedJson, string $actualJson): void
{
$expected = json_decode($expectedJson, true);
$actual = json_decode($actualJson, true);
$expected = Json::decodeAssociatively($expectedJson);
$actual = Json::decodeAssociatively($actualJson);

if (is_null($expected)) {
$this->testCase->fail('Expected json is not valid json.');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace CultuurNet\UDB3\Http\Deserializer\Calendar;

use CultuurNet\UDB3\Deserializer\DataValidationException;
use CultuurNet\UDB3\Json;
use PHPUnit\Framework\TestCase;

class CalendarForEventDataValidatorTest extends TestCase
Expand All @@ -25,9 +26,8 @@ protected function setUp(): void
*/
public function it_does_not_throw_for_valid_calendars(string $file): void
{
$data = json_decode(
file_get_contents(__DIR__ . '/samples/' . $file),
true
$data = Json::decodeAssociatively(
file_get_contents(__DIR__ . '/samples/' . $file)
);

$this->calendarForEventDataValidator->validate($data);
Expand Down
22 changes: 10 additions & 12 deletions tests/Http/Deserializer/Calendar/CalendarJSONParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use CultuurNet\UDB3\Event\ValueObjects\Status;
use CultuurNet\UDB3\Event\ValueObjects\StatusReason;
use CultuurNet\UDB3\Event\ValueObjects\StatusType;
use CultuurNet\UDB3\Json;
use CultuurNet\UDB3\Language;
use CultuurNet\UDB3\Model\ValueObject\Calendar\OpeningHours\Hour;
use CultuurNet\UDB3\Model\ValueObject\Calendar\OpeningHours\Minute;
Expand All @@ -34,7 +35,7 @@ class CalendarJSONParserTest extends TestCase
protected function setUp(): void
{
$updateCalendar = file_get_contents(__DIR__ . '/samples/calendar_all_fields.json');
$this->updateCalendarAsArray = json_decode($updateCalendar, true);
$this->updateCalendarAsArray = Json::decodeAssociatively($updateCalendar);

$this->calendarJSONParser = new CalendarJSONParser();
}
Expand All @@ -60,7 +61,7 @@ public function it_can_get_the_start_date(): void
public function it_returns_null_when_start_date_is_missing(): void
{
$updateCalendar = file_get_contents(__DIR__ . '/samples/calendar_missing_start_and_end.json');
$updateCalendarAsArray = json_decode($updateCalendar, true);
$updateCalendarAsArray = Json::decodeAssociatively($updateCalendar);

$this->assertNull(
$this->calendarJSONParser->getStartDate(
Expand Down Expand Up @@ -90,7 +91,7 @@ public function it_can_get_the_end_date(): void
public function it_returns_null_when_end_date_is_missing(): void
{
$updateCalendar = file_get_contents(__DIR__ . '/samples/calendar_missing_start_and_end.json');
$updateCalendarAsArray = json_decode($updateCalendar, true);
$updateCalendarAsArray = Json::decodeAssociatively($updateCalendar);

$this->assertNull(
$this->calendarJSONParser->getEndDate(
Expand Down Expand Up @@ -180,9 +181,8 @@ public function it_can_get_the_timestamps(): void
*/
public function it_should_not_create_timestamps_when_json_is_missing_an_end_property(): void
{
$calendarData = json_decode(
file_get_contents(__DIR__ . '/samples/calendar_missing_time_span_end.json'),
true
$calendarData = Json::decodeAssociatively(
file_get_contents(__DIR__ . '/samples/calendar_missing_time_span_end.json')
);

$this->assertEmpty(
Expand All @@ -195,9 +195,8 @@ public function it_should_not_create_timestamps_when_json_is_missing_an_end_prop
*/
public function it_should_not_create_timestamps_when_json_is_missing_a_start_property(): void
{
$calendarData = json_decode(
file_get_contents(__DIR__ . '/samples/calendar_missing_time_span_start.json'),
true
$calendarData = Json::decodeAssociatively(
file_get_contents(__DIR__ . '/samples/calendar_missing_time_span_start.json')
);

$this->assertEmpty(
Expand Down Expand Up @@ -255,9 +254,8 @@ public function it_can_get_the_opening_hours(): void
*/
public function it_should_not_create_opening_hours_when_fields_are_missing(): void
{
$calendarData = json_decode(
file_get_contents(__DIR__ . '/samples/calendar_with_opening_hours_but_missing_fields.json'),
true
$calendarData = Json::decodeAssociatively(
file_get_contents(__DIR__ . '/samples/calendar_with_opening_hours_but_missing_fields.json')
);

$this->assertEmpty(
Expand Down
5 changes: 3 additions & 2 deletions tests/Http/Ownership/RequestOwnershipRequestHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use CultuurNet\UDB3\Http\ApiProblem\AssertApiProblemTrait;
use CultuurNet\UDB3\Http\ApiProblem\SchemaError;
use CultuurNet\UDB3\Http\Request\Psr7RequestBuilder;
use CultuurNet\UDB3\Json;
use CultuurNet\UDB3\Model\ValueObject\Identity\ItemType;
use CultuurNet\UDB3\Model\ValueObject\Identity\UserId;
use CultuurNet\UDB3\Model\ValueObject\Identity\UUID;
Expand Down Expand Up @@ -98,7 +99,7 @@ public function it_handles_requesting_ownership(): void
[
'id' => 'e6e1f3a0-3e5e-4b3e-8e3e-3f3e3e3e3e3e',
],
json_decode((string) $response->getBody(), true)
Json::decodeAssociatively((string) $response->getBody())
);

$this->assertEquals(
Expand Down Expand Up @@ -156,7 +157,7 @@ public function it_handles_requesting_ownership_as_admin(): void
[
'id' => 'e6e1f3a0-3e5e-4b3e-8e3e-3f3e3e3e3e3e',
],
json_decode((string) $response->getBody(), true)
Json::decodeAssociatively((string) $response->getBody())
);

$this->assertEquals(
Expand Down
2 changes: 1 addition & 1 deletion tests/Offer/IriOfferIdentifierJSONDeserializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public function it_throws_an_json_exception_when_the_json_is_malformed(): void
$json = '{"foo"';

$this->expectException(JsonException::class);
$this->expectExceptionMessage('Invalid JSON');
$this->expectExceptionMessage('Syntax error');

$this->deserializer->deserialize($json);
}
Expand Down

0 comments on commit 0c7d36e

Please sign in to comment.