Welcome Guest, Not a member yet? Register   Sign In
Entity cast-on-fill
#3

(04-14-2020, 10:54 AM)kilishan Wrote: Come to think of it, though, and a safer way to do it without modifying any code is simply to provide a setX() method that will cast it automatically on the way in.

That would work but I guess what I'm after is a way to normalize data types in bulk. That approach would require a `setX()` method for every attribute and would duplicate the casts we have defined for the way out. For the moment I've written my own extension to `toRawArray()` like I outlined above.
PHP Code:
    /**
     * Force raw array output through casts.
     *
     * @param boolean $onlyChanged
     *
     * @return array
     */
    
public function toRawArray(bool $onlyChanged false): array
    {
        
$array parent::toRawArray($onlyChanged);
        
        if (empty(
$this->casts))
        {
            return 
$array;
        }

        
// Check each key for a cast
        
foreach ($array as $key => $value)
        {
            if (! empty(
$this->casts[$key]))
            {
                
$array[$key] = $this->castAs($value$this->casts[$key]);
            }
        }

        return 
$array;
    } 
Reply


Messages In This Thread
Entity cast-on-fill - by MGatner - 04-14-2020, 10:40 AM
RE: Entity cast-on-fill - by kilishan - 04-14-2020, 10:54 AM
RE: Entity cast-on-fill - by MGatner - 04-14-2020, 11:01 AM
RE: Entity cast-on-fill - by kilishan - 04-14-2020, 11:16 AM



Theme © iAndrew 2016 - Forum software by © MyBB