CakePHP 5 patchentity camelCase mapping

I need to patch an entity using

but the field from the request come in camelcase, is there any automapper in cake php 5 To make it works because my entity is in snake_case
patchEntity($city , $data);

  class City extends Entity
{
    /**
     * Fields that can be mass assigned using newEntity() or patchEntity().
     *
     * Note that when '*' is set to true, this allows all unspecified fields to
     * be mass assigned. For security purposes, it is advised to set '*' to false
     * (or remove it), and explicitly make individual fields accessible as needed.
     *
     * @var array<string, bool>
     */
    protected array $_accessible = [
        'name' => true,
        'zip_code' => true,
        'region_code' => true,
        'department_code' => true,
        'deleted' => true,
        'department_id' => true,
        'updated_at' => true,
        'created_at' => true,
    ];
}

You could use the beforeMarshal callback to do the swap in a table class. The Inflector class could be used to automate the swap between camelCase and snake_case.

 dd([
            Inflector::underscore('zipCode'),
            Inflector::camelize('zip_code'),
            Inflector::variable('zip_code')
        ]);

# output
[
  (int) 0 => 'zip_code',
  (int) 1 => 'ZipCode',
  (int) 2 => 'zipCode'
]

https://book.cakephp.org/5/en/orm/saving-data.html#before-marshal


// In a table or behavior class
public function beforeMarshal(EventInterface $event, ArrayObject $data, ArrayObject $options)
{
    if (isset($data['zipCode'])) {
        $data['zip_code'] = $data['zipCode'];
        unset($data['zipCode']);
    }
}

1 Like

It’s almost certainly easier, and more reliable in the long term, to just arrange for the data to be sent in as zip_code in the first place.

1 Like