EntityDirLocator.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace Elgg;
  3. /**
  4. * Locate the relative path of an entity's data dir.
  5. *
  6. * This returns paths like: '1/27/'.
  7. *
  8. * @note This class does not require the Elgg engine to be loaded and is suitable for
  9. * being used directly.
  10. *
  11. * @access private
  12. *
  13. * @package Elgg.Core
  14. */
  15. class EntityDirLocator {
  16. /**
  17. * Number of entries per matrix dir. DO NOT CHANGE!
  18. */
  19. const BUCKET_SIZE = 5000;
  20. /**
  21. * Find an entity's data dir.
  22. *
  23. * @param int $guid GUID of the entity.
  24. *
  25. * @throws \InvalidArgumentException
  26. */
  27. public function __construct($guid) {
  28. $guid = (int) $guid;
  29. if (!$guid || $guid < 1) {
  30. // Don't throw a ClassException to keep this class completely atomic.
  31. throw new \InvalidArgumentException("GUIDs must be integers > 0.");
  32. }
  33. $this->guid = $guid;
  34. }
  35. /**
  36. * Construct a file path matrix for an entity.
  37. * As of 1.9.0 matrixes are based on GUIDs and separated into dirs of 5000 entries
  38. * with the dir name being the lower bound for the GUID.
  39. *
  40. * @return string The path with trailing '/' where the entity's data will be stored relative to the data dir.
  41. */
  42. public function getPath() {
  43. $bound = $this->getLowerBucketBound($this->guid);
  44. return "$bound/$this->guid/";
  45. }
  46. /**
  47. * String casting magic method.
  48. *
  49. * @return string
  50. */
  51. public function __toString() {
  52. return $this->getPath();
  53. }
  54. /**
  55. * Return the lower bound for a guid with a bucket size
  56. *
  57. * @param int $guid The guid to get a bound for. Must be > 0.
  58. * @param int $bucket_size The size of the bucket. (The number of entities per dir.)
  59. * @return int
  60. */
  61. private static function getLowerBucketBound($guid, $bucket_size = null) {
  62. if (!$bucket_size || $bucket_size < 1) {
  63. $bucket_size = self::BUCKET_SIZE;
  64. }
  65. if ($guid < 1) {
  66. return false;
  67. }
  68. return (int) max(floor($guid / $bucket_size) * $bucket_size, 1);
  69. }
  70. }