ConvertDoctrine1Schema.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the MIT license. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\ORM\Tools;
  20. use Doctrine\DBAL\Types\Type;
  21. use Doctrine\Inflector\InflectorFactory;
  22. use Doctrine\ORM\Mapping\ClassMetadataInfo;
  23. use Symfony\Component\Yaml\Yaml;
  24. use function array_merge;
  25. use function count;
  26. use function explode;
  27. use function file_get_contents;
  28. use function glob;
  29. use function in_array;
  30. use function is_array;
  31. use function is_dir;
  32. use function is_string;
  33. use function preg_match;
  34. use function strtolower;
  35. /**
  36. * Class to help with converting Doctrine 1 schema files to Doctrine 2 mapping files
  37. *
  38. * @link www.doctrine-project.org
  39. */
  40. class ConvertDoctrine1Schema
  41. {
  42. /** @var mixed[] */
  43. private $from;
  44. /** @var array<string,string> */
  45. private $legacyTypeMap = [
  46. // TODO: This list may need to be updated
  47. 'clob' => 'text',
  48. 'timestamp' => 'datetime',
  49. 'enum' => 'string',
  50. ];
  51. /**
  52. * Constructor passes the directory or array of directories
  53. * to convert the Doctrine 1 schema files from.
  54. *
  55. * @psalm-param list<string>|string $from
  56. */
  57. public function __construct($from)
  58. {
  59. $this->from = (array) $from;
  60. }
  61. /**
  62. * Gets an array of ClassMetadataInfo instances from the passed
  63. * Doctrine 1 schema.
  64. *
  65. * @return ClassMetadataInfo[] An array of ClassMetadataInfo instances
  66. *
  67. * @psalm-return list<ClassMetadataInfo>
  68. */
  69. public function getMetadata()
  70. {
  71. $schema = [];
  72. foreach ($this->from as $path) {
  73. if (is_dir($path)) {
  74. $files = glob($path . '/*.yml');
  75. foreach ($files as $file) {
  76. $schema = array_merge($schema, (array) Yaml::parse(file_get_contents($file)));
  77. }
  78. } else {
  79. $schema = array_merge($schema, (array) Yaml::parse(file_get_contents($path)));
  80. }
  81. }
  82. $metadatas = [];
  83. foreach ($schema as $className => $mappingInformation) {
  84. $metadatas[] = $this->convertToClassMetadataInfo($className, $mappingInformation);
  85. }
  86. return $metadatas;
  87. }
  88. /**
  89. * @param mixed[] $mappingInformation
  90. */
  91. private function convertToClassMetadataInfo(string $className, $mappingInformation): ClassMetadataInfo
  92. {
  93. $metadata = new ClassMetadataInfo($className);
  94. $this->convertTableName($className, $mappingInformation, $metadata);
  95. $this->convertColumns($className, $mappingInformation, $metadata);
  96. $this->convertIndexes($className, $mappingInformation, $metadata);
  97. $this->convertRelations($className, $mappingInformation, $metadata);
  98. return $metadata;
  99. }
  100. /**
  101. * @param mixed[] $model
  102. */
  103. private function convertTableName(string $className, array $model, ClassMetadataInfo $metadata): void
  104. {
  105. if (isset($model['tableName']) && $model['tableName']) {
  106. $e = explode('.', $model['tableName']);
  107. if (count($e) > 1) {
  108. $metadata->table['schema'] = $e[0];
  109. $metadata->table['name'] = $e[1];
  110. } else {
  111. $metadata->table['name'] = $e[0];
  112. }
  113. }
  114. }
  115. /**
  116. * @param string $className
  117. * @param mixed[] $model
  118. *
  119. * @return void
  120. */
  121. private function convertColumns($className, array $model, ClassMetadataInfo $metadata)
  122. {
  123. $id = false;
  124. if (isset($model['columns']) && $model['columns']) {
  125. foreach ($model['columns'] as $name => $column) {
  126. $fieldMapping = $this->convertColumn($className, $name, $column, $metadata);
  127. if (isset($fieldMapping['id']) && $fieldMapping['id']) {
  128. $id = true;
  129. }
  130. }
  131. }
  132. if (! $id) {
  133. $fieldMapping = [
  134. 'fieldName' => 'id',
  135. 'columnName' => 'id',
  136. 'type' => 'integer',
  137. 'id' => true,
  138. ];
  139. $metadata->mapField($fieldMapping);
  140. $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO);
  141. }
  142. }
  143. /**
  144. * @param string $className
  145. * @param string $name
  146. * @param string|mixed[] $column
  147. *
  148. * @return mixed[]
  149. *
  150. * @throws ToolsException
  151. */
  152. private function convertColumn($className, $name, $column, ClassMetadataInfo $metadata)
  153. {
  154. if (is_string($column)) {
  155. $string = $column;
  156. $column = [];
  157. $column['type'] = $string;
  158. }
  159. if (! isset($column['name'])) {
  160. $column['name'] = $name;
  161. }
  162. // check if a column alias was used (column_name as field_name)
  163. if (preg_match('/(\w+)\sas\s(\w+)/i', $column['name'], $matches)) {
  164. $name = $matches[1];
  165. $column['name'] = $name;
  166. $column['alias'] = $matches[2];
  167. }
  168. if (preg_match('/([a-zA-Z]+)\(([0-9]+)\)/', $column['type'], $matches)) {
  169. $column['type'] = $matches[1];
  170. $column['length'] = $matches[2];
  171. }
  172. $column['type'] = strtolower($column['type']);
  173. // check if legacy column type (1.x) needs to be mapped to a 2.0 one
  174. if (isset($this->legacyTypeMap[$column['type']])) {
  175. $column['type'] = $this->legacyTypeMap[$column['type']];
  176. }
  177. if (! Type::hasType($column['type'])) {
  178. throw ToolsException::couldNotMapDoctrine1Type($column['type']);
  179. }
  180. $fieldMapping = [];
  181. if (isset($column['primary'])) {
  182. $fieldMapping['id'] = true;
  183. }
  184. $fieldMapping['fieldName'] = $column['alias'] ?? $name;
  185. $fieldMapping['columnName'] = $column['name'];
  186. $fieldMapping['type'] = $column['type'];
  187. if (isset($column['length'])) {
  188. $fieldMapping['length'] = $column['length'];
  189. }
  190. $allowed = ['precision', 'scale', 'unique', 'options', 'notnull', 'version'];
  191. foreach ($column as $key => $value) {
  192. if (in_array($key, $allowed)) {
  193. $fieldMapping[$key] = $value;
  194. }
  195. }
  196. $metadata->mapField($fieldMapping);
  197. if (isset($column['autoincrement'])) {
  198. $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO);
  199. } elseif (isset($column['sequence'])) {
  200. $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE);
  201. $definition = [
  202. 'sequenceName' => is_array($column['sequence']) ? $column['sequence']['name'] : $column['sequence'],
  203. ];
  204. if (isset($column['sequence']['size'])) {
  205. $definition['allocationSize'] = $column['sequence']['size'];
  206. }
  207. if (isset($column['sequence']['value'])) {
  208. $definition['initialValue'] = $column['sequence']['value'];
  209. }
  210. $metadata->setSequenceGeneratorDefinition($definition);
  211. }
  212. return $fieldMapping;
  213. }
  214. /**
  215. * @param string $className
  216. * @param mixed[] $model
  217. *
  218. * @return void
  219. */
  220. private function convertIndexes($className, array $model, ClassMetadataInfo $metadata)
  221. {
  222. if (empty($model['indexes'])) {
  223. return;
  224. }
  225. foreach ($model['indexes'] as $name => $index) {
  226. $type = isset($index['type']) && $index['type'] === 'unique'
  227. ? 'uniqueConstraints' : 'indexes';
  228. $metadata->table[$type][$name] = [
  229. 'columns' => $index['fields'],
  230. ];
  231. }
  232. }
  233. /**
  234. * @param string $className
  235. * @param mixed[] $model
  236. *
  237. * @return void
  238. */
  239. private function convertRelations($className, array $model, ClassMetadataInfo $metadata)
  240. {
  241. if (empty($model['relations'])) {
  242. return;
  243. }
  244. $inflector = InflectorFactory::create()->build();
  245. foreach ($model['relations'] as $name => $relation) {
  246. if (! isset($relation['alias'])) {
  247. $relation['alias'] = $name;
  248. }
  249. if (! isset($relation['class'])) {
  250. $relation['class'] = $name;
  251. }
  252. if (! isset($relation['local'])) {
  253. $relation['local'] = $inflector->tableize($relation['class']);
  254. }
  255. if (! isset($relation['foreign'])) {
  256. $relation['foreign'] = 'id';
  257. }
  258. if (! isset($relation['foreignAlias'])) {
  259. $relation['foreignAlias'] = $className;
  260. }
  261. if (isset($relation['refClass'])) {
  262. $type = 'many';
  263. $foreignType = 'many';
  264. $joinColumns = [];
  265. } else {
  266. $type = $relation['type'] ?? 'one';
  267. $foreignType = $relation['foreignType'] ?? 'many';
  268. $joinColumns = [
  269. [
  270. 'name' => $relation['local'],
  271. 'referencedColumnName' => $relation['foreign'],
  272. 'onDelete' => $relation['onDelete'] ?? null,
  273. ],
  274. ];
  275. }
  276. if ($type === 'one' && $foreignType === 'one') {
  277. $method = 'mapOneToOne';
  278. } elseif ($type === 'many' && $foreignType === 'many') {
  279. $method = 'mapManyToMany';
  280. } else {
  281. $method = 'mapOneToMany';
  282. }
  283. $associationMapping = [];
  284. $associationMapping['fieldName'] = $relation['alias'];
  285. $associationMapping['targetEntity'] = $relation['class'];
  286. $associationMapping['mappedBy'] = $relation['foreignAlias'];
  287. $associationMapping['joinColumns'] = $joinColumns;
  288. $metadata->$method($associationMapping);
  289. }
  290. }
  291. }