saver - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of saver.php

  1. <?php
  2. namespace usni\library\business;
  3.  
  4. use usni\Ecocom;
  5. use usni\library\dto\DetailViewDTO;
  6. use usni\library\dto\BulkEditFormDTO;
  7. use usni\library\db\ActiveRecord;
  8. use usni\library\modules\users\dao\UserDAO;
  9. use usni\library\dto\FormDTO;
  10. use usni\library\dto\GridViewDTO;
  11. use usni\library\utils\StringUtil;
  12. use yii\base\InvalidParamException;
  13. use usni\library\db\TranslatableActiveRecord;
  14. use usni\library\utils\ArrayUtil;
  15. /**
  16.  * Manager class file. This class acts as the base manager class for the business layer.
  17.  * 
  18.  * @package usni\library\business
  19.  */
  20. class Manager extends \yii\base\Component
  21. {
  22.     /**
  23.      * Language selected by the user. It would be used in case of translated models for e.g. Group.
  24.      * @var string 
  25.      */
  26.     public $language;
  27.  
  28.     /**
  29.      * User id of the logged in identity
  30.      * @var integer
  31.      */
  32.     public $userId;
  33.  
  34.     /**
  35.      * @var string 
  36.      */
  37.     public $modelClass;
  38.  
  39.  
  40.     /**
  41.      * inheritdoc
  42.      */
  43.     public function init()
  44.     {
  45.         if($this->language == null)
  46.         {
  47.             if(Ecocom::app()->isInstalled())
  48.             {
  49.                 $this->language = Ecocom::app()->languageManager->selectedLanguage;
  50.             }
  51.             else
  52.             {
  53.                 $this->language = Ecocom::app()->language;
  54.             }
  55.         }
  56.         if($this->userId == null)
  57.         {
  58.             if(Ecocom::app()->isInstalled())
  59.             {
  60.                 $this->userId   = Ecocom::app()->user->getId();
  61.             }
  62.             else
  63.             {
  64.                 $this->userId   = 0;
  65.             }
  66.         }
  67.     }
  68.  
  69.     /**
  70.      * Get instance of the class
  71.      * @param array $config
  72.      * @return get_called_class() the created object
  73.      */
  74.     public static function getInstance($config = [])
  75.     {
  76.         $class = get_called_class();
  77.         return new $class($config);
  78.     }
  79.  
  80.     /**
  81.      * Process edit.
  82.      * @param FormDTO $formDTO
  83.      */
  84.     public function processEdit($formDTO) 
  85.     {
  86.         $model      = $formDTO->getModel();
  87.         $scenario   = $model->scenario;
  88.         $postData   = $formDTO->getPostData();
  89.  
  90.         if (!empty($postData))
  91.         {
  92.             $this->beforeAssigningPostData($model);
  93.             $model->load($postData);
  94.  
  95.             $result = $this->processInputData($model);
  96.             $formDTO->setModel($model);
  97.             $formDTO->setIsTransactionSuccess($result);
  98.  
  99.         }
  100.         if($scenario != 'create')
  101.         {
  102.             $modelClass = get_class($formDTO->getModel());
  103.             $formDTO->setBrowseModels($this->getBrowseModels($modelClass));
  104.         }
  105.         elseif (!empty($postData))
  106.         {
  107.             if($model instanceof TranslatableActiveRecord && empty($model->errors) && $model->scenario == 'create')
  108.             {
  109.                 $model->saveTranslatedModels();
  110.             }
  111.         }
  112.     }
  113.  
  114.     /**
  115.      * Perform changes to the model before assigning the data from post array.
  116.      * @param ActiveRecord $model
  117.      * @return void
  118.      */
  119.     public function beforeAssigningPostData($model)
  120.     {
  121.  
  122.     }
  123.  
  124.     /**
  125.      * Get the list of models for browse
  126.      * @param string $modelClass
  127.      * @return array
  128.      */
  129.     public function getBrowseModels($modelClass)
  130.     {
  131.         return $modelClass::find()->orderBy(['id' => SORT_ASC])->asArray()->all();
  132.     }
  133.  
  134.     /**
  135.      * @param $model
  136.      * @return bool
  137.      * @throws \Exception
  138.      * @throws \Throwable
  139.      */
  140.     public function processInputData($model)
  141.     {
  142.         if($this->beforeModelSave($model))
  143.         {
  144.             $transaction = Ecocom::db()->beginTransaction();
  145.             try
  146.             {
  147.                 if ($model->save())
  148.                 {
  149.                     if ($this->afterModelSave($model))
  150.                     {
  151.                         $transaction->commit();
  152.                         return true;
  153.                     }
  154.                     else
  155.                     {
  156.                         $transaction->rollback();
  157.                         \Yii::info("After model saved failed");
  158.                         return false;
  159.                     }
  160.                 }
  161.                 else
  162.                 {
  163.                     \Yii::info("Model saved failed");
  164.                     $transaction->rollback();
  165.                     return false;
  166.                 }
  167.             }
  168.             catch (\Exception $e)
  169.             {
  170.                 $transaction->rollback();
  171.                 throw $e;
  172.             }
  173.             //Php 7.0
  174.             catch(\Throwable $e) 
  175.             {
  176.                 $transaction->rollBack();
  177.                 throw $e;
  178.             }
  179.         }
  180.         return false;    
  181.     }
  182.  
  183.     /**
  184.      * Perform changes to the model before saving it.
  185.      * If this is overridden in the extended class than make a call like
  186.      * if(parent::beforeModelSave($model)
  187.      * {
  188.      *      code here..
  189.      *      return true;
  190.      * }
  191.      * return false;
  192.      * @param ActiveRecord $model
  193.      * @return void
  194.      */
  195.     public function beforeModelSave($model)
  196.     {
  197.         return true;
  198.     }
  199.  
  200.     /**
  201.      * Perform changes after saving the model.
  202.      * @param ActiveRecord $model
  203.      * @return boolean
  204.      */
  205.     public function afterModelSave($model)
  206.     {
  207.         return true;
  208.     }
  209.  
  210.     /**
  211.      * Populate metadata related to author and time in DTO
  212.      * @param DetailViewDTO $detailViewDTO
  213.      */
  214.     public function populateMetadata($detailViewDTO)
  215.     {
  216.         //Call user DAO
  217.         $model      = $detailViewDTO->getModel();
  218.         if(ArrayUtil::getValue($model, 'created_by', false) !== false)
  219.         {
  220.             $createdBy  = UserDAO::getById($model['created_by']);
  221.             $detailViewDTO->setCreatedBy($createdBy);
  222.         }
  223.         if(ArrayUtil::getValue($model, 'modified_by', false) !== false)
  224.         {
  225.             $modifiedBy = UserDAO::getById($model['modified_by']);
  226.             $detailViewDTO->setModifiedBy($modifiedBy);
  227.         }
  228.     }
  229.  
  230.     /**
  231.      * Process bulk edit update.
  232.      * @param BulkEditFormDTO $formDTO
  233.      */
  234.     public function processBulkEdit($formDTO)
  235.     {
  236.         $selectedIdData = explode(',', $formDTO->getSelectedIds());
  237.         if($this->modelClass == null)
  238.         {
  239.             $this->modelClass = $formDTO->getModelClass();
  240.         }
  241.         $modelClassName = $this->modelClass;
  242.         $postData       = $formDTO->getPostData();
  243.         $modelBaseName  = strtolower(StringUtil::basename($modelClassName));
  244.         $formData       = ArrayUtil::getValue($postData, StringUtil::basename($modelClassName));
  245.         if(!empty($selectedIdData))
  246.         {
  247.             foreach ($formData as $key => $value)
  248.             {
  249.                 foreach ($selectedIdData as $id)
  250.                 {
  251.                     if($value != null)
  252.                     {
  253.                         //Check if allowed to update
  254.                         $model  = $modelClassName::findOne($id);
  255.                         if(isset($model['created_by']))
  256.                         {
  257.                             if(($model['created_by'] == $this->userId && Ecocom::app()->authorizationManager->checkAccess($this->userId, $modelBaseName . '.update')) ||
  258.                                     ($model['created_by'] != $this->userId && Ecocom::app()->authorizationManager->checkAccess($this->userId, $modelBaseName . '.updateother')))
  259.                             {
  260.                                 $this->updateModelAttributeWithBulkEdit($model, $key, $value);
  261.                             }
  262.                         }
  263.                         else
  264.                         {
  265.                             $this->updateModelAttributeWithBulkEdit($model, $key, $value);
  266.                         }
  267.                     }
  268.                 }
  269.             }
  270.         }
  271.     }
  272.  
  273.     /**
  274.      * Update model attribute with bulk edit
  275.      * @param string $model
  276.      * @param string $key
  277.      * @param string $value
  278.      */
  279.     public function updateModelAttributeWithBulkEdit($model, $key, $value)
  280.     {
  281.         $model->scenario    = 'bulkedit';
  282.         $model->$key        = $value;
  283.         $model->save();
  284.     }
  285.  
  286.     /**
  287.      * Process bulk delete.
  288.      * @param GridViewDTO $gridViewDTO
  289.      */
  290.     public function processBulkDelete($gridViewDTO)
  291.     {
  292.         $modelClass             = $gridViewDTO->getModelClass();
  293.         $selectedItems          = $gridViewDTO->getSelectedIdsForBulkDelete();
  294.         $permissionPrefix       = $this->getPermissionPrefix($modelClass);
  295.         foreach ($selectedItems as $item)
  296.         {
  297.             $model = $modelClass::findOne(intval($item));
  298.             //Check if allowed to delete
  299.             if(isset($model['created_by']))
  300.             {
  301.                 if(($model['created_by'] == $this->userId && Ecocom::app()->authorizationManager->checkAccess($this->userId, $permissionPrefix . '.delete')) ||
  302.                         ($model['created_by'] != $this->userId && Ecocom::app()->authorizationManager->checkAccess($this->userId, $permissionPrefix . '.deleteother')))
  303.                 {
  304.                     $this->deleteModel($model);
  305.                 }
  306.             }
  307.             else
  308.             {
  309.                 $this->deleteModel($model);
  310.             }
  311.         }
  312.     }
  313.  
  314.     /**
  315.      * Loads model.
  316.      * @param string  $modelClass Model class name.
  317.      * @param integer $id         ID of the model to be loaded.
  318.      * @return Array
  319.      * @throws exception InvalidParamException.
  320.      */
  321.     public function loadModel($modelClass, $id)
  322.     {
  323.         $model      = $modelClass::find()->where('id = :id', [':id' => $id])->asArray()->one();
  324.         if ($model === null)
  325.         {
  326.             throw new InvalidParamException("Id is not valid: $id");
  327.         }
  328.         return $model;
  329.     }
  330.  
  331.     /**
  332.      * Deletes model
  333.      * @param ActiveRecord $model
  334.      * @return int|false
  335.      * @throws \yii\db\Exception
  336.      */
  337.     public function deleteModel($model)
  338.     {
  339.         try
  340.         {
  341.             return $model->delete();
  342.         }
  343.         catch (\yii\db\Exception $ex)
  344.         {
  345.             throw $ex;
  346.         }
  347.     }
  348.  
  349.     /**
  350.      * Process list.
  351.      * @param GridViewDTO $gridViewDTO
  352.      */
  353.     public function processList($gridViewDTO) 
  354.     {
  355.         $searchModel  = $gridViewDTO->getSearchModel();
  356.         $searchModel->load($gridViewDTO->getQueryParams());
  357.         $gridViewDTO->setSearchModel($searchModel);
  358.         $dataProvider = $searchModel->search();
  359.         $gridViewDTO->setDataProvider($dataProvider);
  360.     }
  361.  
  362.     /**
  363.      * Process detail
  364.      * @param DetailViewDTO $detailViewDTO
  365.      */
  366.     public function processDetail($detailViewDTO)
  367.     {
  368.         $modelClass         = $detailViewDTO->getModelClass();
  369.         $model              = $this->loadModel($modelClass, $detailViewDTO->getId());
  370.         $isPermissible      = $this->processDetailAccess($detailViewDTO, $model);
  371.         if(!$isPermissible)
  372.         {
  373.             return false;
  374.         }
  375.         $detailViewDTO->setModel($model);
  376.         $this->populateMetadata($detailViewDTO);
  377.         $detailViewDTO->setBrowseModels($this->getBrowseModels($modelClass));
  378.     }
  379.  
  380.     /**
  381.      * Process detail access
  382.      * @param DetailViewDTO $detailViewDTO
  383.      * @param array $model
  384.      */
  385.     public function processDetailAccess($detailViewDTO, $model)
  386.     {
  387.         $modelClass         = $detailViewDTO->getModelClass();
  388.         $isPermissible      = true;
  389.         $permissionPrefix   = $this->getPermissionPrefix($modelClass);
  390.         if(ArrayUtil::getValue($model, 'created_by', false) !== false)
  391.         {
  392.             if($this->userId != $model['created_by'])
  393.             {
  394.                 $isPermissible  = Ecocom::app()->authorizationManager->checkAccess($this->userId, $permissionPrefix . '.viewother');
  395.             }
  396.         }
  397.         return $isPermissible;
  398.     }
  399.  
  400.     /**
  401.      * Get permission prefix.
  402.      * @param string $modelClass
  403.      * @return string
  404.      */
  405.     public function getPermissionPrefix($modelClass)
  406.     {
  407.         return strtolower(StringUtil::basename($modelClass));
  408.     }
  409. }
File Description
  • saver
  • PHP Code
  • 19 Jul-2019
  • 12.07 Kb
You can Share it: