From eab8b9c65fb8b2577366cadee8ca53c8ab07b4a8 Mon Sep 17 00:00:00 2001 From: Simon Vieille Date: Sat, 19 Mar 2016 15:16:42 +0100 Subject: [PATCH] propel behaviour (rest) --- .../Propel/Behavior/FOSRestBehavior.php | 124 ++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 src/CoursEndingBundle/Propel/Behavior/FOSRestBehavior.php diff --git a/src/CoursEndingBundle/Propel/Behavior/FOSRestBehavior.php b/src/CoursEndingBundle/Propel/Behavior/FOSRestBehavior.php new file mode 100644 index 0000000..9498f29 --- /dev/null +++ b/src/CoursEndingBundle/Propel/Behavior/FOSRestBehavior.php @@ -0,0 +1,124 @@ + + */ +class FOSRestBehavior extends Behavior +{ + /** + * {@inheritdoc} + */ + public function objectFilter(&$script) + { + $script = preg_replace( + '#(\s+)\*/(\s+)abstract class#', + '$1'.$this->getClassAnnotations().'*/$2abstract class', + $script + ); + } + + public function objectMethods() + { + $script = ''; + + foreach ($this->getTable()->getColumns() as $column) { + $name = ucfirst($column->getName()); + + try { + $groups = $this->transformGroups($this->getParameter($column->getName())); + $getter = $this->getColumnGetter($column); + $newGetter = preg_replace('/^get/', 'getRest', $getter); + $script.= $this->generateRestMethod($column, $newGetter, $getter, $groups); + } catch (Exception $e) { + } + } + + return $script; + } + + /** + * Transform the group list to parameter format of annotation + * + * @param string $groups + * @return string + */ + protected function transformGroups($groups) + { + $data = []; + + foreach (explode(',', $groups) as $group) { + $group = trim($group); + + if ('' !== $group) { + $data[] = '"'.$group.'"'; + } + } + + return implode(', ', $data); + } + + public function generateRestMethod(Column $column, $newGetter, $getter, $groups) + { + $annotations = [ + '/**', + ' * @JMS\Serializer\Annotation\SerializedName("'.$column->getName().'")', + ]; + + if ($groups) { + $annotations[] = ' * @JMS\Serializer\Annotation\Groups('.$groups.')'; + } + + $annotations[] = ' * @JMS\Serializer\Annotation\VirtualProperty'; + $annotations[] = '*/'; + + $annotations = implode("\n", $annotations); + + $method = <<$getter(); +} + + +EOS; + + return $method; + } + + /** + * Get the getter of one of the columns of the behavior + * + * @param string $column One of the behavior columns, 'create_column' or 'update_column' + * @return string The related getter, 'getCreatedOn' or 'getUpdatedOn' + */ + protected function getColumnGetter($column) + { + return 'get' . $column->getPhpName(); + } + + /** + * Generates code for annotations + * + * @return string + */ + protected function getClassAnnotations() + { + $annotations = []; + + foreach (['@JMS\Serializer\Annotation\ExclusionPolicy("all")'] as $annotation) { + $annotations[] = ' * '.$annotation; + } + + return sprintf("%s\n", implode("\n", $annotations)); + } +} +