PageRenderTime 48ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/database/classes/kohana/database/query/builder/join.php

https://bitbucket.org/alvinpd/monsterninja
PHP | 107 lines | 49 code | 17 blank | 41 comment | 3 complexity | 7d91537b9bd6e3948b34fa208b4c71fa MD5 | raw file
  1. <?php defined('SYSPATH') or die('No direct script access.');
  2. /**
  3. * Database query builder for JOIN statements.
  4. *
  5. * @package Kohana/Database
  6. * @category Query
  7. * @author Kohana Team
  8. * @copyright (c) 2008-2009 Kohana Team
  9. * @license http://kohanaphp.com/license
  10. */
  11. class Kohana_Database_Query_Builder_Join extends Database_Query_Builder {
  12. // Type of JOIN
  13. protected $_type;
  14. // JOIN ...
  15. protected $_table;
  16. // ON ...
  17. protected $_on = array();
  18. /**
  19. * Creates a new JOIN statement for a table. Optionally, the type of JOIN
  20. * can be specified as the second parameter.
  21. *
  22. * @param mixed column name or array($column, $alias) or object
  23. * @param string type of JOIN: INNER, RIGHT, LEFT, etc
  24. * @return void
  25. */
  26. public function __construct($table, $type = NULL)
  27. {
  28. // Set the table to JOIN on
  29. $this->_table = $table;
  30. if ($type !== NULL)
  31. {
  32. // Set the JOIN type
  33. $this->_type = (string) $type;
  34. }
  35. }
  36. /**
  37. * Adds a new condition for joining.
  38. *
  39. * @param mixed column name or array($column, $alias) or object
  40. * @param string logic operator
  41. * @param mixed column name or array($column, $alias) or object
  42. * @return $this
  43. */
  44. public function on($c1, $op, $c2)
  45. {
  46. $this->_on[] = array($c1, $op, $c2);
  47. return $this;
  48. }
  49. /**
  50. * Compile the SQL partial for a JOIN statement and return it.
  51. *
  52. * @param object Database instance
  53. * @return string
  54. */
  55. public function compile(Database $db)
  56. {
  57. if ($this->_type)
  58. {
  59. $sql = strtoupper($this->_type).' JOIN';
  60. }
  61. else
  62. {
  63. $sql = 'JOIN';
  64. }
  65. // Quote the table name that is being joined
  66. $sql .= ' '.$db->quote_table($this->_table).' ON ';
  67. $conditions = array();
  68. foreach ($this->_on as $condition)
  69. {
  70. // Split the condition
  71. list($c1, $op, $c2) = $condition;
  72. if ($op)
  73. {
  74. // Make the operator uppercase and spaced
  75. $op = ' '.strtoupper($op);
  76. }
  77. // Quote each of the identifiers used for the condition
  78. $conditions[] = $db->quote_identifier($c1).$op.' '.$db->quote_identifier($c2);
  79. }
  80. // Concat the conditions "... AND ..."
  81. $sql .= '('.implode(' AND ', $conditions).')';
  82. return $sql;
  83. }
  84. public function reset()
  85. {
  86. $this->_type =
  87. $this->_table = NULL;
  88. $this->_on = array();
  89. }
  90. } // End Database_Query_Builder_Join