Helper.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace backend\actions\helpers;
  3. use Yii;
  4. use yii\base\Exception;
  5. use yii\base\Model;
  6. /**
  7. * Author: lf
  8. * Blog: https://blog.feehi.com
  9. * Email: job@feehi.com
  10. * Created at: 2020-01-31 21:19
  11. */
  12. class Helper
  13. {
  14. public static function getPrimaryKeys($primaryKeyIdentity, $primaryKeyFromMethod)
  15. {
  16. $primaryKeys = [];
  17. if( !empty( $primaryKeyIdentity ) ){
  18. if( is_string($primaryKeyIdentity) ){
  19. $primaryKeyIdentity = [$primaryKeyIdentity];
  20. }else if( !is_array($primaryKeyIdentity) ){
  21. throw new Exception("primaryKeyIdentity must be string or array");
  22. }
  23. foreach ($primaryKeyIdentity as $identity){
  24. if( $primaryKeyFromMethod == "GET" ){
  25. $primaryKeys[] =Yii::$app->getRequest()->get($identity, null);
  26. }else if( $primaryKeyFromMethod == "POST" ){
  27. $primaryKeys[] = Yii::$app->getRequest()->post($identity, null);
  28. }else{
  29. throw new Exception('primaryKeyFromMethod must be GET or POST');
  30. }
  31. }
  32. }
  33. return $primaryKeys;
  34. }
  35. public static function getErrorString($result)
  36. {
  37. if( !is_array($result) ){
  38. $results = [$result];
  39. }else{
  40. $results = $result;
  41. }
  42. $error = "";
  43. foreach ($results as $result) {
  44. if ($result instanceof Model) {//if returns a model, will call getErrors() get the error description string
  45. $items = $result->getErrors();
  46. foreach ($items as $item) {
  47. foreach ($item as $e) {
  48. $error .= $e . "<br>";
  49. }
  50. }
  51. $error = rtrim($error, "<br>");
  52. } else if (is_string($result)) {//if returns a string, they will be the error description
  53. $error = $result;
  54. } else {
  55. throw new Exception("doCreate/doUpdate/doDelete/doSort closure must return boolean, yii\base\Model or string");
  56. }
  57. }
  58. return $error;
  59. }
  60. }