Created
September 10, 2024 04:59
-
-
Save POMXARK/bab1347fb9b46af1434a1becc73fbd95 to your computer and use it in GitHub Desktop.
symfony, Doctrine - CustomNamingStrategy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Doctrine; | |
use Doctrine\ORM\Mapping\DefaultNamingStrategy; | |
use Doctrine\ORM\Mapping\NamingStrategy; | |
class CustomNamingStrategy extends DefaultNamingStrategy implements NamingStrategy | |
{ | |
/** | |
* Преобразование имени класса в имя таблицы в множественном числе. | |
* | |
* @param $className | |
* | |
* @return string | |
*/ | |
public function classToTableName($className): string | |
{ | |
return $this->pluralize(parent::classToTableName($className)); | |
} | |
/** | |
* Преобразование имени свойства в имя колонки в snake_case. | |
* | |
* @param $propertyName | |
* @param $className | |
* | |
* @return string | |
*/ | |
public function propertyToColumnName($propertyName, $className = null): string | |
{ | |
return $this->camelToSnake($propertyName); | |
} | |
/** | |
* Преобразование имени свойства для использования в join-колонках. | |
* | |
* @param $propertyName | |
* @param string $className | |
* | |
* @return string | |
*/ | |
public function joinColumnName($propertyName, string $className): string | |
{ | |
return $this->camelToSnake($propertyName); | |
} | |
/** | |
* Преобразование имени таблицы для связи. | |
* | |
* @param $sourceEntity | |
* @param $targetEntity | |
* @param null $propertyName | |
* | |
* @return string | |
*/ | |
public function joinTableName($sourceEntity, $targetEntity, $propertyName = null): string | |
{ | |
return $this->pluralize(parent::joinTableName($sourceEntity, $targetEntity, $propertyName)); | |
} | |
/** | |
* Имя столбца для внешних ключей. | |
* | |
* @return string | |
*/ | |
public function referenceColumnName(): string | |
{ | |
return 'id'; | |
} | |
/** | |
* Пример простого преобразования в множественное число. | |
* Вы можете использовать библиотеку или более сложные правила для этого. | |
* | |
* @param $name | |
* | |
* @return string | |
*/ | |
private function pluralize($name): string | |
{ | |
return $name.'s'; | |
} | |
/** | |
* Преобразование camelCase в snake_case. | |
* | |
* @param $camelCase | |
* | |
* @return string | |
*/ | |
private function camelToSnake($camelCase): string | |
{ | |
$pattern = '/([a-z])([A-Z])/'; | |
$replacement = '$1_$2'; | |
$snakeCase = preg_replace($pattern, $replacement, $camelCase); | |
return strtolower($snakeCase); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment