Extending¶
The module has no hooks or events of its own and no aspect_ratio.api.php. Custom code can use its service and batch class.
The calculator service¶
aspect_ratio.calculator (class Drupal\aspect_ratio\AspectRatioCalculator, also available for autowiring by that class name).
| Method | What it does |
|---|---|
calculate(MediaInterface $media, bool $force = FALSE): bool |
Sets field_aspect_ratio on the media item without saving it. Without $force, it does nothing when the item already has a value and its source file is unchanged. With $force, it reads the dimensions from the file. Returns TRUE if the value changed. |
getRatio(MediaInterface $media, bool $read_file = FALSE): ?float |
Returns width รท height of the item's source image, unrounded, or NULL when the source is not an image. |
getBundles(): array |
The IDs of the media types that have field_aspect_ratio. |
countMedia(): int |
The number of media items of those types, without an access check. |
The field name is available as AspectRatioCalculator::FIELD_NAME.
Recalculate one item from custom code:
$calculator = \Drupal::service('aspect_ratio.calculator');
if ($calculator->calculate($media, TRUE)) {
$media->save();
}
The batch¶
Drupal\aspect_ratio\AspectRatioBatch::build() returns the same batch the Calculate Aspect Ratios form runs. Use it from a Drush command or a deploy hook:
Hook implementations¶
The module implements hook_media_presave() in Drupal\aspect_ratio\Hook\AspectRatioHooks::mediaPresave(). On Drupal before 11.1, the aspect_ratio_media_presave() function in aspect_ratio.module calls it.
A module that needs to change the ratio after it is calculated can implement hook_media_presave() and run after this module.
Deprecated functions¶
These procedural functions remain as wrappers and will be removed in 2.0.0:
| Function | Replacement |
|---|---|
aspect_ratio_calculate($media) |
\Drupal::service('aspect_ratio.calculator')->calculate($media) |
aspect_ratio_calculate_and_save($media) |
calculate($media, TRUE), then $media->save() |
aspect_ratio_calculate_and_save_by_id($media_id) |
AspectRatioBatch |