dynamic.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php namespace System\DB\Query;
  2. use System\Str;
  3. class Dynamic {
  4. /**
  5. * Add conditions to a query from a dynamic method call.
  6. *
  7. * @param string $method
  8. * @param array $parameters
  9. * @param Query $query
  10. * @return Query
  11. */
  12. public static function build($method, $parameters, $query)
  13. {
  14. // ---------------------------------------------------------
  15. // Strip the "where_" off of the method.
  16. // ---------------------------------------------------------
  17. $finder = substr($method, 6);
  18. // ---------------------------------------------------------
  19. // Split the column names from the connectors.
  20. // ---------------------------------------------------------
  21. $segments = preg_split('/(_and_|_or_)/i', $finder, -1, PREG_SPLIT_DELIM_CAPTURE);
  22. // ---------------------------------------------------------
  23. // The connector variable will determine which connector
  24. // will be used for the condition. We'll change it as we
  25. // come across new connectors in the dynamic method string.
  26. //
  27. // The index variable helps us get the correct parameter
  28. // value for the where condition. We increment it each time
  29. // we add a condition.
  30. // ---------------------------------------------------------
  31. $connector = 'AND';
  32. $index = 0;
  33. // ---------------------------------------------------------
  34. // Iterate through each segment and add the conditions.
  35. // ---------------------------------------------------------
  36. foreach ($segments as $segment)
  37. {
  38. if ($segment != '_and_' and $segment != '_or_')
  39. {
  40. if ( ! array_key_exists($index, $parameters))
  41. {
  42. throw new \Exception("Wrong number of parameters for dynamic finder [$method].");
  43. }
  44. $query->where($segment, '=', $parameters[$index], $connector);
  45. $index++;
  46. }
  47. else
  48. {
  49. $connector = trim(Str::upper($segment), '_');
  50. }
  51. }
  52. return $query;
  53. }
  54. }