mardi 6 août 2019

Renaming object keys name in PHP Laravel

I have a JSON request and i need to change all object key names similar on my model object keys, i'm having a difficulty about nested array objects, and also dot notation is not working on this part.

Here is my code on my validation request:

<?php

namespace App\Http\Requests\Api\Nutmeg;

use Illuminate\Foundation\Http\FormRequest;

class WebhookValidation extends FormRequest
{

    protected $map = [
        'callback_url' => 'url',
        'tokenApi' => 'secret_token',
        'supplier' => 'agent',
        'supplier.*.key.*' => 'id',
        'supplier.*.number.*' => 'quantity'
    ];

    protected $jsonConvert;

    public function setJson($json)
    {
        foreach($this->map as $original => $new) {
            $json->set($new, $json->get($original));
            $json->remove($original);
        }
        $this->jsonConvert = $json;
    }

    public function validationData()
    {
        return $this->jsonConvert->all();
    }

    public function rules()
    {
        return [
            'url' => 'bail|required|url|unique:webhooks,url',
            'secret_token' => 'required',
            'agent.*.id' => 'required',
            'agent.*.quantity' => 'required'
        ];
    }

    public function messages()
    {
        return [
            'url.unique' => 'Url should be unique',
            'secret_token.required' => 'Secret token is required'
        ];
    }
}

Here is the JSON request:

{
      "callback_url": "https://www.gosdoddgle.com",
      "tokenApi": "stringstrinngstringstring",
      "supplier": [
            {
                "key": "sdsds1",
                "number": "sdsds1"
            },
            {
                "key": "sdsds1",
                "number": "sdsds1"
            }
        ]
}

From that i want it to be like this:

{
      "url": "https://www.gosdoddgle.com",
      "secret_token": "stringstrinngstringstring",
      "agent": [
            {
                "id": "sdsds1",
                "quantity": "sdsds1"
            },
            {
                "id": "sdsds1",
                "quantity": "sdsds1"
            }
        ]
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire