DeletionService.php (2419B)
1 <?php 2 /** 3 * Created by PhpStorm. 4 * User: felicitus 5 * Date: 10/25/17 6 * Time: 5:38 PM. 7 */ 8 9 namespace PartKeepr\DoctrineReflectionBundle\Services; 10 11 use Doctrine\ORM\EntityManager; 12 use Doctrine\ORM\Mapping\ClassMetadata; 13 14 class DeletionService 15 { 16 /** 17 * @var EntityManager 18 */ 19 private $em; 20 21 public function __construct(EntityManager $entityManager) 22 { 23 $this->em = $entityManager; 24 } 25 26 public function findUndeletableUsages($entity) 27 { 28 $realClassName = $this->em->getClassMetadata(get_class($entity))->name; 29 30 $meta = $this->em->getMetadataFactory()->getAllMetadata(); 31 $sourceEntityMetaData = $this->getAllMetadataInfoFor($realClassName); 32 33 $usedIn = []; 34 35 foreach ($meta as $foo) { 36 /* @var ClassMetadata $foo */ 37 foreach ($foo->getAssociationMappings() as $associationMapping) { 38 if ($associationMapping["targetEntity"] === $realClassName && $associationMapping["isOwningSide"]) { 39 40 //var_dump($associationMapping-> 41 if ($associationMapping["inversedBy"] !== null) { 42 $inverseAssociationMapping = $sourceEntityMetaData->getAssociationMapping($associationMapping["inversedBy"]); 43 44 if ($inverseAssociationMapping["isCascadeRemove"]) { 45 continue; 46 } 47 } 48 49 $qb = $this->em->createQueryBuilder(); 50 $qb->select("q")->from($associationMapping["sourceEntity"], "q")->where( 51 $qb->expr()->eq("q.".$associationMapping["fieldName"], ":query") 52 ); 53 54 $qb->setParameter(":query", $entity); 55 56 foreach ($qb->getQuery()->getResult() as $result) { 57 $usedIn[] = (string) $result; 58 } 59 } 60 } 61 } 62 63 return $usedIn; 64 } 65 66 /** 67 * @param $className 68 * 69 * @return ClassMetadata|null 70 */ 71 protected function getAllMetadataInfoFor($className) 72 { 73 $data = $this->em->getMetadataFactory()->getAllMetadata(); 74 75 foreach ($data as $info) { 76 /** 77 * @var ClassMetadata $info 78 */ 79 if ($info->getName() == $className) { 80 return $info; 81 } 82 } 83 84 return null; 85 } 86 }