Advertisement
Guest User

Untitled

a guest
Apr 25th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App;
  4.  
  5. use Vinkla\Hashids\HashidsManager;
  6.  
  7. /**
  8. * Bind a model to a route based on the hash of
  9. * its id (or other specified key).
  10. *
  11. * @package App
  12. *
  13. * @mixin \Illuminate\Database\Eloquent\Model
  14. */
  15. trait HashidsRoutable
  16. {
  17. /**
  18. * Instantiate appropriate Hashids connection
  19. *
  20. * @return \Hashids\Hashids
  21. */
  22. protected function getHashidsInstance()
  23. {
  24. return app(HashidsManager::class)->connection($this->getHashidsConnection());
  25. }
  26.  
  27. /**
  28. * Determine Hashids connection to use
  29. *
  30. * @return null|string
  31. */
  32. protected function getHashidsConnection()
  33. {
  34. return null;
  35. }
  36.  
  37. /**
  38. * Encode a parameter
  39. *
  40. * @param string $parameter
  41. * @return string
  42. */
  43. protected function encodeParameter($parameter)
  44. {
  45. return $this->getHashidsInstance()->encode($parameter);
  46. }
  47.  
  48. /**
  49. * Decode parameter
  50. *
  51. * @param string $parameter
  52. * @return array
  53. */
  54. protected function decodeParameter($parameter)
  55. {
  56. return $this->getHashidsInstance()->decode($parameter);
  57. }
  58.  
  59. /**
  60. * Instruct implicit route binding to use
  61. * our custom hashed parameter.
  62. *
  63. * This is long and crazy to avoid parameters
  64. * collisions.
  65. *
  66. * @return string
  67. */
  68. public function getRouteKeyName()
  69. {
  70. return 'hashidsRoutableHashParam';
  71. }
  72.  
  73. /**
  74. * Determine which attribute to encode
  75. *
  76. * @return string
  77. */
  78. public function getRouteHashKeyName()
  79. {
  80. return $this->getKeyName();
  81. }
  82.  
  83. /**
  84. * Get beginning value
  85. *
  86. * @return string
  87. */
  88. public function getRouteHashKey()
  89. {
  90. return $this->getAttribute($this->getRouteHashKeyName());
  91. }
  92.  
  93. /**
  94. * Encode real parameter to url value for bindings
  95. *
  96. * @return string
  97. */
  98. public function getHashidsRoutableHashParamAttribute()
  99. {
  100. return $this->encodeParameter($this->getRouteHashKey());
  101. }
  102.  
  103. /**
  104. * Transform a checking by hashed key to real query
  105. *
  106. * @return \Illuminate\Database\Eloquent\Builder
  107. */
  108. public function where()
  109. {
  110. $params = func_get_args();
  111.  
  112. if ($params[0] == $this->getRouteKeyName()) {
  113. return parent::where($this->getRouteHashKeyName(), $this->decodeParameter($params[1]));
  114. }
  115.  
  116. return parent::where(...$params);
  117. }
  118. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement