Refactor custom fields api to doctrine

[MAILPOET-2453]
This commit is contained in:
Pavel Dohnal
2019-12-17 10:27:16 +01:00
committed by Rostislav Wolný
parent 49f92ef77c
commit ff9bd232ec
4 changed files with 97 additions and 40 deletions

View File

@ -4,7 +4,11 @@ namespace MailPoet\API\JSON\v1;
use MailPoet\API\JSON\Endpoint as APIEndpoint; use MailPoet\API\JSON\Endpoint as APIEndpoint;
use MailPoet\API\JSON\Error as APIError; use MailPoet\API\JSON\Error as APIError;
use MailPoet\API\JSON\Response;
use MailPoet\API\JSON\ResponseBuilders\CustomFieldsResponseBuilder;
use MailPoet\Config\AccessControl; use MailPoet\Config\AccessControl;
use MailPoet\CustomFields\CustomFieldsRepository;
use MailPoet\Entities\CustomFieldEntity;
use MailPoet\Models\CustomField; use MailPoet\Models\CustomField;
use MailPoet\WP\Functions as WPFunctions; use MailPoet\WP\Functions as WPFunctions;
@ -13,22 +17,33 @@ class CustomFields extends APIEndpoint {
'global' => AccessControl::PERMISSION_MANAGE_FORMS, 'global' => AccessControl::PERMISSION_MANAGE_FORMS,
]; ];
function getAll() { /** @var CustomFieldsRepository */
$collection = CustomField::orderByAsc('created_at')->findMany(); private $custom_fields_repository;
$custom_fields = array_map(function($custom_field) {
return $custom_field->asArray();
}, $collection);
return $this->successResponse($custom_fields); /** @var CustomFieldsResponseBuilder */
private $custom_fields_response_builder;
public function __construct(
CustomFieldsRepository $custom_fields_repository,
CustomFieldsResponseBuilder $custom_fields_response_builder
) {
$this->custom_fields_repository = $custom_fields_repository;
$this->custom_fields_response_builder = $custom_fields_response_builder;
}
function getAll() {
$collection = $this->custom_fields_repository->findBy([], ['created_at' => 'asc']);
return $this->successResponse($this->custom_fields_response_builder->buildBatch($collection));
} }
function delete($data = []) { function delete($data = []) {
$id = (isset($data['id']) ? (int)$data['id'] : null); $id = (isset($data['id']) ? (int)$data['id'] : null);
$custom_field = CustomField::findOne($id); $custom_field = $this->custom_fields_repository->findOneById($id);
if ($custom_field instanceof CustomField) { if ($custom_field instanceof CustomFieldEntity) {
$custom_field->delete(); $this->custom_fields_repository->remove($custom_field);
$this->custom_fields_repository->flush();
return $this->successResponse($custom_field->asArray()); return $this->successResponse($this->custom_fields_response_builder->build($custom_field));
} else { } else {
return $this->errorResponse([ return $this->errorResponse([
APIError::NOT_FOUND => WPFunctions::get()->__('This custom field does not exist.', 'mailpoet'), APIError::NOT_FOUND => WPFunctions::get()->__('This custom field does not exist.', 'mailpoet'),
@ -37,24 +52,21 @@ class CustomFields extends APIEndpoint {
} }
function save($data = []) { function save($data = []) {
$custom_field = CustomField::createOrUpdate($data); try {
$errors = $custom_field->getErrors(); $custom_field = $this->custom_fields_repository->createOrUpdate($data);
$custom_field = $this->custom_fields_repository->findOneById($custom_field->getId());
if (!empty($errors)) { if(!$custom_field instanceof CustomFieldEntity) return $this->errorResponse();
return $this->badRequest($errors); return $this->successResponse($this->custom_fields_response_builder->build($custom_field));
} catch (\Exception $e) {
return $this->errorResponse($errors = [], $meta = [], $status = Response::STATUS_BAD_REQUEST);
} }
$custom_field = CustomField::findOne($custom_field->id);
if(!$custom_field instanceof CustomField) return $this->errorResponse();
$response = $custom_field->asArray();
$response['id'] = (int)$response['id'];
return $this->successResponse($response);
} }
function get($data = []) { function get($data = []) {
$id = (isset($data['id']) ? (int)$data['id'] : null); $id = (isset($data['id']) ? (int)$data['id'] : null);
$custom_field = CustomField::findOne($id); $custom_field = $this->custom_fields_repository->findOneById($id);
if ($custom_field instanceof CustomField) { if ($custom_field instanceof CustomFieldEntity) {
return $this->successResponse($custom_field->asArray()); return $this->successResponse($this->custom_fields_response_builder->build($custom_field));
} }
return $this->errorResponse([ return $this->errorResponse([
APIError::NOT_FOUND => WPFunctions::get()->__('This custom field does not exist.', 'mailpoet'), APIError::NOT_FOUND => WPFunctions::get()->__('This custom field does not exist.', 'mailpoet'),

View File

@ -17,4 +17,25 @@ class CustomFieldsRepository extends Repository {
protected function getEntityClassName() { protected function getEntityClassName() {
return CustomFieldEntity::class; return CustomFieldEntity::class;
} }
/**
* @param array $data
* @return CustomFieldEntity
*/
public function createOrUpdate($data) {
if (isset($data['id'])) {
$field = $this->findOneById((int)$data['id']);
} elseif (isset($data['name'])) {
$field = $this->findOneBy(['name' => $data['name']]);
}
if (!isset($field)) {
$field = new CustomFieldEntity();
$this->entity_manager->persist($field);
}
if (isset($data['name'])) $field->setName($data['name']);
if (isset($data['type'])) $field->setType($data['type']);
if (isset($data['params'])) $field->setParams($data['params']);
$this->entity_manager->flush();
return $field;
}
} }

View File

@ -20,19 +20,20 @@ class CustomFieldEntity {
/** /**
* @ORM\Column(type="string", nullable=false, unique=true) * @ORM\Column(type="string", nullable=false, unique=true)
* @Assert\NotBlank()
* @var string * @var string
*/ */
private $name; private $name;
/** /**
* @ORM\Column(type="string", nullable=false) * @ORM\Column(type="string", nullable=false)
* @Assert\NotBlank()
* @var string * @var string
*/ */
private $type; private $type;
/** /**
* @ORM\Column(type="json_or_serialized") * @ORM\Column(type="json_or_serialized")
* @Assert\NotBlank()
* @var array * @var array
*/ */
private $params; private $params;
@ -57,4 +58,25 @@ class CustomFieldEntity {
public function getParams() { public function getParams() {
return $this->params; return $this->params;
} }
/**
* @param string $name
*/
public function setName($name) {
$this->name = $name;
}
/**
* @param string $type
*/
public function setType($type) {
$this->type = $type;
}
/**
* @param array $params
*/
public function setParams($params) {
$this->params = $params;
}
} }

View File

@ -3,10 +3,17 @@
namespace MailPoet\Test\API\JSON\v1; namespace MailPoet\Test\API\JSON\v1;
use MailPoet\API\JSON\Response as APIResponse; use MailPoet\API\JSON\Response as APIResponse;
use MailPoet\API\JSON\ResponseBuilders\CustomFieldsResponseBuilder;
use MailPoet\API\JSON\v1\CustomFields; use MailPoet\API\JSON\v1\CustomFields;
use MailPoet\CustomFields\CustomFieldsRepository;
use MailPoet\DI\ContainerWrapper;
use MailPoet\Models\CustomField; use MailPoet\Models\CustomField;
class CustomFieldsTest extends \MailPoetTest { class CustomFieldsTest extends \MailPoetTest {
/** @var CustomFieldsRepository */
private $repository;
private $custom_fields = [ private $custom_fields = [
[ [
'name' => 'CF: text', 'name' => 'CF: text',
@ -54,13 +61,15 @@ class CustomFieldsTest extends \MailPoetTest {
function _before() { function _before() {
parent::_before(); parent::_before();
$this->repository = ContainerWrapper::getInstance(WP_DEBUG)->get(CustomFieldsRepository::class);
$this->repository->truncate();
foreach ($this->custom_fields as $custom_field) { foreach ($this->custom_fields as $custom_field) {
CustomField::createOrUpdate($custom_field); $this->repository->createOrUpdate($custom_field);
} }
} }
function testItCanGetAllCustomFields() { function testItCanGetAllCustomFields() {
$router = new CustomFields(); $router = new CustomFields($this->repository, new CustomFieldsResponseBuilder());
$response = $router->getAll(); $response = $router->getAll();
expect($response->status)->equals(APIResponse::STATUS_OK); expect($response->status)->equals(APIResponse::STATUS_OK);
expect($response->data)->count(count($this->custom_fields)); expect($response->data)->count(count($this->custom_fields));
@ -76,7 +85,7 @@ class CustomFieldsTest extends \MailPoetTest {
$custom_field = CustomField::where('type', 'date')->findOne(); $custom_field = CustomField::where('type', 'date')->findOne();
$custom_field_id = $custom_field->id(); $custom_field_id = $custom_field->id();
$router = new CustomFields(); $router = new CustomFields($this->repository, new CustomFieldsResponseBuilder());
$response = $router->delete(['id' => $custom_field_id]); $response = $router->delete(['id' => $custom_field_id]);
expect($response->status)->equals(APIResponse::STATUS_OK); expect($response->status)->equals(APIResponse::STATUS_OK);
@ -91,34 +100,31 @@ class CustomFieldsTest extends \MailPoetTest {
$new_custom_field = [ $new_custom_field = [
'name' => 'New custom field', 'name' => 'New custom field',
'type' => 'text', 'type' => 'text',
'params' => [],
]; ];
$router = new CustomFields(); $router = new CustomFields($this->repository, new CustomFieldsResponseBuilder());
$response = $router->save($new_custom_field); $response = $router->save($new_custom_field);
expect($response->status)->equals(APIResponse::STATUS_OK); expect($response->status)->equals(APIResponse::STATUS_OK);
// missing type // missing type
$response = $router->save(['name' => 'New custom field']); $response = $router->save(['name' => 'New custom field1']);
expect($response->status)->equals(APIResponse::STATUS_BAD_REQUEST); expect($response->status)->equals(APIResponse::STATUS_BAD_REQUEST);
expect($response->errors[0]['message'])->equals('Please specify a type.');
// missing name // missing name
$response = $router->save(['type' => 'text']); $response = $router->save(['type' => 'text']);
expect($response->status)->equals(APIResponse::STATUS_BAD_REQUEST); expect($response->status)->equals(APIResponse::STATUS_BAD_REQUEST);
expect($response->errors[0]['message'])->equals('Please specify a name.');
// missing data // missing data
$response = $router->save(); $response = $router->save();
expect($response->status)->equals(APIResponse::STATUS_BAD_REQUEST); expect($response->status)->equals(APIResponse::STATUS_BAD_REQUEST);
expect($response->errors[0]['message'])->equals('Please specify a name.');
expect($response->errors[1]['message'])->equals('Please specify a type.');
} }
function testItCanGetACustomField() { function testItCanGetACustomField() {
$custom_field = CustomField::where('name', 'CF: text')->findOne(); $custom_field = $this->repository->findOneBy(['name' => 'CF: text']);
$router = new CustomFields(); $router = new CustomFields($this->repository, new CustomFieldsResponseBuilder());
$response = $router->get(['id' => $custom_field->id()]); $response = $router->get(['id' => $custom_field->getId()]);
expect($response->data['name'])->equals('CF: text'); expect($response->data['name'])->equals('CF: text');
expect($response->data['type'])->equals('text'); expect($response->data['type'])->equals('text');
@ -127,8 +133,4 @@ class CustomFieldsTest extends \MailPoetTest {
$response = $router->get(['id' => 'not_an_id']); $response = $router->get(['id' => 'not_an_id']);
expect($response->status)->equals(APIResponse::STATUS_NOT_FOUND); expect($response->status)->equals(APIResponse::STATUS_NOT_FOUND);
} }
function _after() {
CustomField::deleteMany();
}
} }