Yaml.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace Gedmo\Sortable\Mapping\Driver;
  3. use Gedmo\Mapping\Driver\File,
  4. Gedmo\Mapping\Driver,
  5. Gedmo\Exception\InvalidMappingException;
  6. use Doctrine\Common\Persistence\Mapping\ClassMetadata;
  7. /**
  8. * This is a yaml mapping driver for Sortable
  9. * behavioral extension. Used for extraction of extended
  10. * metadata from yaml specificaly for Sortable
  11. * extension.
  12. *
  13. * @author Lukas Botsch <lukas.botsch@gmail.com>
  14. * @package Gedmo.Sortable.Mapping.Driver
  15. * @subpackage Yaml
  16. * @link http://www.gediminasm.org
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. class Yaml extends File implements Driver
  20. {
  21. /**
  22. * File extension
  23. * @var string
  24. */
  25. protected $_extension = '.dcm.yml';
  26. /**
  27. * List of types which are valid for position fields
  28. *
  29. * @var array
  30. */
  31. private $validTypes = array(
  32. 'integer',
  33. 'smallint',
  34. 'bigint'
  35. );
  36. /**
  37. * {@inheritDoc}
  38. */
  39. public function validateFullMetadata(ClassMetadata $meta, array $config)
  40. {
  41. if ($config && !isset($config['position'])) {
  42. throw new InvalidMappingException("Missing property: 'position' in class - {$meta->name}");
  43. }
  44. }
  45. /**
  46. * {@inheritDoc}
  47. */
  48. public function readExtendedMetadata(ClassMetadata $meta, array &$config)
  49. {
  50. $mapping = $this->_getMapping($meta->name);
  51. if (isset($mapping['fields'])) {
  52. foreach ($mapping['fields'] as $field => $fieldMapping) {
  53. if (isset($fieldMapping['gedmo'])) {
  54. if (in_array('sortablePosition', $fieldMapping['gedmo'])) {
  55. if (!$this->isValidField($meta, $field)) {
  56. throw new InvalidMappingException("Sortable position field - [{$field}] type is not valid and must be 'integer' in class - {$meta->name}");
  57. }
  58. $config['position'] = $field;
  59. } elseif (in_array('sortableGroup', $fieldMapping['gedmo'])) {
  60. if (!isset($config['groups'])) {
  61. $config['groups'] = array();
  62. }
  63. $config['groups'][] = $field;
  64. }
  65. }
  66. }
  67. }
  68. }
  69. /**
  70. * {@inheritDoc}
  71. */
  72. protected function _loadMappingFile($file)
  73. {
  74. return \Symfony\Component\Yaml\Yaml::parse($file);
  75. }
  76. /**
  77. * Checks if $field type is valid as SortablePosition field
  78. *
  79. * @param ClassMetadata $meta
  80. * @param string $field
  81. * @return boolean
  82. */
  83. protected function isValidField($meta, $field)
  84. {
  85. $mapping = $meta->getFieldMapping($field);
  86. return $mapping && in_array($mapping['type'], $this->validTypes);
  87. }
  88. }