How can you get the bundle's name from an entity?
is there any function or service to get this?
$artist = new Artist();
$bundleName = artist->getBundleName();
echo $bundleName
myCompanyArtistBundle
I prefer this solution :
/**
* Get the bundle name from an Entity namespace
*
* @return string
* @author lenybernard
**/
protected static function getBundleNameFromEntity($entityNamespace, $bundles)
{
$dataBaseNamespace = substr($entityNamespace, 0, strpos($entityNamespace, '\\Entity\\'));
foreach ($bundles as $type => $bundle) {
$bundleRefClass = new \ReflectionClass($bundle);
if ($bundleRefClass->getNamespaceName() === $dataBaseNamespace) {
return $type;
}
}
}
Nota bene : the $bundles
variable is the result of calling the getBundles() method on the kernel
service.
I found a solution but don't know if it's a good one :
<?php
$rootEntityName = "company\myNamespace\Entity\user";
$bundles = $context->get('kernel')->getBundles();
$bundleName = '';
foreach($bundles as $type=>$bundle){
$className = get_class($bundle);
$entityClass = substr($rootEntityName,0,strpos($rootEntityName,'\\Entity\\'));
if(strpos($className,$entityClass)=== FALSE){
echo get_class($bundle).'<br>';
echo $type.'<br>';
}else{
$bundleName = $type;
}
}
echo $bundleName;