EntityPreloader.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace Elgg;
  3. /**
  4. * Preload entities based on properties of fetched objects
  5. *
  6. * @access private
  7. *
  8. * @package Elgg.Core
  9. */
  10. class EntityPreloader {
  11. /**
  12. * Preload entities based on the given objects
  13. *
  14. * @param object[] $objects Objects--e.g. loaded from an Elgg query--from which we can
  15. * pluck GUIDs to preload
  16. * @param string[] $guid_properties e.g. array("owner_guid")
  17. *
  18. * @return void
  19. */
  20. public function preload($objects, array $guid_properties) {
  21. $guids = $this->getGuidsToLoad($objects, $guid_properties);
  22. // If only 1 to load, not worth the overhead of elgg_get_entities(),
  23. // get_entity() will handle it later.
  24. if (count($guids) > 1) {
  25. call_user_func($this->_callable_entity_loader, array(
  26. 'guids' => $guids,
  27. ));
  28. }
  29. }
  30. /**
  31. * Get GUIDs that need to be loaded
  32. *
  33. * To simplify the user API, this function accepts non-arrays and arrays containing non-objects
  34. *
  35. * @param object[] $objects Objects from which to pluck GUIDs
  36. * @param string[] $guid_properties e.g. array("owner_guid")
  37. * @return int[]
  38. */
  39. protected function getGuidsToLoad($objects, array $guid_properties) {
  40. if (!is_array($objects) || count($objects) < 2) {
  41. return array();
  42. }
  43. $preload_guids = array();
  44. foreach ($objects as $object) {
  45. if (is_object($object)) {
  46. foreach ($guid_properties as $property) {
  47. if (empty($object->{$property})) {
  48. continue;
  49. }
  50. $guid = $object->{$property};
  51. if ($guid && !call_user_func($this->_callable_cache_checker, $guid)) {
  52. $preload_guids[] = $guid;
  53. }
  54. }
  55. }
  56. }
  57. return array_unique($preload_guids);
  58. }
  59. /**
  60. * DO NOT USE. For unit test mocking
  61. * @access private
  62. */
  63. public $_callable_cache_checker = '_elgg_retrieve_cached_entity';
  64. /**
  65. * DO NOT USE. For unit test mocking
  66. * @access private
  67. */
  68. public $_callable_entity_loader = 'elgg_get_entities';
  69. }