浏览代码

data transformer

Luciano Andrade 7 年之前
父节点
当前提交
f2e66b5a8b
共有 1 个文件被更改,包括 64 次插入0 次删除
  1. 64 0
      Form/Transformer/ClientTransformer.php

+ 64 - 0
Form/Transformer/ClientTransformer.php

@@ -0,0 +1,64 @@
+<?php
+namespace WebserviceBundle\Form\Transformer;
+
+use Doctrine\ORM\EntityManagerInterface;
+use Symfony\Component\Form\DataTransformerInterface;
+use Symfony\Component\Form\Exception\TransformationFailedException;
+
+class ClientTransformer implements DataTransformerInterface
+{
+    private $em;
+
+    public function __construct(EntityManagerInterface $em)
+    {
+        $this->em = $em;
+    }
+
+    /**
+     * Transforms an object (issue) to a string (number).
+     *
+     * @param  Int | null $client
+     * @return string
+     */
+    public function transform($client)
+    {
+        if (null === $client) {
+            return '';
+        }
+
+        return $client;
+    }
+
+    /**
+     * Transforms a string (query pattern) to an client id (using the web service).
+     *
+     * @param  string $client_query_param
+     * @return Issue|null
+     * @throws TransformationFailedException if object (issue) is not found.
+     */
+    public function reverseTransform($client_query_param)
+    {
+        // no issue number? It's optional, so that's ok
+        if (!$issueNumber) {
+            return;
+        }
+
+        $issue = $this->em
+            ->getRepository(Issue::class)
+            // query for the issue with this id
+            ->find($issueNumber)
+        ;
+
+        if (null === $issue) {
+            // causes a validation error
+            // this message is not shown to the user
+            // see the invalid_message option
+            throw new TransformationFailedException(sprintf(
+                'An Client could not be found for the query "%s"!',
+                $issueNumber
+            ));
+        }
+
+        return $issue;
+    }
+}