Yaml.php 2.7 KB

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