Skip to content

Commit

Permalink
Merge pull request #1 from sanderjongsma/master
Browse files Browse the repository at this point in the history
fix: use reflection to cast arguments
  • Loading branch information
peterjaap authored Nov 29, 2024
2 parents 7d7a1c0 + ba774b5 commit ac02fd7
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 12 deletions.
31 changes: 19 additions & 12 deletions src/Model/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Elgentos\Imgproxy\Service\Curl;
use Exception;
use Imgproxy\OptionSet;
use Imgproxy\UrlBuilder;
use Magento\Store\Model\Store;
use Magento\Store\Model\StoreManagerInterface;
Expand Down Expand Up @@ -78,13 +79,15 @@ public function getCustomUrl(
if ($customProcessingOptions) {
$options = array_map('trim', explode('/', $customProcessingOptions));
foreach ($options as $option) {
$arguments = $this->convertCustomProcessingOptionsToInt(explode(':', $option));
$arguments = explode(':', $option);
$method = sprintf('with%s', array_shift($arguments));

$name = array_shift($arguments);
$reflectionClass = new \ReflectionClass($url->options());
if (! $reflectionClass->hasMethod($method)) {
continue;
}

// @todo We need to use reflection here
$method = sprintf('with%s', $name);
$url->options()->{$method}(...$arguments);
$url->options()->{$method}(...$this->castArguments($url->options(), $method, $arguments));
}
}

Expand All @@ -102,14 +105,18 @@ public function getCustomUrl(
return $imgProxyUrl;
}

private function convertCustomProcessingOptionsToInt(array $arguments): array
private function castArguments(OptionSet $class, string $methodName, array $arguments): array
{
foreach ($arguments as $key => $value) {
if (is_numeric($value) && ctype_digit($value)) {
$arguments[$key] = (int)$value;
$reflectionMethod = new \ReflectionMethod($class, $methodName);
$parameters = $reflectionMethod->getParameters();

return array_map(function($parameter, $argument) {
$paramType = $parameter->getType();
if ($paramType) {
$typeName = $paramType->getName();

Check failure on line 116 in src/Model/Image.php

View workflow job for this annotation

GitHub Actions / GrumPHP

Call to an undefined method ReflectionType::getName().
settype($argument, $typeName);
}
}

return $arguments;
return $argument;
}, $parameters, $arguments);
}
}
21 changes: 21 additions & 0 deletions src/ViewModel/Imgproxy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

namespace Elgentos\Imgproxy\ViewModel;

use Elgentos\Imgproxy\Model\Image;
use Magento\Framework\View\Element\Block\ArgumentInterface;

class Imgproxy implements ArgumentInterface
{
public function __construct(
private readonly Image $image,
) {
}

public function getCustomUrl(string $currentUrl, int $width, int $height): string
{
return $this->image->getCustomUrl($currentUrl, $width, $height);
}
}

0 comments on commit ac02fd7

Please sign in to comment.