1
0

FeaturePolicyManager.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Security\FeaturePolicy;
  8. use OCP\AppFramework\Http\EmptyFeaturePolicy;
  9. use OCP\EventDispatcher\IEventDispatcher;
  10. use OCP\Security\FeaturePolicy\AddFeaturePolicyEvent;
  11. class FeaturePolicyManager {
  12. /** @var EmptyFeaturePolicy[] */
  13. private array $policies = [];
  14. public function __construct(
  15. private IEventDispatcher $dispatcher,
  16. ) {
  17. }
  18. public function addDefaultPolicy(EmptyFeaturePolicy $policy): void {
  19. $this->policies[] = $policy;
  20. }
  21. public function getDefaultPolicy(): FeaturePolicy {
  22. $event = new AddFeaturePolicyEvent($this);
  23. $this->dispatcher->dispatchTyped($event);
  24. $defaultPolicy = new FeaturePolicy();
  25. foreach ($this->policies as $policy) {
  26. $defaultPolicy = $this->mergePolicies($defaultPolicy, $policy);
  27. }
  28. return $defaultPolicy;
  29. }
  30. /**
  31. * Merges the first given policy with the second one
  32. *
  33. */
  34. public function mergePolicies(
  35. FeaturePolicy $defaultPolicy,
  36. EmptyFeaturePolicy $originalPolicy,
  37. ): FeaturePolicy {
  38. foreach ((object)(array)$originalPolicy as $name => $value) {
  39. $setter = 'set' . ucfirst($name);
  40. if (\is_array($value)) {
  41. $getter = 'get' . ucfirst($name);
  42. $currentValues = \is_array($defaultPolicy->$getter()) ? $defaultPolicy->$getter() : [];
  43. $defaultPolicy->$setter(\array_values(\array_unique(\array_merge($currentValues, $value))));
  44. } elseif (\is_bool($value)) {
  45. $defaultPolicy->$setter($value);
  46. }
  47. }
  48. return $defaultPolicy;
  49. }
  50. }