From f69cd151ca75aff8bd8eee409fdf0c80f2c81109 Mon Sep 17 00:00:00 2001
From: pbarroca <pbarroca@afi-sa.fr>
Date: Mon, 23 Jan 2017 19:29:35 +0100
Subject: [PATCH] dev #53936 : apply to selected profiles limited to library

---
 library/Class/Profil.php                      |  15 ++
 library/Class/Profil/ModuleDefinition.php     |  23 ++-
 .../ZendAfi/Controller/Action/Helper/View.php |   2 +-
 .../ZendAfi/View/Helper/TagListeCoches.php    | 169 ++++++++++++------
 .../controllers/ModulesControllerTest.php     |  11 +-
 5 files changed, 151 insertions(+), 69 deletions(-)

diff --git a/library/Class/Profil.php b/library/Class/Profil.php
index a37db03e721..05a50f5e37b 100644
--- a/library/Class/Profil.php
+++ b/library/Class/Profil.php
@@ -87,6 +87,21 @@ class ProfilLoader extends Storm_Model_Loader {
   }
 
 
+  public function findTopForUser($user) {
+    if (!$user)
+      return [];
+
+    return ($user->isRoleLibraryLimited() && ($library = $user->getBib()))
+      ? Class_Profil::findTopForLibrary($library)
+      : Class_Profil::findTopProfils();
+  }
+
+
+  public function findTopForCurrentUser() {
+    return Class_Profil::findTopForUser(Class_Users::getIdentity());
+  }
+
+
   public function getRoot() {
     return isset($this->_root)
       ? $this->_root
diff --git a/library/Class/Profil/ModuleDefinition.php b/library/Class/Profil/ModuleDefinition.php
index 859820d1ce6..69763fb20b2 100644
--- a/library/Class/Profil/ModuleDefinition.php
+++ b/library/Class/Profil/ModuleDefinition.php
@@ -32,13 +32,17 @@ class Class_Profil_ModuleDefinition extends Class_Entity {
 
   public function getApplyToForm($url) {
     $form = ZendAfi_Form::newWithOptions(['action' => $url])
-      ->addElement('checkbox', 'all_profiles',
-                   ['label' => $this->_('Appliquer le paramétrage de cet écran à tous les profils que j\'administre ?')]);
+      ->addElement('cochesSuggestion', 'profiles',
+                   ['label' => $this->_('Au(x) profil(s)'),
+                    'SelectedAllMeansNothing' => false,
+                    'rubrique' => 'profile',
+                    'name' => 'profiles',
+                    'value' => Class_Profil::getCurrentProfil()->getId()]);
 
     if ('recherche' == $this->getController()
         && 'viewnotice' == $this->getAction())
       $form->addElement('cochesSuggestion', 'doc_types',
-                        ['label' => $this->_('Appliquer le paramétrage au(x) type(s) de document'),
+                        ['label' => $this->_('Au(x) type(s) de document'),
                          'SelectedAllMeansNothing' => false,
                          'rubrique' => 'type_doc',
                          'name' => 'doc_types',
@@ -55,11 +59,14 @@ class Class_Profil_ModuleDefinition extends Class_Entity {
   public function handleApplyToForm($form) {
     $profiles = [];
 
-    if ($form->getValue('all_profiles')) {
-      $user = Class_Users::getIdentity();
-      $profiles = ($user->isRoleLibraryLimited() && ($library = $user->getBib()))
-        ? Class_Profil::findTopForLibrary($library)
-        : Class_Profil::findTopProfils();
+    if ($profile_ids = $form->getValue('profiles')) {
+      $availables = Class_Profil::findTopForCurrentUser();
+      $profile_ids = explode(';', $profile_ids);
+      $profiles = array_filter(
+                               $availables,
+                               function($profile) use ($profile_ids) {
+                                 return in_array($profile->getId(), $profile_ids);
+                               });
 
       (new Class_Profil_Preferences())
         ->batchApplyModulePref(Class_Profil::getCurrentProfil(), $profiles, $this);
diff --git a/library/ZendAfi/Controller/Action/Helper/View.php b/library/ZendAfi/Controller/Action/Helper/View.php
index ac9eba74434..bdeb124e8cb 100644
--- a/library/ZendAfi/Controller/Action/Helper/View.php
+++ b/library/ZendAfi/Controller/Action/Helper/View.php
@@ -76,7 +76,7 @@ class ZendAfi_Controller_Action_Helper_View extends Zend_View {
 
     if (file_exists($template)) {
       $html = file_get_contents($template);
-      $blocs = '';
+      $blocs = [];
       // Interpretation des IF-xxx
       $pos_fin = 0;
       while (true) {
diff --git a/library/ZendAfi/View/Helper/TagListeCoches.php b/library/ZendAfi/View/Helper/TagListeCoches.php
index 52c1c33c582..83760f3d6dc 100644
--- a/library/ZendAfi/View/Helper/TagListeCoches.php
+++ b/library/ZendAfi/View/Helper/TagListeCoches.php
@@ -39,25 +39,21 @@ class ZendAfi_View_Helper_TagListeCoches extends ZendAfi_View_Helper_BaseHelper
 
 
   public function tagListeCoches($rubrique, $name, $valeurs='', $id_bib=0) {
-    $rubriques = ['type_doc' => ['model' => 'Class_TypeDoc'],
+    $rubriques =
+      ['type_doc' => new ZendAfi_View_Helper_TagListeCochesSourceDocType(),
+       'section' => $this->_simpleSourceFor('Class_CodifSection'),
+       'genre' => $this->_simpleSourceFor('Class_CodifGenre'),
+       'langue' => $this->_simpleSourceFor('Class_CodifLangue'),
+       'emplacement' => $this->_simpleSourceFor('Class_CodifEmplacement'),
+       'nature_doc' => $this->_simpleSourceFor('Class_NatureDoc'),
 
-                  'section' => ['model' => 'Class_CodifSection'],
+       'bibliotheque' => $this->_simpleSourceFor('Class_Bib')->setWhere(['visibilite' => '2']),
 
-                  'genre' => ['model' => 'Class_CodifGenre'],
+       'annexe' => (new ZendAfi_View_Helper_TagListeCochesSourceAnnexe())->setWhere(array_filter(['id_bib' => $id_bib,
+                                                                                                  'invisible' => 0])),
 
-                  'langue' => ['model' => 'Class_CodifLangue'],
-
-                  'bibliotheque' => ['model' => 'Class_Bib',
-                                     'where' => ['visibilite' => '2']],
-
-                  'emplacement' => ['model' => 'Class_CodifEmplacement'],
-
-                  'nature_doc' => ['model' => 'Class_NatureDoc'],
-
-                  'annexe' => ['id' => 'code',
-                               'model' => 'Class_CodifAnnexe',
-                               'where' => array_filter(['id_bib' => $id_bib,
-                                                        'invisible' => 0])]];
+       'profile' => new ZendAfi_View_Helper_TagListeCochesSourceProfile()
+      ];
 
     if (!array_key_exists($rubrique, $rubriques))
       return '';
@@ -66,7 +62,7 @@ class ZendAfi_View_Helper_TagListeCoches extends ZendAfi_View_Helper_BaseHelper
     $this->_type = $rubrique;
     Class_ScriptLoader::getInstance()->addAdminScript('tag_selection');
     $this->_definition = $rubriques[$rubrique];
-    $this->_possibles = $this->_getList();
+    $this->_possibles = $this->_definition->getList();
     $this->_cant_select_all = $this->selected_all_means_nothing ? 'true' : 'false';
 
     $this->_handleValues($valeurs);
@@ -78,6 +74,11 @@ class ZendAfi_View_Helper_TagListeCoches extends ZendAfi_View_Helper_BaseHelper
   }
 
 
+  protected function _simpleSourceFor($model) {
+    return new ZendAfi_View_Helper_TagListeCochesSource($model);
+  }
+
+
   protected function _renderValues() {
     return $this->view->formHidden($this->_name, implode(';', $this->_filtred_codes));
   }
@@ -152,43 +153,6 @@ class ZendAfi_View_Helper_TagListeCoches extends ZendAfi_View_Helper_BaseHelper
   }
 
 
-  protected function _getList() {
-    $instances = $this->_getInstances();
-    if ('type_doc' == $this->_type)
-      usort($instances,
-            function($a, $b)
-            {
-              return strtolower($a->getLabel()) > strtolower($b->getLabel());
-            });
-
-
-
-    $list = [];
-    foreach($instances as $instance) {
-      $key = $instance
-        ->callGetterByAttributeName($this->_getDefinitionOr('id', 'id'));
-      $list[$key] = $instance->getLibelle();
-    }
-
-    return $list;
-  }
-
-
-  protected function _getInstances() {
-    $filter = $this->_getDefinitionOr('where', []);
-    $filter['order'] = 'libelle';
-
-    return call_user_func([$this->_definition['model'], 'findAllBy'], $filter);
-  }
-
-
-  protected function _getDefinitionOr($name, $default) {
-    return isset($this->_definition[$name])
-      ? $this->_definition[$name]
-      : $default;
-  }
-
-
   protected function _handleValues($values) {
     $this->_selection = '';
     $this->_coche = [];
@@ -215,4 +179,101 @@ class ZendAfi_View_Helper_TagListeCoches extends ZendAfi_View_Helper_BaseHelper
 
     return $this;
   }
+}
+
+
+
+class ZendAfi_View_Helper_TagListeCochesSource extends Class_Entity {
+  public function __construct($model) {
+    $this->setModel($model);
+  }
+
+
+  public function getList() {
+    $list = [];
+    foreach($this->getInstances() as $instance)
+      $list[$this->getKey($instance)] = $this->getLabel($instance);
+
+    return $list;
+  }
+
+
+  protected function getKey($instance) {
+    return $instance->getId();
+  }
+
+
+  protected function getLabel($instance) {
+    return $instance->getLibelle();
+  }
+
+
+  protected function getInstances() {
+    $filter = ($where = $this->getWhere()) ? $where : [];
+    $filter['order'] = 'libelle';
+
+    return call_user_func([$this->getModel('model'), 'findAllBy'], $filter);
+  }
+}
+
+
+
+class ZendAfi_View_Helper_TagListeCochesSourceDocType extends ZendAfi_View_Helper_TagListeCochesSource {
+  public function __construct() {
+    parent::__construct('Class_TypeDoc');
+  }
+
+
+  protected function getInstances() {
+    $instances = parent::getInstances();
+    usort($instances,
+          function($a, $b)
+          {
+            return strtolower($a->getLabel()) > strtolower($b->getLabel());
+          });
+
+    return $instances;
+  }
+
+}
+
+
+
+class ZendAfi_View_Helper_TagListeCochesSourceProfile extends ZendAfi_View_Helper_TagListeCochesSource {
+  use Trait_Translator;
+
+  public function __construct() {
+    parent::__construct('Class_Profil');
+  }
+
+
+  protected function getInstances() {
+    $instances = Class_Profil::findTopForCurrentUser();
+    usort($instances,
+          function($a, $b)
+          {
+            return $this->getLabel($a) > $this->getLabel($b);
+          });
+
+    return $instances;
+  }
+
+
+  protected function getLabel($instance) {
+    return (($bib = $instance->getBib()) ? $bib->getLibelle() : $this->_('Portail'))
+      . ' : ' . $instance->getLibelle();
+  }
+}
+
+
+
+class ZendAfi_View_Helper_TagListeCochesSourceAnnexe extends ZendAfi_View_Helper_TagListeCochesSource {
+  public function __construct() {
+    parent::__construct('Class_CodifAnnexe');
+  }
+
+
+  protected function getKey($instance) {
+    return $instance->getCode();
+  }
 }
\ No newline at end of file
diff --git a/tests/application/modules/admin/controllers/ModulesControllerTest.php b/tests/application/modules/admin/controllers/ModulesControllerTest.php
index 4fb7b1a967e..024aeb06569 100644
--- a/tests/application/modules/admin/controllers/ModulesControllerTest.php
+++ b/tests/application/modules/admin/controllers/ModulesControllerTest.php
@@ -1179,8 +1179,8 @@ class ModulesControllerContactApplyToActionTest extends Admin_AbstractController
 
   /** @test */
   public function applyToAllProfilChoiceShouldBePresent() {
-    $this->assertXPathContentContains('//label[@for="all_profiles"]',
-                                      'Appliquer le paramétrage de cet écran à tous les profils que j\'administre');
+    $this->assertXPathContentContains('//label[@for="profiles"]',
+                                      'Au(x) profil(s)');
   }
 
 
@@ -1210,8 +1210,7 @@ class ModulesControllerNoticeApplyToActionTest extends Admin_AbstractControllerT
 
   /** @test */
   public function applyToAllProfilChoiceShouldBePresent() {
-    $this->assertXPathContentContains('//label[@for="all_profiles"]',
-                                      'Appliquer le paramétrage de cet écran à tous les profils que j\'administre');
+    $this->assertXPathContentContains('//label[@for="profiles"]', 'Au(x) profil(s)');
   }
 
 
@@ -1313,7 +1312,7 @@ abstract class ModulesControllerContactApplyToActionPostTestCase
     parent::setUp();
 
     $this->postDispatch($this->_getDispatchUrl(),
-                        ['all_profiles' => 1]);
+                        ['profiles' => '2;44']);
   }
 
   protected function _prepare_fixtures() {
@@ -1388,7 +1387,7 @@ class ModulesControllerNoticeApplyToActionPostTestCase
     parent::setUp();
 
     $this->postDispatch($this->_getDispatchUrl(),
-                        ['all_profiles' => 1, 'doc_types' => '1;2']);
+                        ['profiles' => '2;44', 'doc_types' => '1;2']);
   }
 
 
-- 
GitLab