Exclude null properties in JMS Serializer - php

My consumed XML API has an option to retrieve only parts of the response.
This causes the resulting object to have a lot of NULL properties if this feature is used.
Is there a way to actually skip NULL properties? I tried to implement an exclusion strategy with
shouldSkipProperty(PropertyMetadata $property, Context $context)`
but i realized there is no way to access the current property value.
An example would be the following class
class Hotel {
/**
* #Type("string")
*/
public $id;
/**
* #Type("integer")
*/
public $bookable;
/**
* #Type("string")
*/
public $name;
/**
* #Type("integer")
*/
public $type;
/**
* #Type("double")
*/
public $stars;
/**
* #Type("MssPhp\Schema\Response\Address")
*/
public $address;
/**
* #Type("integer")
*/
public $themes;
/**
* #Type("integer")
*/
public $features;
/**
* #Type("MssPhp\Schema\Response\Location")
*/
public $location;
/**
* #Type("MssPhp\Schema\Response\Pos")
*/
public $pos;
/**
* #Type("integer")
*/
public $price_engine;
/**
* #Type("string")
*/
public $language;
/**
* #Type("integer")
*/
public $price_from;
}
which deserializes in this specific api call to the following object with a lot of null properties.
"hotel": [
{
"id": "11230",
"bookable": 1,
"name": "Hotel Test",
"type": 1,
"stars": 3,
"address": null,
"themes": null,
"features": null,
"location": null,
"pos": null,
"price_engine": 0,
"language": "de",
"price_from": 56
}
]
But i want it to be
"hotel": [
{
"id": "11230",
"bookable": 1,
"name": "Hotel Test",
"type": 1,
"stars": 3,
"price_engine": 0,
"language": "de",
"price_from": 56
}
]

You can configure JMS Serializer to skip null properties like so:
$serializer = JMS\SerializerBuilder::create();
$serializedString = $serializer->serialize(
$data,
'xml',
JMS\SerializationContext::create()->setSerializeNull(true)
);
Taken from this issue.
UPDATE:
Unfortunately, if you don't want the empty properties when deserializing, there is no other way then removing them yourself.
However, I'm not sure what your use case for actually wanting to remove these properties is, but it doesn't look like the Hotel class contains much logic. In this case, I'm wondering whether the result has should be a class at all ?
I think it would be more natural to have the data represented as an associative array instead of an object. Of course, JMS Serializer cannot deserialize your data into an array, so you will need a data transfer object.
It's enough that you add dumpArray and loadArray methods to your existing Hotel class. These will be used for transforming the data into your desired result and vice versa. There is your DTO.
/**
* Sets the object's properties based on the passed array
*/
public function loadArray(array $data)
{
}
/**
* Returns an associative array based on the objects properties
*/
public function dumpArray()
{
// filter out the properties that are empty here
}
I believe it's the cleanest approach and it might reflect what you're trying to do more.
I hope this helps.

Related

PHP Symfony NelmioApiDocBundle ignore methods in model class

I created the following class (simplified for the example) and using as #Model.
class Model
{
public string $name;
public function address(): string
{
return "$this->name#gmail.com";
}
public function isShort(): bool
{
return strlen($this->name) < 3;
}
}
The ApiDoc generator tries to interpret the functions as addSomething and isSomething so I obtain the model
{
"name": string,
"address": string,
"short": boolean
}
But I want only
{
"name": string
}
Is there a way to annotate the function to make them being ignored from the API doc renderer?
Use serialization groups for your entity for this purpose
1.In your controller, import
use OpenApi\Annotations as OA;
use Nelmio\ApiDocBundle\Annotation\Model;
2.Annotate your method with the desired model and serialization group. (In the example, this is the File:class entity and the file:read group)
/**
* #Route("/api/files", methods={"GET"})
* #OA\Response(
* response=200,
* description="Returns the Files",
* #OA\JsonContent(
* type="array",
* #OA\Items(ref=#Model(type=File::class, groups={"file:read"}))
* )
* )
* #OA\Tag(name="files")
*/
public function getFiles(){
//...
}
3.And finally specify in your serialization group entity to tell the api which properties to use.
class File
{
/**
* #Groups({"file:read"})
* #ORM\Column(name="filename", type="string")
*/
private string $filename;
/**
* #ORM\Column(name="extension", type="string")
*/
private string $extension;
}
4.Result. As we can see api doc ignores properties where the used serialization group is not set, in the example this property is extension.
{
"filename": string
}

How to prevent lazy loading of vulnarable entities in Symfony

My question is rather simple, but I didn't find any clues on the Internet after googling for one hour.
I'm trying to build an Symfony API, but when returning json output, it lazy loads, every relation into the output. While this is not such a big deal (in most cases), its really bad when it does this trick with user information. So everything (password, email, etc.) is displayed.
My question is: Is it possible to mark an entity in doctrine, as protected, so the autoload will not be made, with this entity? In some cases it comes pretty handy but this is a big flaw. If its not possible to mark an entity, is it possible to deactivate it completely, or on an Collection Element?
Thanks in advance
EDIT:
class User implements UserInterface
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=180, unique=true)
*/
private $email;
/**
* #var string The hashed password
* #ORM\Column(type="string")
*/
private $password;
/**
* #ORM\OneToOne(targetEntity="App\Entity\Profile", mappedBy="user", cascade={"persist", "remove"})
*/
private $profile;
getters and setters are there.
And there is a Profile class, that is the interface, for all relations. It has an 1to1 relation.
class Profile
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\OneToOne(targetEntity="App\Entity\User", inversedBy="profile", cascade={"persist", "remove"})
* #ORM\JoinColumn(nullable=false)
*/
private $user;
getters and setters are there to.
class Event
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="datetime")
*/
private $date;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Profile", inversedBy="ownedEvents")
* #ORM\JoinColumn(nullable=false)
*/
private $profile;
/**
* #ORM\OneToMany(targetEntity=Post::class, mappedBy="event", orphanRemoval=true)
*/
private $posts;
The problem ist, that this profile is loaded, and with it the user...
The following is the controller function. But the serialization is happening in an extra method.
public function getUnreactedEvents(): JsonResponse{
$events = $this->getDoctrine()
->getManager()
->getRepository(Event::class)
->getUnreactedEvents($this->profileUtils->getLoggedInProfileFromDatabase()->getId());
return new JsonResponse($this->eventUtils->eventsToArray($events));
}
here is the to array function. (There is a base class so there are two mathods:
\Utils class:
\\Utils class:
public function eventsToArray($events): array{
return $this->toArray($events, array("usrEvntSts"));
}
\\Base class:
protected function toArray($objects, $fieldsToBeRemoved): array{
$normalizers = [new DateTimeNormalizer(), new ObjectNormalizer()];
$serializer = new Serializer($normalizers);
if(!is_array($objects)){
$objects = array($objects);
}
//normalizes the objects object, for circular references, returns id of the object
//doctrine comes with own array format
$objectsArray = $serializer->normalize($objects, 'array', [
'circular_reference_handler' => function ($object) {
return $object->getId();
}
]);
//some keys have to be erased from the event response
foreach ($objectsArray as $key => $object) {
if (method_exists($objects[0], "getProfile")){
/** #var Profile $profile */
$profile = $objects[$key]->getProfile();
unset($objectsArray[$key]["profile"]);
$objectsArray[$key]["profile"]['id'] = $profile->getId();
}
foreach ($fieldsToBeRemoved as $field){
unset($objectsArray[$key][$field]);
}
}
return $objectsArray;
}
}
As you see, my first idea was to just delete the field. But afer I added an new entity relation (posts), which has an owner profile too. The user class is loaded again...
Output:
{
"id": 1,
"name": "xcvxycv",
"date": "2020-06-28T18:08:55+02:00",
"public": false,
"posts": [
{
"id": 1,
"date": "2020-06-30T00:00:00+02:00",
"content": "sfdnsdfnslkfdnlskd",
"profile": {
"id": 2,
"user": {
"id": 2,
"email": "alla",
"username": "alla",
"roles": [
"ROLE_USER"
],
"password": "$argon2id$v=19$m=65536,t=4,p=1$a01US1dadGFLY05Lb1RkcQ$npmy0HMf19Neo/BnMqXGwkq8AZKVSCAEmDz8mVHLaQ0",
"salt": null,
"apiToken": null,
"profile": 2
},
"username": "sdfsdf",
"usrEvntSts": [],
"ownedEvents": [
{
"id": 3,
"name": "blaaaa",
"date": "2020-06-28T18:08:55+02:00",
"profile": 2,
"public": false,
"usrEvntSts": [],
"posts": [
{
"id": 2,
"date": "2020-06-30T00:00:00+02:00",
"content": "sfdnsdfnslkfdnlskd",
"profile": 2,
"event": 3,
"comments": []
}
]
},
And it goes on and on and on....
I would suggest to use JMSSerializerBundle for that. It is a widely used bundle, also in huge API's. You can exactly configure which properties should be exposed and which not. You can also build groups for exposing properties and use a specific exclusion strategy. Check the documentation for further information.
Hint: also check the Limiting serialization depth for deep nested objects.

Symfony SerializedName equivalent for collection attributes while denormalizing

I am having a json request
{
applicant_info:{
"email": "jhon.doe#gmail.com",
"given_name": "jhon",
"family_name": "doe"
},
productId: 12
}
Having a dto class as below:
class Dto
{
/**
* #var int
* #SerializedName("product_id")
*/
public $productId;
/**
* #var Collection
* #SerializedName("applicant_info")
*/
public $applicantInfo = [
'email',
'givenName',
'familyName'
];
}
Now when I use below to deserialize I am not sure how to convert given_name and family_name from request to
givenName and familyName like I have converted product_id and applicant_info to productId and applicantInfo using #SerializedName
$serializer->deserialize(
$request->getContent(),
Dto::class,
self::FORMAT_JSON
);
Any help will be really appreciated

Laravel CRUD testing

In my Laravel application I am trying to get into feature testing and have started with a model called Announcement.
One test I'm running is whether a user can create an instance of Announcement and persist it to the database.
My test is as follows:
/** #test */
public function a_user_can_create_an_announcement()
{
$this->withoutExceptionHandling();
$this->setupPermissions();
$announcement = factory(Announcement::class)->raw();
$this->actingAs(factory(User::class)->create())->get(route('announcements.index'))->assertStatus(200);
$this->post(route('announcements.store', $announcement))->assertStatus(302);
$this->assertDatabaseHas('announcements', $announcement);
}
Now as far as I understand factory(Announcement::class)->raw(); returns a new Announcement as an array using the relevant model factory.
I then make a request to my store endpoint with the data array and expect to redirected so I add the following:
$this->post(route('announcements.store', $announcement))->assertStatus(302);
The final line is to check the announcement was written to the database table called announcements
I get the following error from the test case:
1) Tests\Feature\AnnouncementsTest::a_user_can_create_an_announcement
Failed asserting that a row in the table [announcements] matches the attributes {
"message": "King. 'When did you.",
"message_details": "The Caterpillar.",
"author": "beatrice-herzog",
"status": "pending",
"published_at": null,
"created_at": {
"date": "2019-05-16 04:13:12.000000",
"timezone_type": 3,
"timezone": "Europe\/London"
},
"updated_at": "2019-08-20T13:37:22.293428Z"
}.
Found: [
{
"id": 5,
"message": "King. 'When did you.",
"message_details": "<p>The Caterpillar.<\/p>",
"author": "hollis-dach",
"status": "pending",
"published_at": null,
"created_at": "2019-08-20 14:37:23",
"updated_at": "2019-08-20 14:37:23"
}
].
Here is my AnnouncementFactory
<?php
/* #var $factory \Illuminate\Database\Eloquent\Factory */
use Faker\Generator as Faker;
use App\User;
use App\Announcement;
use Carbon\Carbon;
$factory->define(Announcement::class, function (Faker $faker) {
$user = factory(User::class)->create();
return [
'message' => $faker->realText(25),
'message_details' => $faker->realText(20),
'author' => $user->username,
'status' => 'pending',
'published_at' => null,
'created_at' => $faker->dateTimeThisYear('now', 'Europe/London'),
'updated_at' => Carbon::now()
];
});
Here is my AnnouncementModel
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Purifier;
use Carbon\Carbon;
use App\Like;
class Announcement extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'message', 'message_details', 'status', 'published_at'
];
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = [
'published_at',
'created_at',
'updated_at',
];
/**
* Get the user that posted this announcement
*/
public function user()
{
return $this->belongsTo(User::class, 'author', 'username');
}
/**
* Get the users that have liked this article
*
* #return void
*/
public function likes()
{
return $this->morphToMany(User::class, 'likeable');
}
/**
* Purify the content of message details when it is set so that it isn't vulnerable to XXS attacks
*
* #param string $value
* #return void
*/
public function setMessageDetailsAttribute($value)
{
$this->attributes['message_details'] = Purifier::clean($value);
}
/**
* Generate a nicer format for created_at
*
* #return void
*/
public function getCreatedAtAttribute($value)
{
return Carbon::parse($value)->format('d F Y');
}
/**
* Determine whether an announcement is pending
*
* #return void
*/
public function getPendingAttribute()
{
return $this->status == 'pending' ? true : false;
}
/**
* Check if the user has liked this announcement
*
* #return void
*/
public function getUserHasLikedAttribute()
{
$like = $this->likes()->whereUserId(auth()->user()->id)->first();
return (!is_null($like)) ? true : false;
}
/**
* Get the users that have liked this article
*
* #return void
*/
public function getLikesCountAttribute()
{
return $this->likes()->count();
}
/**
* Get count of users who liked the announcement excluding the logged in user
*
* #return void
*/
public function getLikesCountExcludingAuthUserAttribute()
{
return $this->likes()->where('username', '<>', auth()->user()->username)->count();
}
/**
* Get random user who liked this announcement
*
* #return void
*/
public function getRandomUserWhoLikedThisAttribute()
{
return $this->likes()->where('username', '<>', auth()->user()->username)->inRandomOrder()->first();
}
/**
* Get all users who liked this announcement
*
* #return void
*/
public function getUsersWhoLikedThisAttribute()
{
return $this->likes()->where('username', '<>', auth()->user()->username)->get();
}
/**
* Scope an article by whether or not it's published
*/
public function scopePublished($query)
{
return $query->where('status', 'published');
}
/**
* Scope an article by whether or not it's drafted
*/
public function scopePending($query)
{
return $query->where('status', 'pending');
}
/**
* Scope an article by whether or not it's archived
*/
public function scopeArchived($query)
{
return $query->where('status', 'archived');
}
}
Do the attributes literally have to be identical or am I just using tests incorrectly?
Do factories use model accessors and mutators?
I don't think you need to be testing the created_at and updated_at fields in this case. The reason why your test is failing is because the created_at value on the array is an instance of Carbon\Carbon rather than a string representing the datetime.
I would just update your factory to remove the created_at and updated_at values.
Try changing your factory to the following:
$factory->define(Announcement::class, function (Faker $faker) {
$user = factory(User::class)->create();
return [
'message' => $faker->realText(25),
'message_details' => $faker->realText(20),
'author' => $user->username,
'status' => 'pending',
'published_at' => null
];
});
Basically you are checking the database with the wrong information.
1 - announcements.store is an api which creates a new announcements for you.
2 - when you are calling assertDatabase, it's mean you have some information in your hand which you can check against the database. But if you take a look at the exception you can see you want to check this
"message": "King. 'When did you.",
"message_details": "The Caterpillar.",
"author": "beatrice-herzog",
"status": "pending",
"published_at": null,
"created_at": {
"date": "2019-05-16 04:13:12.000000",
"timezone_type": 3,
"timezone": "Europe\/London"
},
"updated_at": "2019-08-20T13:37:22.293428Z"
with this
"message": "King. 'When did you.",
"message_details": "<p>The Caterpillar.<\/p>",
"author": "hollis-dach",
"status": "pending",
"published_at": null,
"created_at": "2019-08-20 14:37:23",
"updated_at": "2019-08-20 14:37:23"
So either way you need to change the clause you are using. in this case you need to fix this three fields values(created_at, updated_at, message_details) or just remove them.
Yes, the key / value pairs you pass to assertDatabaseHas have to be identical to the record in your database. The function just searches for a row having the given column (key) with the specified value.
Be careful about converting your models to arrays. The resulting array may contain unexpected fields (relations) so better explicitly state the fields you want to check for.
I suggest you only include the properties of your announcement you want to test omitting the timestamps and other meta information.
Like this:
$this->assertDatabaseHas('announcements', Arr::only($announcement, [
'message', 'status'
]));
or like this:
$this->assertDatabaseHas('announcements', [
'message' => $announcement->message,
'status' => $announcement->status,
]);

How to configure the output of an object during json_encode?

A price object has three properties,
/** #var float */
public $amount = 0.0;
/** #var string */
public $currency = '';
/**
* #var \DateTime
*/
public $dueDate;
When serializing this object to json via the symfony2 Symfony\Component\HttpFoundation\JsonResponse, it will look like:
{
"price": {
"amount": 235,
"currency": "EUR",
"dueDate": {
"date": "2015-10-25 00:00:00.000000",
"timezone": "UTC",
"timezone_type": 3
}
}
}
I want the \DateTime to be formatted as simply a string:
"dueDate": "2015-10-22 00:00:00.000000"
How to get this done is not the scope of the question, as I currently handle this case in the object's constructor:
/**
* Price constructor.
* #param float $amount
* #param string $currency
* #param \DateTime|null $dueDate
*/
public function __construct($amount = 0.0, $currency = "", $dueDate)
{
$this->amount = $amount;
$this->currency = $currency;
$this->dueDate = $dueDate;;
if ($dueDate instanceof \DateTime) {
$this->dueDate = $dueDate->format(\DateTime::ATOM);
}
}
yet it doesn't feel entirely right, and I am curious if I could configure the serialize process differently, in the sense, instead of coding my representation, modify the way the object is serialized.
Reasoning is to have all \DateTime objects serialized that are serialized wherever in an to-be-serialized object in a same specific way, without duplicating logic. (I guess I could put the handling in an abstract class or somewhere similar, yet extending objects also has its pitfalls)
Basically:
Is there a catch an onserialize "event" where I can add some logic, or am I better off looking into JMSSerializer?
I don't know why I didn't submit this as the answer. Since PHP 5.4.0 a JsonSerializable library class is shipped with the PHP install. You can implement this class on your own and create a method named jsonSerialize that will be called whenever json_encode() is called with the class as the argument. A solution to your predicament could be similar to this:
<?php
class Price implements JsonSerializable {
private
$amount
, $currency
, $dueDate
;
/**
* Price constructor.
* #param float $amount
* #param string $currency
* #param \DateTime|null $dueDate
*/
public function __construct($amount = 0.0, $currency = "", $dueDate = NULL)
{
$this->amount = $amount;
$this->currency = $currency;
$this->dueDate = $dueDate;
}
public function jsonSerialize(){
return array(
'amount' => $this->amount
, 'currency' => $this->currency
, 'dueDate' => $this->dueDate instanceof \DateTime ? $this->dueDate->format(\DateTime::ATOM) : $this->dueDate
}
}
echo json_encode(new Price(235, "EUR", new DateTime()));
So you have 3 options:
Use the JsonSerializable interface like #iam-coder proposed.
Use a full-blown serializer like JMS (can be slow).
Use a transformer, the plus side of this is that your output is decoupled from your data, and you can change and test each component on it's own.

Categories