timber icon indicating copy to clipboard operation
timber copied to clipboard

Timber 2.x - ImageHelper::theme_url_to_dir() returns an invalid path when theme template is theme-name/theme

Open Moustachos opened this issue 4 years ago • 0 comments

First, thanks for your great work on this project :)

Expected behavior

Path returned by ImageHelper::theme_url_to_dir() (https://github.com/timber/timber/blob/master/lib/ImageHelper.php#L445) should be consistent (always returning a file path), regardless of theme files structure.

In ImageHelper::theme_url_to_dir(), we should check if get_stylesheet() contains a / and only return what comes before the / when that's the case.

That way, $site_root won't contain /theme and theme url will properly be removed from $src.

Actual behavior

My theme has the following structure : -- my-theme-name/ --- theme/ ---- functions.php ---- style.css --- images/ ---- my-image.png

So my theme template is my-theme-name/theme and that's the value returned by get_stylesheet().

The problem is that in ImageHelper::theme_url_to_dir(), we use that to build $site_root variable, and $site_root ends with /theme (because of get_stylesheet()). But in $src, there's no /theme (because images are stored in my-theme-name/images/), so the following code fails to replace $site_root from url: $tmp = str_replace($site_root, '', $src);

And I end up with errors in my logs whenever I try to use any Twig filter (like |webp) on a theme image: [25-May-2021 14:20:37 UTC] [ Timber ] Error loading /[...]/themes/my-theme-name/themehttps://[...]/themes/my-theme-name/build/images/my-image.png

The /theme shouldn't be here.

Steps to reproduce behavior

  • create a new theme with above files structure (taken from Starter theme 2.x: https://github.com/timber/starter-theme/tree/2.x)
  • add a theme image in theme-name/images/
  • load this image inside a Twig file and try to apply any image filter causing Timber to create a new image (like |webp)
  • new image can't be created, because ImageHelper::theme_url_to_dir() fails to replace theme url from image $src
  • see errors in PHP log

What version of WordPress, PHP and Timber are you using?

WordPress 5.7.2, PHP 7.4, Timber 2.0-dev.

How did you install Timber? (for example, from GitHub, Composer/Packagist, WP.org?)

Through Composer.

Moustachos avatar May 25 '21 14:05 Moustachos