mardi 27 février 2018

Variable properties on a variable method

I'm using a third-party package which manipulates images. For basic conversions it accepts a single value:

$image = $this->addMediaConversion('thumb');
$image->width(100);
$image->height(100);

The system I am building has a level of abstraction where I need to define these values from within a config file. I load the config file in as an array. I can then loop through the values in the config file and generate my various conversions.

My config file:

return [
  'thumb' => [
    'width' => 100,
    'height' => 100,
  ],
];

The code to define these conversions from that config:

$definitions = config('definitions');

foreach($definitions as $name => $keys) {
  $image = $this->addMediaConversion($name);

  foreach($keys as $key => $value) {
    $image->$key($value);
  }
}

This works fine for SINGLE values.

However, the package has methods that take multiple properties against a method, for example:

$image = $this->addMediaConversion('thumb');
$image->fit(Manipulations::FIT_FILL, 560, 560);

There are various methods available that have various different acceptable attributes. I'm looking for an *ELEGANT* solution to this. I am able to achieve it by having an array of values in my config file, checking the type, checking the length of that array, and then passing the correct number, but this isn't scalable, easily maintainable nor elegant.

Config:

return [
  'thumb' => [
    'fit' => [Manipulations::FIT_FILL, 560, 560]
  ]
];

Code:

foreach($image_definitions as $name => $keys) {
  // Generate the conversion
  $conversion = $this->addMediaConversion($name);
  // Loop through and define the attributes as they are in the config, things like ->width(), ->height()
  foreach($keys as $key => $value) {
    if(is_array($value))
    {
      // LOOKING FOR A MORE ELEGANT WAY TO DO THE BELOW
      switch(count($value)) 
      {
        case 2:
          $conversion->$key($value[0], $value[1]);
          break;
        case 3:
          $conversion->$key($value[0], $value[1], $value[2]);
          break;
        case 4:
          $conversion->$key($value[0], $value[1], $value[2], $value[3]);
          break;
        case 5:
          $conversion->$key($value[0], $value[1], $value[2], $value[3], $value[4]);
          break;
        case 6:
          $conversion->$key($value[0], $value[1], $value[2], $value[3], $value[4], $value[5]);
          break;
      }
    } else 
    {
      $conversion->$key($value);
    }                
  }
}

What's the best and most elegant solution for this?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire