AnnotationConverter.php 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /*
  3. * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. namespace JMS\SecurityExtraBundle\Metadata\Driver;
  18. use JMS\SecurityExtraBundle\Annotation\RunAs;
  19. use JMS\SecurityExtraBundle\Annotation\SatisfiesParentSecurityPolicy;
  20. use JMS\SecurityExtraBundle\Annotation\SecureReturn;
  21. use JMS\SecurityExtraBundle\Annotation\SecureParam;
  22. use JMS\SecurityExtraBundle\Annotation\Secure;
  23. use JMS\SecurityExtraBundle\Metadata\MethodMetadata;
  24. /**
  25. * Converts annotations to method metadata
  26. *
  27. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  28. */
  29. class AnnotationConverter
  30. {
  31. public function convertMethodAnnotations(\ReflectionMethod $method, array $annotations)
  32. {
  33. $parameters = array();
  34. foreach ($method->getParameters() as $index => $parameter) {
  35. $parameters[$parameter->getName()] = $index;
  36. }
  37. $methodMetadata = new MethodMetadata($method->getDeclaringClass()->getName(), $method->getName());
  38. $hasSecurityMetadata = false;
  39. foreach ($annotations as $annotation) {
  40. if ($annotation instanceof Secure) {
  41. $methodMetadata->roles = $annotation->roles;
  42. $hasSecurityMetadata = true;
  43. } else if ($annotation instanceof SecureParam) {
  44. if (!isset($parameters[$annotation->name])) {
  45. throw new \InvalidArgumentException(sprintf('The parameter "%s" does not exist for method "%s".', $annotation->name, $method->getName()));
  46. }
  47. $methodMetadata->addParamPermissions($parameters[$annotation->name], $annotation->permissions);
  48. $hasSecurityMetadata = true;
  49. } else if ($annotation instanceof SecureReturn) {
  50. $methodMetadata->returnPermissions = $annotation->permissions;
  51. $hasSecurityMetadata = true;
  52. } else if ($annotation instanceof SatisfiesParentSecurityPolicy) {
  53. $methodMetadata->satisfiesParentSecurityPolicy = true;
  54. $hasSecurityMetadata = true;
  55. } else if ($annotation instanceof RunAs) {
  56. $methodMetadata->runAsRoles = $annotation->roles;
  57. $hasSecurityMetadata = true;
  58. }
  59. }
  60. return $hasSecurityMetadata ? $methodMetadata : null;
  61. }
  62. }