1

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

martin
  • 93,354
  • 25
  • 191
  • 226
Chopchop
  • 2,899
  • 18
  • 36

2 Answers2

0

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.

lenybernard
  • 2,399
  • 22
  • 22
0

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;
Magentron
  • 376
  • 2
  • 10
Chopchop
  • 2,899
  • 18
  • 36