Álvaro González
Álvaro González

Reputation: 146460

File system path for images

I'm writing a custom helper that extends HtmlHelper and overriding the \HtmlHelper::image() method to calculate the image dimensions and add them as HTML attributes. What I have so far works fine for regular pictures:

public function image($path, $options = array()) {
    if (!array_key_exists('width', $options) && !array_key_exists('height', $options)) {
        $stamp = Configure::read('Asset.timestamp');
        Configure::write('Asset.timestamp', false);

        $path = $this->assetUrl($path, $options + array('pathPrefix' => Configure::read('App.imageBaseUrl')));
        list($width, $height) = @getimagesize(rtrim(WWW_ROOT, '\\/') . $path);
        if (!is_null($width)) {
            $options['width'] = $width;
        }
        if (!is_null($height)) {
            $options['height'] = $height;
        }

        Configure::write('Asset.timestamp', $stamp);
    }
    return parent::image($path, $options);
}

… but has these flaws:

I've been looking for a builtin method to convert a CakePHP picture URL (in any format accepted by \HtmlHelper::image() into a file system path (o something like null when doesn't apply) but I couldn't find any. Native features that need a disk path, such as \Helper::assetTimestamp() are wrapped in tons of non-reusable code.

Is there an elegant solution?

Upvotes: 1

Views: 511

Answers (2)

ndm
ndm

Reputation: 60463

I'd say that there are pretty much only 3 options:

  • Submit a patch to add asset filesystem path retrieval functionality to the core.
  • Copy a lot of code from the helper (assetUrl(), webroot(), and assetTimestamp()).
  • Use web requests for local URLs (ideally combined with caching).

Upvotes: 1

Daljeet Singh
Daljeet Singh

Reputation: 714

Try using DS rather than using \ or /, they sometime can cause problems with the OS. DS is directory separator provided by cakephp Short for PHP’s DIRECTORY_SEPARATOR, which is / on Linux and \ on Windows. Check the doc

Upvotes: 0

Related Questions