ConfigurationFieldsController.php 13.6 KB
<?php 
namespace App\Controller;

use App\Controller\AppController;
use App\Form\ConfigurationFieldsForm;
use Cake\Core\Configure;

use Symfony\Component\Yaml\Yaml;


// modelless form : voir https://book.cakephp.org/3/en/core-libraries/form.html
class ConfigurationFieldsController extends AppController
{
    
    /*
     * @Override
     *
     * Initialisation des autorisations pour les actions spécifiques à ce controleur
     *
     */
    protected function setAuthorizations() {
        
        // On supprime les autres actions par défaut (add, view, index, find)
        //foreach (array_keys($this->is_authorized_action[]) as $a) if ($a != 'display') unset($this->is_authorized_action[$a]);
        $this->is_authorized_action = [];

        // admin (+) only
        $this->setAuthorizationsForAction('index', -1, ['admin'=>0, 'super'=>0]);
        $this->setAuthorizationsForAction('view', -1, ['admin'=>0, 'super'=>0]);
        $this->setAuthorizationsForAction('edit', -1, ['admin'=>0, 'super'=>0]);
        $this->setAuthorizationsForAction('resetToDefault', -1, ['admin'=>0, 'super'=>0]);
        // tous
        //$this->setAuthorizationsForAction('index', 0);
        // Superadmin only :
        //$this->setAuthorizationsForAction('index', -1, ['super'=>0]);
        
    }
    
    public function index() {
        $this->view();
    }
    
    public function view() {
        
        $this->edit(true);
        // Lecteurs configurés : 'default', 'yaml'
        //debug(Configure::configured());
        
        //$fields = Configure::readOrFail('MANDATORY_FIELDS_FOR_LOT'.$lot_num);
        /*
        $fields = Configure::readOrFail('MANDATORY_AND_READONLY_FIELDS');
        $this->set(compact('fields'));
        */
    }
    
    public function resetToDefault() {
        $config_mandatory_fields_file_name = CONFIG.DS.CONFIG_MATERIEL_FIELDS_FILE_NAME.'.yml';
        $config_mandatory_fields_file_name_default = CONFIG.DS.CONFIG_MATERIEL_FIELDS_FILE_NAME.'.default.yml';
        
        $config_default = Yaml::parse(file_get_contents($config_mandatory_fields_file_name_default)); //parse le fichier
        $config_default_as_yaml = Yaml::dump($config_default); //remet en yaml
        if (! file_put_contents($config_mandatory_fields_file_name, $config_default_as_yaml) )
            throw new \ErrorException("Impossible de remettre la configuration des champs de matériel aux valeurs par défaut - le fichier de config $config_mandatory_fields_file_name n'est pas accessible en écriture");
            
        $this->Flash->success("La configuration des champs de matériel a bien été réinitialisée aux valeurs par défaut");
        return $this->redirect(['action' => 'view']);
    }
        
    
    public function edit($READONLY=false) {
        
        $contact = new ConfigurationFieldsForm();
        //debug($contact);
        
        // - En mode POST
        if ($this->request->is('post')) {
            /*
             * We use the execute() method to run our form’s _execute() method only when the data is valid,
             * and set flash messages accordingly.
             * We could have also used the validate() method to only validate the request data:
             *      $isValid = $form->validate($this->request->getData());
             */
            //debug($this->request->getData());
            
            // - OK
            if ($contact->execute($this->request->getData())) {
                $fieldsets = $this->request->getData();
                //debug($fieldsets);
                $contact->setData($fieldsets);
                
                // On sauvegarde le contenu de $fieldsets dans le fichier de config (array => yaml)
                
                //debug($contact);
                // See : https://book.cakephp.org/3/en/development/configuration.html#writing-configuration-data
                /*
                 Configure::write('Company.name','Pizza, Inc.');
                 Configure::write('Company.slogan','Pizza for your body and soul');
                 // idem :
                 Configure::write('Company', [
                 'name' => 'Pizza, Inc.',
                 'slogan' => 'Pizza for your body and soul'
                 ]);
                 */
                //$data1 = Configure::read('MANDATORY_AND_READONLY_FIELDS');
                //debug($data1);
                /*
                 Configure::write('MANDATORY_AND_READONLY_FIELDS',$data);
                 $data2 = Configure::read('MANDATORY_AND_READONLY_FIELDS');
                 */
                //debug($data2);
                //$name = $contact->getData('name');
                /* NE MARCHE PAS, WHY ???
                 $config_mandatory_fields_file_name = 'app_labinvent_mandatory_fields';
                 if ( Configure::dump($config_mandatory_fields_file_name, 'my_yaml', ['MANDATORY_AND_READONLY_FIELDS']) )
                 $this->Flash->success("La configuration des champs matériels a bien été sauvegardée");
                 */
                 //$config_mandatory_fields_file_name = CONFIG.DS.'app_labinvent_mandatory_fields'.'.yml';
                 $config_mandatory_fields_file_name = CONFIG.DS.CONFIG_MATERIEL_FIELDS_FILE_NAME.'.yml';
                 // Symfony YAML component : https://symfony.com/doc/current/components/yaml.html
                 /*
                  $array = Yaml::parse(file_get_contents($config_mandatory_fields_file_name)); //parse le fichier
                  debug($array);
                  $res = Yaml::dump($array); //remet en yaml
                  */
                 $fieldsets_new = [];
                 $fieldsets_new['MANDATORY_AND_READONLY_FIELDS']=$fieldsets;
                 //debug($fieldsets_new);
                 
                 $fieldsets_as_yaml = Yaml::dump($fieldsets_new); //remet en yaml
                 //debug($res); exit;
                 if (! file_put_contents($config_mandatory_fields_file_name, $fieldsets_as_yaml) )
                     throw new \ErrorException("Impossible d'enregistrer la configuration des champs de matériel - le fichier de config $config_mandatory_fields_file_name n'est pas accessible en écriture"); 
                 $this->Flash->success("La configuration des champs de matériel a bien été sauvegardée");
                 return $this->redirect(['action' => 'view']);
            }
            
            // - KO
            else {
                // Once a form has been validated you can retrieve the errors from it:
                $errors = $form->getErrors(); // $form->errors(); // prior to 3.7.0
                debug($errors);
                /* $errors contains
                 [
                 'email' => ['A valid email address is required']
                 ]
                 */
                $this->Flash->error("La configuration n'a pas pu être enregistrée");
            }
        }
        
        // - En mode GET (ou POST avec erreur)
        
        if ($this->request->is('get')) {
            /*
             $contact->setData([
             'name' => 'John Doe',
             'email' => 'john.doe@example.com'
             ]);
             */
        }
        
        $this->set('contact', $contact);
        
        $fieldsets = Configure::readOrFail('MANDATORY_AND_READONLY_FIELDS');
        $this->set(compact('READONLY', 'fieldsets'));
        //debug($fieldsets);
        
    } // edit()
    
    
    public function OLD_edit($READONLY=false)
    {
        $contact = new ConfigurationFieldsForm();
        //debug($contact);
        
        // - En mode POST
        if ($this->request->is('post')) {
            /* 
             * We use the execute() method to run our form’s _execute() method only when the data is valid, 
             * and set flash messages accordingly. 
             * We could have also used the validate() method to only validate the request data:
             *      $isValid = $form->validate($this->request->getData());
             */
            //debug($this->request->getData());
            
            // - OK
            if ($contact->execute($this->request->getData())) {
                $fieldsets = $this->request->getData();
                //debug($data);
                $contact->setData($fieldsets);

                /* 
                 * 1) On retouche $fieldsets pour qu'il puisse être sauvegardé au format fichier texte (yaml) :
                 * 
                 * Ex:
            		'designation' => [
            			'selected' => '0',
            			'labl' => 'commentaire',
            			'roles' => [
            				(int) 0 => 'Responsable',
            				(int) 1 => 'Administration'
            			]
            		],
                 * 
                 * - '.selected' : si = 0 => on préfixe le nom du champ par "OFF_" 
                 *      => 'OFF_designation'
                 * - '.labl' : on l'ajoute entre parenthèse à la suite du nom du champ 
                 *      => 'OFF_designation (commentaire)'
                 * - '.roles' : on les ajoute entre parenthèse à la fin du nom du champ => 
                 *      => 'OFF_designation (commentaire) (sauf Responsable, Administration)'
                 */
                $fieldsets_new = [];
                $fieldsets_new['MANDATORY_AND_READONLY_FIELDS']=[];
                //$fn = &$fieldsets_new['MANDATORY_AND_READONLY_FIELDS'];
                foreach ($fieldsets as $fieldset_name=>$fields) {
                    $fieldsets_new['MANDATORY_AND_READONLY_FIELDS'][$fieldset_name] = [];
                    foreach ($fields as $field_name=>$attributes) {
                        $field_name_new = $field_name;
                        // - selected
                        if (! $attributes['selected'] )
                            $field_name_new = 'OFF_'.$field_name_new;
                        // - labl
                        if ($attributes['labl'])
                            $field_name_new .= ' ('. $attributes['labl'] .')';
                        // - roles
                        if (isset($attributes['except_roles']) && $attributes['except_roles'])
                            $field_name_new .= ' (sauf '. implode(',',$attributes['except_roles']) .')';
                        //debug($field_name_new);
                        $fieldsets_new['MANDATORY_AND_READONLY_FIELDS'][$fieldset_name][] = $field_name_new;
                    }
                }
                //debug($fieldsets_new); exit;
                
                // 2) On sauvegarde le contenu de $fieldsets dans le fichier de config (array => yaml)
                
                //debug($contact);
                // See : https://book.cakephp.org/3/en/development/configuration.html#writing-configuration-data
                /*
                Configure::write('Company.name','Pizza, Inc.');
                Configure::write('Company.slogan','Pizza for your body and soul');
                // idem :
                Configure::write('Company', [
                    'name' => 'Pizza, Inc.',
                    'slogan' => 'Pizza for your body and soul'
                ]);
                */
                //$data1 = Configure::read('MANDATORY_AND_READONLY_FIELDS');
                //debug($data1);
                /*
                Configure::write('MANDATORY_AND_READONLY_FIELDS',$data);
                $data2 = Configure::read('MANDATORY_AND_READONLY_FIELDS');
                */
                //debug($data2);
                //$name = $contact->getData('name');
                /* NE MARCHE PAS, WHY ???
                $config_mandatory_fields_file_name = 'app_labinvent_mandatory_fields';
                if ( Configure::dump($config_mandatory_fields_file_name, 'my_yaml', ['MANDATORY_AND_READONLY_FIELDS']) )
                    $this->Flash->success("La configuration des champs matériels a bien été sauvegardée");
                */
                //$config_mandatory_fields_file_name = CONFIG.DS.'app_labinvent_mandatory_fields'.'.yml';
                $config_mandatory_fields_file_name = CONFIG.DS.CONFIG_MATERIEL_FIELDS_FILE_NAME.'.yml';
                // Symfony YAML component : https://symfony.com/doc/current/components/yaml.html
                /*
                $array = Yaml::parse(file_get_contents($config_mandatory_fields_file_name)); //parse le fichier
                debug($array);
                $res = Yaml::dump($array); //remet en yaml
                */
                $fieldsets_new_as_yaml = Yaml::dump($fieldsets_new); //remet en yaml
                //debug($res); exit;
                if ( file_put_contents($config_mandatory_fields_file_name, $fieldsets_new_as_yaml) ) 
                    $this->Flash->success("La configuration des champs matériels a bien été sauvegardée");
                return $this->redirect(['action' => 'view']);
            }
            
            // - KO
            else {
                // Once a form has been validated you can retrieve the errors from it:
                $errors = $form->getErrors(); // $form->errors(); // prior to 3.7.0
                debug($errors);
                /* $errors contains
                 [
                 'email' => ['A valid email address is required']
                 ]
                 */
                $this->Flash->error("La configuration n'a pas pu être enregistrée");
            }
        }

        // - En mode GET (ou POST avec erreur)
        
        if ($this->request->is('get')) {
            /*
            $contact->setData([
                'name' => 'John Doe',
                'email' => 'john.doe@example.com'
            ]);
            */
        }

        $this->set('contact', $contact);
        
        $fieldsets = Configure::readOrFail('MANDATORY_AND_READONLY_FIELDS');
        $this->set(compact('READONLY', 'fieldsets'));
        
    } // edit()
    
    
    
} // end of class