entity_repository.class.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. use Doctrine\ORM\QueryBuilder;
  3. /**
  4. * Description of repository
  5. *
  6. * @license see /license.txt
  7. * @author Laurent Opprecht <laurent@opprecht.info> for the Univesity of Geneva
  8. */
  9. class EntityRepository extends Doctrine\ORM\EntityRepository
  10. {
  11. function next_id($entity = null)
  12. {
  13. $column = $this->get_id_field();
  14. if (empty($column)) {
  15. return false;
  16. }
  17. $metadata = $this->getClassMetadata();
  18. $entity_name = $metadata->name;
  19. if ($this->is_course_table()) {
  20. $course = $entity ? $entity->get_c_id() : Entity::current_course();
  21. $course = $course ? $course : Entity::current_course();
  22. $c_id = is_object($course) ? $course->get_id() : $course;
  23. if (empty($c_id)) {
  24. return null;
  25. }
  26. $query = new QueryBuilder($this->getEntityManager());
  27. $query = $query->select("MAX(t.id) AS m")->from($entity_name, 't')->where('t.c_id = ' . $c_id);
  28. } else {
  29. $query = new QueryBuilder($this->getEntityManager());
  30. $query = $query->select("MAX(t.$column) AS m")->from($entity_name, 't');
  31. }
  32. $result = $this->getEntityManager()->createQuery($query);
  33. $result = $result->getSingleScalarResult();
  34. $result += 10; //in case somebody does an insert in between
  35. return $result;
  36. }
  37. /**
  38. *
  39. * @return string|bool
  40. */
  41. function get_id_field()
  42. {
  43. $metadata = $this->getClassMetadata();
  44. if (count($metadata->identifier) == 1) {
  45. $field = $metadata->identifier[0];
  46. return $field;
  47. }
  48. if (count($metadata->identifier) > 2) {
  49. return false;
  50. }
  51. if (isset($metadata->identifier['id'])) {
  52. return 'id';
  53. }
  54. if (!$this->is_course_table()) {
  55. return false;
  56. }
  57. foreach ($metadata->identifier as $field) {
  58. if ($field != 'c_id' && $field != 'course') {
  59. return $field;
  60. }
  61. }
  62. return false;
  63. }
  64. function is_course_table()
  65. {
  66. $metadata = $this->getClassMetadata();
  67. $table = $metadata->table['name'];
  68. return strpos($table, 'c_') === 0;
  69. }
  70. }