drago-ex / gravatar
Simple and customizable Gravatar integration for PHP applications, allowing easy Gravatar image generation based on user email with options for size, default image, and rating.
Requires
- php: >=8.3 <9
- nette/application: ^3.2
- nette/di: ^3.2
- nette/utils: ^4.0
Requires (Dev)
- nette/bootstrap: ^3.2
- nette/tester: ^2.5
- phpstan/phpstan-nette: ^2.0
- tracy/tracy: ^2.10
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Simple and customizable Gravatar integration for PHP applications.
Requirements
- PHP >= 8.3, < 9
- Nette Framework
- Composer
Installation
composer require drago-ex/gravatar
Extension Registration
After installation, register the extension in your Nette configuration (neon file):
extensions: gravatar: Drago\Gravatar\DI\GravatarExtension
Optional configuration
gravatar: size: 80 defaultImage: "mm" rating: "g"
You can adjust the size, defaultImage, and rating parameters based on your needs.
Overview
Drago Gravatar generates Gravatar image URLs from user email addresses, with a configurable size, default image and rating.
Usage in Services and Templates
Inject Drago\Gravatar\Gravatar and call getUrl(). It does not change the state of the shared
service, so it is safe for lists of several users:
$url = $this->gravatar->getUrl('someone@somewhere.com'); $small = $this->gravatar->getUrl('someone@somewhere.com', 40);
Using Gravatar in Presenters
The GravatarAdapter trait passes the URL to the template as $gravatar when the presenter sets an email:
use Drago\Gravatar\GravatarAdapter; use Nette\Application\UI\Presenter; final class ProfilePresenter extends Presenter { use GravatarAdapter; protected function beforeRender(): void { parent::beforeRender(); // a guest has no identity, so no avatar $email = $this->getUser()->getIdentity()?->email; if (is_string($email)) { $this->gravatar->setEmail($email); } } }
When no email is set, the variable is not passed and rendering continues normally. With a typed template class, declare the property:
public string $gravatar;
In Template
<img n:if="isset($gravatar)" src="{$gravatar}" alt="">
Options
size: image size in pixels, 1 to 2048. Default is80.setSize()changes it only for the service, not the configuration.defaultImage: image used when the user has no Gravatar, for examplemm,identicon,monsterid,wavatar, or a URL of your own image. Default ismm. Values are URL-encoded.rating: maximum rating, one ofg,pg,r,x. Default isg. Other values throwInvalidArgumentException.
The email is trimmed, lowercased and hashed with SHA-256, as Gravatar documents.
Invalid emails throw Drago\Gravatar\EmailException, invalid sizes Drago\Gravatar\SizeException.
getGravatar() throws EmailException when setEmail() has not been called.