2013-12-16 3 views
1

У меня есть некоторые логики, которые я недавно собрал вместе, и теперь мне нужно сделать их обобщенными, чтобы искать родителя на бесконечном числе родительских уровней. Каким будет наиболее эффективный способ структурирования этого кода как цикла вместо моих спагетти-гнезд?конденсировать логику в цикле

public function hasAccess($user,$container) 
{ 

    //If user is admin 
    $roles = $user->getRoles(); 
    foreach ($roles as $role) { 
     if ($role == 'ROLE_ADMIN') { 
      return true; 
     }  
    }; 

    //Or if user has access to object 
    foreach ($container->getUsers() as $userWithAccess) { 
     if ($userWithAccess == $user) { 
      return true; 
     } 
    } 

    //Or if object has parent and user has access to the parent 
    $parent = $container->getParent(); 
    if ($parent) { 
     foreach ($parent->getUsers() as $userWithAccess) { 
      if ($userWithAccess == $user) { 
       return true; 
      } 
     } 
    } 

    //Or if object has grandparent and user has access to the grandparent 
    $parent = $container->getParent(); 
    if ($parent) { 
     $grandparent = $parent->getParent(); 
     if ($grandparent) {   
      foreach ($grandparent->getUsers() as $userWithAccess) { 
       if ($userWithAccess == $user) { 
        return true; 
       } 
      } 
     } 
    }  

    //Or if object has greatgrandparent (=entire company access) and user has access to the greatgrandparent ('entire company') 
    $parent = $container->getParent(); 
    if ($parent) { 
     $grandparent = $parent->getParent(); 
     if ($grandparent) { 
      $greatgrandparent = $grandparent->getParent(); 
       if ($greatgrandparent) {       
       foreach ($greatgrandparent->getUsers() as $userWithAccess) { 
        if ($userWithAccess == $user) { 
         return true; 
        } 
       } 
      } 
     } 
    } 

    //Or if object has greatgreatgrandparent (=entire company if this content lives within a module, otherwise this level doesn't exist) and user has access to the greatgreatgrandparent (ie entire company) 
    $parent = $container->getParent(); 
    if ($parent) { 
     $grandparent = $parent->getParent(); 
     if ($grandparent) { 
      $greatgrandparent = $grandparent->getParent(); 
      if ($greatgrandparent) { 
       $greatgreatgrandparent = $greatgrandparent->getParent();       
       if ($greatgreatgrandparent) {      
        foreach ($greatgreatgrandparent->getUsers() as $userWithAccess) { 
         if ($userWithAccess == $user) { 
          return true; 
         } 
        } 
       } 
      } 
     } 
    }   

    //At the moment, access to 'entire company' does NOT grant access to monitors outside the hierarchy. 
    //It is still possible to add privileges to those individual monitors. 


    //If none of the above has matched... 
    return false; 

} 
+1

вау тха ts кролик уоррен. Посмотрите, что саморекурсия должна делать то, что вы хотите :) – Dave

+0

прочитайте эти самые, которые можно изменить, чтобы сделать то, что вы хотите http://stackoverflow.com/questions/4627208/php-object-parent-child-recursion http: // stackoverflow. com/questions/11990531/a-recursive-function-to-sort-through-parent-and-child-nodes-in-php-use-a-forea http://stackoverflow.com/questions/18234510/php-recursive -function-to-display-family-tree-with-parents-and-partners Это поток, который я изначально искал и не мог найти http://stackoverflow.com/questions/10729211/recursive-function-inside- класс-с-foreach-changes-public-value-where-it-shoul – Dave

ответ

1

Может быть петля, а что проверяет наличие $parent, проверка доступа для всех из них пользователи затем сделать $parent родителя текущего. Что-то вроде этого:

$parent = $container->getParent(); 
while ($parent) { 
    foreach ($parent->getUsers() as $userWithAccess) { 
    if ($userWithAccess == $user) { 
     return true; 
    } 
    } 
    $parent = $parent->getParent(); 
} 
+0

спасибо, кажется, только то, что мне нужно, просто возьму его за спину ... –

1

Если вы пытаетесь получить предка, используя while может помочь:

$ancestor = $parent; 
while($parent = $ancestor->getParent()) 
    $ancestor = $parent; 

// foreach($ancestor->getUsers() ... 

Чтобы получить 4-го родителя, просто добавьте переменную-счетчик и разорвать петлю, если $counter > 4

Кроме того, вы могли бы использовать in_array(), чтобы избежать всех этих заявлений Foreach (если методы прибудете * возвращают массивы)

Смежные вопросы