Get the Content Entity of current route

use Drupal\Core\Entity\ContentEntityInterface;

/**
 * Get Entity for the current route.
 */
function getCurrentRouteEntity(): ?ContentEntityInterface {
  $currentRoute = \Drupal::routeMatch();
  if (($routeObj = $currentRoute->getRouteObject()) && ($parameters = $routeObj->getOption('parameters'))) {
    foreach ($parameters as $name => $options) {
      if (isset($options['type']) && strtok($options['type'], ':') === 'entity') {
        $entity = $currentRoute->getParameter($name);
        if ($entity instanceof ContentEntityInterface && $entity->hasLinkTemplate('canonical')) {
          return $entity;
        }
      }
    }
  }
  return NULL;
}
********************************** ************************* ************************ **************** ****************** *********** ************** ************* ************ *************