Skip to content
This repository was archived by the owner on Dec 11, 2025. It is now read-only.

Commit 824b0ee

Browse files
fix: Ensure Options class can accept associative array values
1 parent dd2cc0d commit 824b0ee

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

README.md

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,13 +35,30 @@ echo $options;
3535

3636
### Alternative Initialization
3737

38+
It is possible to initialize the Options object with an associative array. The keys of the array are the option names and the values are the option values.
39+
40+
The values can either be a single value, an array of values, or an associative array of values.
41+
42+
- When a single value is used, it is passed as the first argument to the setter method.
43+
- When an array of values is used, they are destructured as passed as arguments in order to the setter method.
44+
- When an associative array is used, the key/value pairs are destructured and passed in as named arguments to the setter method.
45+
3846
```php
3947
// Create Options object with array of values
4048
$options = new Options([
4149
'width' => 300,
4250
'height' => 400,
43-
'resizingType' => 'fill',
51+
'resize' => [
52+
'width' => 300,
53+
'height' => 400,
54+
'enlarge' => false,
55+
'resize_type' => 'fill',
56+
],
4457
'gravity' => 'sm',
58+
'png_options' => [
59+
'interlaced' => true,
60+
'quantize' => false,
61+
],
4562
]);
4663
```
4764

@@ -55,6 +72,13 @@ use fostercommerce\imgproxy\UrlBuilder;
5572
$options = new Options();
5673
$options->setPreset('sharp')
5774
->setResize('fill', 300, 400, false)
75+
// or
76+
->setResize([
77+
'width' => 300,
78+
'height' => 400,
79+
'enlarge' => false,
80+
'resize_type' => 'fill',
81+
])
5882
->setGravity('sm')
5983
->setQuality(80)
6084
->setFormat('png');

src/Options.php

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,11 @@ class Options implements \Stringable
2727
public function __construct(array $options = [])
2828
{
2929
foreach ($options as $option => $value) {
30-
$method = 'set' . ucfirst($option);
30+
$method = 'set' . $this->toPascalCase($option);
3131
if (method_exists($this, $method)) {
32-
$this->{$method}($value);
32+
// We want to make sure that we can set the individual arguments from an associative array or a regular array.
33+
$args = is_array($value) ? $value : [$value];
34+
$this->{$method}(...$args);
3335
}
3436
}
3537
}
@@ -1875,4 +1877,9 @@ protected function formatValue(mixed $value): string
18751877

18761878
return '';
18771879
}
1880+
1881+
private function toPascalCase(string $input): string
1882+
{
1883+
return ucfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $input))));
1884+
}
18781885
}

0 commit comments

Comments
 (0)