Package.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Config\Composer;
  7. /**
  8. * A model that represents composer package
  9. * @api
  10. * @since 100.0.2
  11. */
  12. class Package
  13. {
  14. /**
  15. * Contents of composer.json
  16. *
  17. * @var \StdClass
  18. */
  19. protected $json;
  20. /**
  21. * Constructor
  22. *
  23. * @param \StdClass $json
  24. */
  25. public function __construct(\stdClass $json)
  26. {
  27. $this->json = $json;
  28. }
  29. /**
  30. * Get JSON contents
  31. *
  32. * @param bool $formatted
  33. * @param string|null $format
  34. * @return string|\StdClass
  35. */
  36. public function getJson($formatted = true, $format = null)
  37. {
  38. if ($formatted) {
  39. if (null === $format) {
  40. $format = JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES;
  41. }
  42. return json_encode($this->json, $format) . "\n";
  43. }
  44. return $this->json;
  45. }
  46. /**
  47. * A getter for properties of the package
  48. *
  49. * For example:
  50. * $package->get('name');
  51. * $package->get('version');
  52. * $package->get('require->php');
  53. *
  54. * Returns whatever there is in the node or false if was unable to find this node
  55. *
  56. * @param string $propertyPath
  57. * @param string $filter pattern to filter out the properties
  58. * @return mixed
  59. * @SuppressWarnings(PHPMD.UnusedLocalVariable)
  60. */
  61. public function get($propertyPath, $filter = null)
  62. {
  63. $result = $this->traverseGet($this->json, explode('->', $propertyPath));
  64. if ($result && $filter) {
  65. foreach ($result as $key => $value) {
  66. if (!preg_match($filter, $key)) {
  67. unset($result->{$key});
  68. }
  69. }
  70. }
  71. return $result;
  72. }
  73. /**
  74. * Traverse an \StdClass object recursively in search of the needed property
  75. *
  76. * @param \StdClass $json
  77. * @param array $chain
  78. * @param int $index
  79. * @return mixed
  80. */
  81. private function traverseGet(\StdClass $json, array $chain, $index = 0)
  82. {
  83. $property = $chain[$index];
  84. if (!property_exists($json, $property)) {
  85. return false;
  86. }
  87. if (isset($chain[$index + 1])) {
  88. return $this->traverseGet($json->{$property}, $chain, $index + 1);
  89. } else {
  90. return $json->{$property};
  91. }
  92. }
  93. }