WIP - phpstan and phpcs - tests failing currently

This commit is contained in:
2026-01-24 01:20:17 -08:00
parent 31650e55c2
commit 37b7bca3be
17 changed files with 888 additions and 822 deletions

View File

@@ -9,7 +9,12 @@
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^10.1", "phpunit/phpunit": "^10.1",
"cakephp/migrations": "^4.0.0" "cakephp/migrations": "^4.0.0",
"phpstan/phpstan": "^2.1",
"dereuromark/composer-prefer-lowest": "^0.1.10",
"cakedc/cakephp-phpstan": "^4.1",
"dereuromark/cakephp-captcha": "^2.0",
"fig-r/psr2r-sniffer": "^2.7"
}, },
"suggest": { "suggest": {
"dereuromark/cakephp-captcha": "^2.0" "dereuromark/cakephp-captcha": "^2.0"
@@ -25,5 +30,17 @@
"Cake\\Test\\": "vendor/cakephp/cakephp/tests/", "Cake\\Test\\": "vendor/cakephp/cakephp/tests/",
"TestApp\\": "tests/test_app/src/" "TestApp\\": "tests/test_app/src/"
} }
},
"scripts": {
"cs-check": "vendor/bin/phpcs --colors --parallel=16",
"cs-fix": "vendor/bin/phpcbf --colors --parallel=16",
"lowest": "validate-prefer-lowest",
"lowest-setup": "composer update --prefer-lowest --prefer-stable --prefer-dist --no-interaction && cp composer.json composer.backup && composer require --dev dereuromark/composer-prefer-lowest && mv composer.backup composer.json",
"stan": "phpstan analyze"
},
"config": {
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": false
}
} }
} }

View File

@@ -3,59 +3,59 @@ declare(strict_types=1);
use Migrations\AbstractMigration; use Migrations\AbstractMigration;
class CreateContactUsFormSubmissions extends AbstractMigration class CreateContactUsFormSubmissions extends AbstractMigration {
{
/** /**
* Change Method. * Change Method.
* *
* More information on this method is available here: * More information on this method is available here:
* https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method * https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
* @return void * @return void
*/ */
public function change(): void public function change(): void {
{ $table = $this->table('contact_us_form_submissions', ['id' => false, 'primary_key' => ['id']]);
$table = $this->table('contact_us_form_submissions', ['id' => false, 'primary_key' => ['id']]);
$table->addColumn('id', 'uuid', [
'default' => null,
'null' => false,
]);
$table->addColumn('submitted_at', 'datetime', [
'default' => null,
'null' => false,
]);
$table->addColumn('client_ip', 'string', [
'default' => null,
'limit' => 45,
'null' => true,
]);
$table->addColumn('name', 'string', [
'default' => null,
'limit' => 255,
'null' => false,
]);
$table->addColumn('email', 'string', [
'default' => null,
'limit' => 255,
'null' => true,
]);
$table->addColumn('subject', 'string', [
'default' => null,
'limit' => 255,
'null' => true,
]);
$table->addColumn('message', 'text', [
'default' => null,
'null' => false,
]);
$table->addColumn('confirm_email_sent', 'datetime', [
'default' => null,
'null' => true,
]);
$table->addColumn('backend_email_sent', 'datetime', [
'default' => null,
'null' => true,
]);
$table->create();
}
$table->addColumn('id', 'uuid', [
'default' => null,
'null' => false,
]);
$table->addColumn('submitted_at', 'datetime', [
'default' => null,
'null' => false,
]);
$table->addColumn('client_ip', 'string', [
'default' => null,
'limit' => 45,
'null' => true,
]);
$table->addColumn('name', 'string', [
'default' => null,
'limit' => 255,
'null' => false,
]);
$table->addColumn('email', 'string', [
'default' => null,
'limit' => 255,
'null' => true,
]);
$table->addColumn('subject', 'string', [
'default' => null,
'limit' => 255,
'null' => true,
]);
$table->addColumn('message', 'text', [
'default' => null,
'null' => false,
]);
$table->addColumn('confirm_email_sent', 'datetime', [
'default' => null,
'null' => true,
]);
$table->addColumn('backend_email_sent', 'datetime', [
'default' => null,
'null' => true,
]);
$table->create();
}
} }

View File

@@ -3,28 +3,28 @@
return [ return [
'ContactUs' => [ 'ContactUs' => [
'fields' => [ 'fields' => [
'subject' => true, 'subject' => true,
'email' => true, 'email' => true,
'captcha' => true, 'captcha' => true,
], ],
'clientIpHeader' => '', 'clientIpHeader' => '',
'email' => [ 'email' => [
'mailerClass' => 'CakeContactUs.ContactUsFormSubmissions', 'mailerClass' => 'CakeContactUs.ContactUsFormSubmissions',
'confirmation' => true, // true or false 'confirmation' => true, // true or false
'backend' => [ // array with enabled and the to/cc/bcc/ fields as strings or arrays 'backend' => [ // array with enabled and the to/cc/bcc/ fields as strings or arrays
'enabled' => true, 'enabled' => true,
'to' => 'bshipley@hipowered.dev', 'to' => 'bshipley@hipowered.dev',
'cc' => '', // email string or array of emails 'cc' => '', // email string or array of emails
'bcc' => '', // email string or array of emails 'bcc' => '', // email string or array of emails
], ],
], ],
'addIdToRedirect' => true, 'addIdToRedirect' => true,
'redirectUrl' => [ 'redirectUrl' => [
'prefix' => 'Admin', 'prefix' => 'Admin',
'plugin' => 'CakeContactUs', 'plugin' => 'CakeContactUs',
'controller' => 'ContactUsFormSubmissions', 'controller' => 'ContactUsFormSubmissions',
'action' => 'view', 'action' => 'view',
], ],
], ],
]; ];

21
phpcs.xml Normal file
View File

@@ -0,0 +1,21 @@
<?xml version="1.0"?>
<ruleset name="plugin">
<arg value="nps"/>
<file>src/</file>
<file>config/</file>
<file>tests/</file>
<exclude-pattern>/tests/test_files/</exclude-pattern>
<exclude-pattern>/tests/test_app/</exclude-pattern>
<rule ref="vendor/fig-r/psr2r-sniffer/PSR2R/ruleset.xml"/>
<rule ref="PSR1.Classes.ClassDeclaration.MissingNamespace">
<exclude-pattern>*/config/Migrations/*</exclude-pattern>
</rule>
<rule ref="PhpCollective.Classes.ClassFileName.NoMatch">
<exclude-pattern>*/config/Migrations/*</exclude-pattern>
</rule>
</ruleset>

10
phpstan.neon Normal file
View File

@@ -0,0 +1,10 @@
includes:
- vendor/cakedc/cakephp-phpstan/extension.neon
parameters:
level: 4
paths:
- src
bootstrapFiles:
- tests/bootstrap.php
treatPhpDocTypesAsCertain: false

View File

@@ -13,12 +13,23 @@ use Cake\Routing\RouteBuilder;
/** /**
* Plugin for CakeContactUs * Plugin for CakeContactUs
*/ */
class CakeContactUsPlugin extends BasePlugin class CakeContactUsPlugin extends BasePlugin {
{
public const EVENT_BEFORE_CONTACT_US_FORM_SAVED = 'ContactUs.Global.beforeRegister'; /**
public const EVENT_AFTER_CONTACT_US_FORM_SAVED = 'ContactUs.Global.afterRegister'; * @var string
public const CAKE_CONTACT_US_MYSQL_DATETIME = 'Y-m-d H:i:s'; */
/** public const EVENT_BEFORE_CONTACT_US_FORM_SAVED = 'ContactUs.Global.beforeRegister';
/**
* @var string
*/
public const EVENT_AFTER_CONTACT_US_FORM_SAVED = 'ContactUs.Global.afterRegister';
/**
* @var string
*/
public const CAKE_CONTACT_US_MYSQL_DATETIME = 'Y-m-d H:i:s';
/**
* Load all the plugin configuration and bootstrap logic. * Load all the plugin configuration and bootstrap logic.
* *
* The host application is provided as an argument. This allows you to load * The host application is provided as an argument. This allows you to load
@@ -27,11 +38,10 @@ class CakeContactUsPlugin extends BasePlugin
* @param \Cake\Core\PluginApplicationInterface $app The host application * @param \Cake\Core\PluginApplicationInterface $app The host application
* @return void * @return void
*/ */
public function bootstrap(PluginApplicationInterface $app): void public function bootstrap(PluginApplicationInterface $app): void {
{ }
}
/** /**
* Add routes for the plugin. * Add routes for the plugin.
* *
* If your plugin has many routes and you would like to isolate them into a separate file, * If your plugin has many routes and you would like to isolate them into a separate file,
@@ -40,59 +50,56 @@ class CakeContactUsPlugin extends BasePlugin
* @param \Cake\Routing\RouteBuilder $routes The route builder to update. * @param \Cake\Routing\RouteBuilder $routes The route builder to update.
* @return void * @return void
*/ */
public function routes(RouteBuilder $routes): void public function routes(RouteBuilder $routes): void {
{ $routes->prefix('Admin', function (RouteBuilder $routes): void {
$routes->prefix('Admin', function (RouteBuilder $routes): void { $routes->plugin('CakeContactUs', function (RouteBuilder $routes): void {
$routes->plugin('CakeContactUs', function (RouteBuilder $routes): void { $routes->connect('/', ['controller' => 'ContactUsFormSubmissions', 'action' => 'index']);
$routes->connect('/', ['controller' => 'ContactUsFormSubmissions', 'action' => 'index']);
$routes->fallbacks(); $routes->fallbacks();
}); });
}); });
$routes->plugin('CakeContactUs', ['path' => '/contact-us'], function (RouteBuilder $routes): void { $routes->plugin('CakeContactUs', ['path' => '/contact-us'], function (RouteBuilder $routes): void {
$routes->connect('/', ['controller' => 'ContactUsFormSubmissions', 'action' => 'add']); $routes->connect('/', ['controller' => 'ContactUsFormSubmissions', 'action' => 'add']);
}); });
parent::routes($routes); parent::routes($routes);
} }
/** /**
* Add middleware for the plugin. * Add middleware for the plugin.
* *
* @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to update. * @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to update.
* @return \Cake\Http\MiddlewareQueue * @return \Cake\Http\MiddlewareQueue
*/ */
public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue {
{ // Add your middlewares here
// Add your middlewares here
return $middlewareQueue; return $middlewareQueue;
} }
/** /**
* Add commands for the plugin. * Add commands for the plugin.
* *
* @param \Cake\Console\CommandCollection $commands The command collection to update. * @param \Cake\Console\CommandCollection $commands The command collection to update.
* @return \Cake\Console\CommandCollection * @return \Cake\Console\CommandCollection
*/ */
public function console(CommandCollection $commands): CommandCollection public function console(CommandCollection $commands): CommandCollection {
{ // Add your commands here
// Add your commands here
$commands = parent::console($commands); $commands = parent::console($commands);
return $commands; return $commands;
} }
/** /**
* Register application container services. * Register application container services.
* *
* @link https://book.cakephp.org/4/en/development/dependency-injection.html#dependency-injection
* @param \Cake\Core\ContainerInterface $container The Container to update. * @param \Cake\Core\ContainerInterface $container The Container to update.
* @return void * @return void
* @link https://book.cakephp.org/4/en/development/dependency-injection.html#dependency-injection
*/ */
public function services(ContainerInterface $container): void public function services(ContainerInterface $container): void {
{ // Add your services here
// Add your services here }
}
} }

View File

@@ -10,79 +10,74 @@ use App\Controller\AppController;
* *
* @property \CakeContactUs\Model\Table\ContactUsFormSubmissionsTable $ContactUsFormSubmissions * @property \CakeContactUs\Model\Table\ContactUsFormSubmissionsTable $ContactUsFormSubmissions
*/ */
class ContactUsFormSubmissionsController extends AppController class ContactUsFormSubmissionsController extends AppController {
{
public function initialize(): void
{
parent::initialize(); // TODO: Change the autogenerated stub
}
/** public function initialize(): void {
parent::initialize(); // TODO: Change the autogenerated stub
}
/**
* Index method * Index method
* *
* @return \Cake\Http\Response|null|void Renders view * @return \Cake\Http\Response|null|void Renders view
*/ */
public function index() public function index() {
{ $query = $this->ContactUsFormSubmissions->find();
$query = $this->ContactUsFormSubmissions->find(); $contactUsFormSubmissions = $this->paginate($query);
$contactUsFormSubmissions = $this->paginate($query);
$this->set(compact('contactUsFormSubmissions')); $this->set(compact('contactUsFormSubmissions'));
} }
/** /**
* View method * View method
* *
* @param string|null $id Contact Us Form Submission id. * @param string|null $id Contact Us Form Submission id.
* @return \Cake\Http\Response|null|void Renders view
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
* @return \Cake\Http\Response|null|void Renders view
*/ */
public function view($id = null) public function view($id = null) {
{ $contactUsFormSubmission = $this->ContactUsFormSubmissions->get($id, contain: []);
$contactUsFormSubmission = $this->ContactUsFormSubmissions->get($id, contain: []); $this->set(compact('contactUsFormSubmission'));
$this->set(compact('contactUsFormSubmission')); }
}
/**
/**
* Edit method * Edit method
* *
* @param string|null $id Contact Us Form Submission id. * @param string|null $id Contact Us Form Submission id.
* @return \Cake\Http\Response|null|void Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
* @return \Cake\Http\Response|null|void Redirects on successful edit, renders view otherwise.
*/ */
public function edit($id = null) public function edit($id = null) {
{ $contactUsFormSubmission = $this->ContactUsFormSubmissions->get($id, contain: []);
$contactUsFormSubmission = $this->ContactUsFormSubmissions->get($id, contain: []); if ($this->request->is(['patch', 'post', 'put'])) {
if ($this->request->is(['patch', 'post', 'put'])) { $contactUsFormSubmission = $this->ContactUsFormSubmissions->patchEntity($contactUsFormSubmission, $this->request->getData());
$contactUsFormSubmission = $this->ContactUsFormSubmissions->patchEntity($contactUsFormSubmission, $this->request->getData()); if ($this->ContactUsFormSubmissions->save($contactUsFormSubmission)) {
if ($this->ContactUsFormSubmissions->save($contactUsFormSubmission)) { $this->Flash->success(__('The contact us form submission has been saved.'));
$this->Flash->success(__('The contact us form submission has been saved.'));
return $this->redirect(['action' => 'index']); return $this->redirect(['action' => 'index']);
} }
$this->Flash->error(__('The contact us form submission could not be saved. Please, try again.')); $this->Flash->error(__('The contact us form submission could not be saved. Please, try again.'));
} }
$this->set(compact('contactUsFormSubmission')); $this->set(compact('contactUsFormSubmission'));
} }
/** /**
* Delete method * Delete method
* *
* @param string|null $id Contact Us Form Submission id. * @param string|null $id Contact Us Form Submission id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
* @return \Cake\Http\Response|null Redirects to index.
*/ */
public function delete($id = null) public function delete($id = null) {
{ $this->request->allowMethod(['post', 'delete']);
$this->request->allowMethod(['post', 'delete']); $contactUsFormSubmission = $this->ContactUsFormSubmissions->get($id);
$contactUsFormSubmission = $this->ContactUsFormSubmissions->get($id); if ($this->ContactUsFormSubmissions->delete($contactUsFormSubmission)) {
if ($this->ContactUsFormSubmissions->delete($contactUsFormSubmission)) { $this->Flash->success(__('The contact us form submission has been deleted.'));
$this->Flash->success(__('The contact us form submission has been deleted.')); } else {
} else { $this->Flash->error(__('The contact us form submission could not be deleted. Please, try again.'));
$this->Flash->error(__('The contact us form submission could not be deleted. Please, try again.')); }
}
return $this->redirect(['action' => 'index']);
}
return $this->redirect(['action' => 'index']);
}
} }

View File

@@ -4,7 +4,6 @@ declare(strict_types=1);
namespace CakeContactUs\Controller\Component; namespace CakeContactUs\Controller\Component;
use Cake\Controller\Component; use Cake\Controller\Component;
use Cake\Controller\ComponentRegistry;
use Cake\Core\Configure; use Cake\Core\Configure;
use Cake\Datasource\EntityInterface; use Cake\Datasource\EntityInterface;
use Cake\Http\Response; use Cake\Http\Response;
@@ -12,158 +11,155 @@ use Cake\I18n\DateTime;
use Cake\Log\Log; use Cake\Log\Log;
use Cake\ORM\Table; use Cake\ORM\Table;
use Cake\ORM\TableRegistry; use Cake\ORM\TableRegistry;
use CakeContactUs\Model\Entity\ContactUsFormSubmission;
use CakeContactUs\Model\Table\ContactUsFormSubmissionsTable;
use Exception;
use CakeContactUs\CakeContactUsPlugin; use CakeContactUs\CakeContactUsPlugin;
use CakeContactUs\Model\Table\ContactUsFormSubmissionsTable;
/** /**
* ContactUs component * ContactUs component
*
* @property \Cake\Controller\Component\FlashComponent $Flash
*/ */
class ContactUsComponent extends Component class ContactUsComponent extends Component {
{
/**
* @var ContactUsFormSubmissionsTable|Table
*/
protected ContactUsFormSubmissionsTable|Table $ContactUsFormSubmissions;
/** /**
* @var \CakeContactUs\Model\Table\ContactUsFormSubmissionsTable|\Cake\ORM\Table
*/
protected ContactUsFormSubmissionsTable|Table $ContactUsFormSubmissions;
/**
* Default configuration. * Default configuration.
* *
* @var array<string, mixed> * @var array<string, mixed>
*/ */
protected array $_defaultConfig = []; protected array $_defaultConfig = [];
/** /**
* @var array|string[] * @var array|string[]
*/ */
protected array $components = ['Flash']; protected array $components = ['Flash'];
/** /**
* @param array $config * @param array $config
* @throws \Exception
* @return void * @return void
* *
* @throws Exception
*/ */
public function initialize(array $config): void public function initialize(array $config): void {
{ parent::initialize($config); // TODO: Change the autogenerated stub
parent::initialize($config); // TODO: Change the autogenerated stub
$this->ContactUsFormSubmissions = TableRegistry::getTableLocator()->get('CakeContactUs.ContactUsFormSubmissions'); $this->ContactUsFormSubmissions = TableRegistry::getTableLocator()->get('CakeContactUs.ContactUsFormSubmissions');
$requireCaptcha = Configure::readOrFail('ContactUs.fields.captcha'); $requireCaptcha = Configure::readOrFail('ContactUs.fields.captcha');
$this->setConfig('redirectUrl', Configure::read('ContactUs.redirectUrl', '/')); $this->setConfig('redirectUrl', Configure::read('ContactUs.redirectUrl', '/'));
$this->setConfig('addIdToRedirect', Configure::read('ContactUs.addIdToRedirect', false)); $this->setConfig('addIdToRedirect', Configure::read('ContactUs.addIdToRedirect', false));
$this->setConfig('requireEmail', Configure::readOrFail('ContactUs.fields.email')); $this->setConfig('requireEmail', Configure::readOrFail('ContactUs.fields.email'));
$this->setConfig('requireCaptcha', $requireCaptcha); $this->setConfig('requireCaptcha', $requireCaptcha);
if ($requireCaptcha) { if ($requireCaptcha) {
// $this->_registry->load('Captcha.Captcha'); // $this->_registry->load('Captcha.Captcha');
$this->getController()->viewBuilder()->addHelpers(['Captcha.Captcha']); $this->getController()->viewBuilder()->addHelpers(['Captcha.Captcha']);
} }
} }
/** /**
* @return EntityInterface|ContactUsFormSubmission * @return \Cake\Datasource\EntityInterface|\CakeContactUs\Model\Entity\ContactUsFormSubmission
*/ */
public function newContactUsForm() public function newContactUsForm() {
{ if ($this->getConfig('requireCaptcha')) {
if ($this->getConfig('requireCaptcha')) { $this->ContactUsFormSubmissions->addBehavior('Captcha.Captcha');
$this->ContactUsFormSubmissions->addBehavior('Captcha.Captcha'); }
}
return $this->ContactUsFormSubmissions->newEmptyEntity(); return $this->ContactUsFormSubmissions->newEmptyEntity();
} }
/** /**
* @return EntityInterface|ContactUsFormSubmission * @return \Cake\Http\Response|null|void
*/ */
public function processContactUsForm(EntityInterface $contactUsFormSubmission, array|null $postData) public function processContactUsForm(EntityInterface $contactUsFormSubmission, array|null $postData) {
{ if (!isset($postData)) {
if (!isset($postData)) { $postData = $this->getController()->getRequest()->getData();
$postData = $this->getController()->getRequest()->getData(); }
} $postData['client_ip'] = array_key_exists('client_ip', $postData) && $postData['client_ip'] ?
$postData['client_ip'] = array_key_exists('client_ip', $postData) && $postData['client_ip'] ? $postData['client_ip'] :
$postData['client_ip'] : ($this->getConfig('clientIpHeader') ?
($this->getConfig('clientIpHeader') ? $this->getController()->getRequest()->getHeaderLine($this->getConfig('clientIpHeader')) :
$this->getController()->getRequest()->getHeaderLine($this->getConfig('clientIpHeader')) : $this->getController()->getRequest()->clientIp()
$this->getController()->getRequest()->clientIp() );
); $postData['submitted_at'] = DateTime::now();
$postData['submitted_at'] = DateTime::now();
$event = $this->getController()->dispatchEvent(CakeContactUsPlugin::EVENT_BEFORE_CONTACT_US_FORM_SAVED, [ $event = $this->getController()->dispatchEvent(CakeContactUsPlugin::EVENT_BEFORE_CONTACT_US_FORM_SAVED, [
'contactUsFormSubmission' => $contactUsFormSubmission, 'contactUsFormSubmission' => $contactUsFormSubmission,
], $this->getController()); ], $this->getController());
$result = $event->getResult(); $result = $event->getResult();
Log::debug(print_r('$result', true)); Log::debug(print_r('$result', true));
Log::debug(print_r($result, true)); Log::debug(print_r($result, true));
if ($result instanceof EntityInterface) { if ($result instanceof EntityInterface) {
$postData = $result->toArray(); $postData = $result->toArray();
$contactUsFormSubmission = $this->ContactUsFormSubmissions->patchEntity($contactUsFormSubmission, $postData); $contactUsFormSubmission = $this->ContactUsFormSubmissions->patchEntity($contactUsFormSubmission, $postData);
if ($contactUsFormSubmission->getErrors()) { if ($contactUsFormSubmission->getErrors()) {
Log::debug(print_r('$contactUsFormSubmission->getErrors()', true)); Log::debug(print_r('$contactUsFormSubmission->getErrors()', true));
Log::debug(print_r($contactUsFormSubmission->getErrors(), true)); Log::debug(print_r($contactUsFormSubmission->getErrors(), true));
} }
$contactUsFormSubmissionSaved = $this->ContactUsFormSubmissions->save($contactUsFormSubmission); $contactUsFormSubmissionSaved = $this->ContactUsFormSubmissions->save($contactUsFormSubmission);
if ($contactUsFormSubmissionSaved) { if ($contactUsFormSubmissionSaved) {
return $this->_afterFormSaved($contactUsFormSubmissionSaved); return $this->_afterFormSaved($contactUsFormSubmissionSaved);
} }
// @TODO contact us form submission failed - handle here // @TODO contact us form submission failed - handle here
} }
if ($event->isStopped()) { if ($event->isStopped()) {
return $this->getController()->redirect($event->getResult()); return $this->getController()->redirect($event->getResult());
} }
if (!$this->getController()->getRequest()->is('post')) { if (!$this->getController()->getRequest()->is('post')) {
return; return;
} }
$contactUsFormSubmission = $this->ContactUsFormSubmissions->patchEntity($contactUsFormSubmission, $postData); $contactUsFormSubmission = $this->ContactUsFormSubmissions->patchEntity($contactUsFormSubmission, $postData);
if ($contactUsFormSubmission->getErrors()) { if ($contactUsFormSubmission->getErrors()) {
Log::debug(print_r('$contactUsFormSubmission->getErrors()', true)); Log::debug(print_r('$contactUsFormSubmission->getErrors()', true));
Log::debug(print_r($contactUsFormSubmission->getErrors(), true)); Log::debug(print_r($contactUsFormSubmission->getErrors(), true));
} }
$contactUsFormSubmissionSaved = $this->ContactUsFormSubmissions->save($contactUsFormSubmission);
$contactUsFormSubmissionSaved = $this->ContactUsFormSubmissions->save($contactUsFormSubmission); if ($contactUsFormSubmissionSaved) {
return $this->_afterFormSaved($contactUsFormSubmissionSaved);
}
$message = __d('cake_contact_us', 'Something doesn\'t look quite right. Please try again.');
if ($contactUsFormSubmissionSaved) { $this->Flash->error($message);
return $this->_afterFormSaved($contactUsFormSubmissionSaved);
}
$message = __d('cake_contact_us', 'Something doesn\'t look quite right. Please try again.');
$this->Flash->error($message); // @TODO contact us form submission failed - handle here
$this->getController()->set(['contactUsFormSubmission' => $contactUsFormSubmission]);
}
// @TODO contact us form submission failed - handle here /**
$this->getController()->set(['contactUsFormSubmission' => $contactUsFormSubmission]);
}
/**
* Prepare flash messages after registration, and dispatch afterRegister event * Prepare flash messages after registration, and dispatch afterRegister event
* *
* @param \Cake\Datasource\EntityInterface|ContactUsFormSubmission $contactUsFormSubmissionSaved Contact us form submission entity * @param \Cake\Datasource\EntityInterface|\CakeContactUs\Model\Entity\ContactUsFormSubmission $contactUsFormSubmissionSaved Contact us form submission entity
* @return \Cake\Http\Response * @return \Cake\Http\Response
*/ */
protected function _afterFormSaved(EntityInterface $contactUsFormSubmissionSaved) protected function _afterFormSaved(EntityInterface $contactUsFormSubmissionSaved) {
{ $message = __d('cake_contact_us', 'Message received, thank you. We will be in touch soon.');
$message = __d('cake_contact_us', 'Message received, thank you. We will be in touch soon.'); $event = $this->getController()->dispatchEvent(CakeContactUsPlugin::EVENT_AFTER_CONTACT_US_FORM_SAVED, [
$event = $this->getController()->dispatchEvent(CakeContactUsPlugin::EVENT_AFTER_CONTACT_US_FORM_SAVED, [ 'contactUsFormSubmission' => $contactUsFormSubmissionSaved,
'contactUsFormSubmission' => $contactUsFormSubmissionSaved, ], $this->getController());
], $this->getController()); $result = $event->getResult();
$result = $event->getResult(); if ($result instanceof Response) {
if ($result instanceof Response) { return $result;
return $result; }
} $this->Flash->success($message);
$this->Flash->success($message);
$redirectUrl = $this->getConfig('redirectUrl');
Log::debug(print_r('$contactUsFormSubmissionSaved after save', true));
Log::debug(print_r($contactUsFormSubmissionSaved, true));
if ($this->getConfig('addIdToRedirect')) {
$redirectUrl[] = $contactUsFormSubmissionSaved->get($this->ContactUsFormSubmissions->getPrimaryKey());
}
return $this->getController()->redirect($redirectUrl);
}
$redirectUrl = $this->getConfig('redirectUrl');
Log::debug(print_r('$contactUsFormSubmissionSaved after save', true));
Log::debug(print_r($contactUsFormSubmissionSaved, true));
if ($this->getConfig('addIdToRedirect')) {
$redirectUrl[] = $contactUsFormSubmissionSaved->get($this->ContactUsFormSubmissions->getPrimaryKey());
}
return $this->getController()->redirect($redirectUrl);
}
} }

View File

@@ -8,27 +8,27 @@ use App\Controller\AppController;
/** /**
* ContactUsFormSubmissions Controller * ContactUsFormSubmissions Controller
* *
* @property \CakeContactUs\Controller\Component\ContactUsComponent $ContactUs
* @property \CakeContactUs\Model\Table\ContactUsFormSubmissionsTable $ContactUsFormSubmissions * @property \CakeContactUs\Model\Table\ContactUsFormSubmissionsTable $ContactUsFormSubmissions
*/ */
class ContactUsFormSubmissionsController extends AppController class ContactUsFormSubmissionsController extends AppController {
{
public function initialize(): void
{
parent::initialize(); // TODO: Change the autogenerated stub
$this->loadComponent('CakeContactUs.ContactUs');
}
/** public function initialize(): void {
parent::initialize(); // TODO: Change the autogenerated stub
$this->loadComponent('CakeContactUs.ContactUs');
}
/**
* Add method * Add method
* *
* @return \Cake\Http\Response|null|void Redirects on successful add, renders view otherwise. * @return \Cake\Http\Response|null|void Redirects on successful add, renders view otherwise.
*/ */
public function add() public function add() {
{ $contactUsFormSubmission = $this->ContactUs->newContactUsForm();
$contactUsFormSubmission = $this->ContactUs->newContactUsForm(); if ($this->request->is('post')) {
if ($this->request->is('post')) { return $this->ContactUs->processContactUsForm($contactUsFormSubmission, $this->request->getData());
return $this->ContactUs->processContactUsForm($contactUsFormSubmission, $this->request->getData()); }
} $this->set(compact('contactUsFormSubmission'));
$this->set(compact('contactUsFormSubmission')); }
}
} }

View File

@@ -4,72 +4,73 @@ declare(strict_types=1);
namespace CakeContactUs\Mailer; namespace CakeContactUs\Mailer;
use Cake\Core\Configure; use Cake\Core\Configure;
use Cake\Datasource\EntityInterface;
use Cake\Mailer\Mailer; use Cake\Mailer\Mailer;
use Cake\Mailer\Message; use Cake\Mailer\Message;
use CakeContactUs\Model\Entity\ContactUsFormSubmission;
/** /**
* User Mailer * User Mailer
*/ */
class ContactUsFormSubmissionsMailer extends Mailer class ContactUsFormSubmissionsMailer extends Mailer {
{
/** /**
* Send the templated email to the user * Send the confirmation email to the user
* *
* @param \Cake\Datasource\EntityInterface $user User entity * @param \CakeContactUs\Model\Entity\ContactUsFormSubmission $contactUsFormSubmission contact us form submission entity
* @param array $options
* @return void * @return void
*/ */
protected function confirmation(EntityInterface $contactUsFormSubmission, array $options = []) protected function confirmation(ContactUsFormSubmission $contactUsFormSubmission, array $options = []) {
{ $name = isset($contactUsFormSubmission->name) ? $contactUsFormSubmission->name . ', ' : '';
$name = isset($contactUsFormSubmission['name']) ? $contactUsFormSubmission['name'] . ', ' : ''; $subject = __d('cake_contact_us', 'We have received your message');
$subject = __d('cake_contact_us', 'We have received your message');
$this $this
->setTo($contactUsFormSubmission['email']) ->setTo($contactUsFormSubmission->email)
->setSubject($name . $subject) ->setSubject($name . $subject)
->setEmailFormat(Message::MESSAGE_BOTH) ->setEmailFormat(Message::MESSAGE_BOTH)
->setViewVars([ ->setViewVars([
'contactUsFormSubmission' => $contactUsFormSubmission, 'contactUsFormSubmission' => $contactUsFormSubmission,
]); ]);
$this->viewBuilder() $this->viewBuilder()
->setTemplate('CakeContactUs.confirmation'); ->setTemplate('CakeContactUs.confirmation');
} }
/** /**
* Send to backoffice to take action * Send to backoffice to take action
* *
* @param \Cake\Datasource\EntityInterface $user User entity * @param \CakeContactUs\Model\Entity\ContactUsFormSubmission $contactUsFormSubmission contact us form submission entity
* @param array $options
* @return void * @return void
*/ */
protected function backend(EntityInterface $contactUsFormSubmission, array $options = []) protected function backend(ContactUsFormSubmission $contactUsFormSubmission, array $options = []) {
{ $subject = __d('cake_contact_us', 'Contact Us Form Submitted');
$subject = __d('cake_contact_us', 'Contact Us Form Submitted'); $name = isset($contactUsFormSubmission->name) ? ' by ' . $contactUsFormSubmission->name : '';
$name = isset($contactUsFormSubmission['name']) ? ' by ' . $contactUsFormSubmission['name'] : '';
$to = Configure::readOrFail('ContactUs.email.backend.to'); $to = Configure::readOrFail('ContactUs.email.backend.to');
$cc = Configure::read('ContactUs.email.backend.cc', []); $cc = Configure::read('ContactUs.email.backend.cc', []);
$bcc = Configure::read('ContactUs.email.backend.bcc', []); $bcc = Configure::read('ContactUs.email.backend.bcc', []);
$to = !is_array($to) ? [$to] : $to; $to = !is_array($to) ? [$to] : $to;
$this $this
->setTo($to) ->setTo($to)
->setSubject($subject . $name) ->setSubject($subject . $name)
->setEmailFormat(Message::MESSAGE_BOTH) ->setEmailFormat(Message::MESSAGE_BOTH)
->setViewVars([ ->setViewVars([
'contactUsFormSubmission' => $contactUsFormSubmission, 'contactUsFormSubmission' => $contactUsFormSubmission,
]); ]);
if ($cc) { if ($cc) {
$cc = !is_array($cc) ? [$cc] : $cc; $cc = !is_array($cc) ? [$cc] : $cc;
$this->setCc($to); $this->setCc($to);
} }
if ($bcc) { if ($bcc) {
$bcc = !is_array($bcc) ? [$bcc] : $bcc; $bcc = !is_array($bcc) ? [$bcc] : $bcc;
$this->setBcc($bcc); $this->setBcc($bcc);
} }
$this->viewBuilder()
->setTemplate('CakeContactUs.backend');
}
$this->viewBuilder()
->setTemplate('CakeContactUs.backend');
}
} }

View File

@@ -18,9 +18,9 @@ use Cake\ORM\Entity;
* @property \Cake\I18n\DateTime|null $confirm_email_sent * @property \Cake\I18n\DateTime|null $confirm_email_sent
* @property \Cake\I18n\DateTime|null $backend_email_sent * @property \Cake\I18n\DateTime|null $backend_email_sent
*/ */
class ContactUsFormSubmission extends Entity class ContactUsFormSubmission extends Entity {
{
/** /**
* Fields that can be mass assigned using newEntity() or patchEntity(). * Fields that can be mass assigned using newEntity() or patchEntity().
* *
* Note that when '*' is set to true, this allows all unspecified fields to * Note that when '*' is set to true, this allows all unspecified fields to
@@ -29,14 +29,15 @@ class ContactUsFormSubmission extends Entity
* *
* @var array<string, bool> * @var array<string, bool>
*/ */
protected array $_accessible = [ protected array $_accessible = [
'submitted_at' => true, 'submitted_at' => true,
'client_ip' => true, 'client_ip' => true,
'name' => true, 'name' => true,
'email' => true, 'email' => true,
'subject' => true, 'subject' => true,
'message' => true, 'message' => true,
'confirm_email_sent' => true, 'confirm_email_sent' => true,
'backend_email_sent' => true, 'backend_email_sent' => true,
]; ];
} }

View File

@@ -3,151 +3,144 @@ declare(strict_types=1);
namespace CakeContactUs\Model\Table; namespace CakeContactUs\Model\Table;
use ArrayObject;
use Cake\Core\Configure; use Cake\Core\Configure;
use Cake\Core\Exception\CakeException; use Cake\Core\Exception\CakeException;
use Cake\Datasource\EntityInterface; use Cake\Datasource\EntityInterface;
use Cake\Datasource\ResultSetInterface;
use Cake\Event\EventInterface; use Cake\Event\EventInterface;
use Cake\I18n\DateTime; use Cake\I18n\DateTime;
use Cake\Log\Log;
use Cake\Mailer\MailerAwareTrait; use Cake\Mailer\MailerAwareTrait;
use Cake\ORM\Query\SelectQuery;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table; use Cake\ORM\Table;
use Cake\Validation\Validator; use Cake\Validation\Validator;
use CakeContactUs\CakeContactUsPlugin; use CakeContactUs\CakeContactUsPlugin;
use CakeContactUs\Model\Entity\ContactUsFormSubmission; use CakeContactUs\Model\Entity\ContactUsFormSubmission;
use Closure;
use Psr\SimpleCache\CacheInterface;
/** /**
* ContactUsFormSubmissions Model * ContactUsFormSubmissions Model
* *
* @method ContactUsFormSubmission newEmptyEntity() * @method \CakeContactUs\Model\Entity\ContactUsFormSubmission newEmptyEntity()
* @method ContactUsFormSubmission newEntity(array $data, array $options = []) * @method \CakeContactUs\Model\Entity\ContactUsFormSubmission newEntity(array $data, array $options = [])
* @method array<ContactUsFormSubmission> newEntities(array $data, array $options = []) * @method array<ContactUsFormSubmission> newEntities(array $data, array $options = [])
* @method ContactUsFormSubmission get(mixed $primaryKey, array|string $finder = 'all', CacheInterface|string|null $cache = null, Closure|string|null $cacheKey = null, mixed ...$args) * @method \CakeContactUs\Model\Entity\ContactUsFormSubmission get(mixed $primaryKey, array|string $finder = 'all', \Psr\SimpleCache\CacheInterface|string|null $cache = null, \Closure|string|null $cacheKey = null, mixed ...$args)
* @method ContactUsFormSubmission findOrCreate($search, ?callable $callback = null, array $options = []) * @method \CakeContactUs\Model\Entity\ContactUsFormSubmission findOrCreate($search, ?callable $callback = null, array $options = [])
* @method ContactUsFormSubmission patchEntity(EntityInterface $entity, array $data, array $options = []) * @method \CakeContactUs\Model\Entity\ContactUsFormSubmission patchEntity(EntityInterface $entity, array $data, array $options = [])
* @method array<ContactUsFormSubmission> patchEntities(iterable $entities, array $data, array $options = []) * @method array<ContactUsFormSubmission> patchEntities(iterable $entities, array $data, array $options = [])
* @method ContactUsFormSubmission|false save(EntityInterface $entity, array $options = []) * @method ContactUsFormSubmission|false save(EntityInterface $entity, array $options = [])
* @method ContactUsFormSubmission saveOrFail(EntityInterface $entity, array $options = []) * @method \CakeContactUs\Model\Entity\ContactUsFormSubmission saveOrFail(\Cake\Datasource\EntityInterface $entity, array $options = [])
* @method iterable<ContactUsFormSubmission>|ResultSetInterface<ContactUsFormSubmission>|false saveMany(iterable $entities, array $options = []) * @method iterable<ContactUsFormSubmission>|\Cake\Datasource\ResultSetInterface<ContactUsFormSubmission>|false saveMany(iterable $entities, array $options = [])
* @method iterable<ContactUsFormSubmission>|ResultSetInterface<ContactUsFormSubmission> saveManyOrFail(iterable $entities, array $options = []) * @method iterable<ContactUsFormSubmission>|\Cake\Datasource\ResultSetInterface<ContactUsFormSubmission> saveManyOrFail(iterable $entities, array $options = [])
* @method iterable<ContactUsFormSubmission>|ResultSetInterface<ContactUsFormSubmission>|false deleteMany(iterable $entities, array $options = []) * @method iterable<ContactUsFormSubmission>|\Cake\Datasource\ResultSetInterface<ContactUsFormSubmission>|false deleteMany(iterable $entities, array $options = [])
* @method iterable<ContactUsFormSubmission>|ResultSetInterface<ContactUsFormSubmission> deleteManyOrFail(iterable $entities, array $options = []) * @method iterable<ContactUsFormSubmission>|\Cake\Datasource\ResultSetInterface<ContactUsFormSubmission> deleteManyOrFail(iterable $entities, array $options = [])
*/ */
class ContactUsFormSubmissionsTable extends Table class ContactUsFormSubmissionsTable extends Table {
{
use MailerAwareTrait;
/** use MailerAwareTrait;
/**
* Initialize method * Initialize method
* *
* @param array<string, mixed> $config The configuration for the Table. * @param array<string, mixed> $config The configuration for the Table.
* @return void * @return void
*/ */
public function initialize(array $config): void public function initialize(array $config): void {
{ parent::initialize($config);
parent::initialize($config);
$this->setTable('contact_us_form_submissions'); $this->setTable('contact_us_form_submissions');
$this->setDisplayField('name'); $this->setDisplayField('name');
$this->setPrimaryKey('id'); $this->setPrimaryKey('id');
} }
/** /**
* Default validation rules. * Default validation rules.
* *
* @param Validator $validator Validator instance. * @param \Cake\Validation\Validator $validator Validator instance.
* @return Validator * @return \Cake\Validation\Validator
*/ */
public function validationDefault(Validator $validator): Validator public function validationDefault(Validator $validator): Validator {
{ $fields = Configure::readOrFail('ContactUs.fields');
$fields = Configure::readOrFail('ContactUs.fields'); $validator
$validator ->dateTime('submitted_at')
->dateTime('submitted_at') ->requirePresence('submitted_at', 'create')
->requirePresence('submitted_at', 'create') ->notEmptyDateTime('submitted_at');
->notEmptyDateTime('submitted_at');
$validator $validator
->scalar('client_ip') ->scalar('client_ip')
->maxLength('client_ip', 45) ->maxLength('client_ip', 45)
->allowEmptyString('client_ip'); ->allowEmptyString('client_ip');
$validator $validator
->scalar('name') ->scalar('name')
->maxLength('name', 255) ->maxLength('name', 255)
->requirePresence('name', 'create') ->requirePresence('name', 'create')
->notEmptyString('name'); ->notEmptyString('name');
// email // email
$validator->email('email'); $validator->email('email');
if ($fields['email'] ?? false) { if ($fields['email'] ?? false) {
$validator->notEmptyString('email'); $validator->notEmptyString('email');
} else { } else {
$validator->allowEmptyString('email'); $validator->allowEmptyString('email');
} }
// subject // subject
$validator $validator
->scalar('subject') ->scalar('subject')
->maxLength('subject', 255); ->maxLength('subject', 255);
if ($fields['subject'] ?? false) { if ($fields['subject'] ?? false) {
$validator->notEmptyString('subject'); $validator->notEmptyString('subject');
} else { } else {
$validator->allowEmptyString('subject'); $validator->allowEmptyString('subject');
} }
$validator $validator
->scalar('message') ->scalar('message')
->requirePresence('message', 'create') ->requirePresence('message', 'create')
->notEmptyString('message'); ->notEmptyString('message');
$validator $validator
->dateTime('confirm_email_sent') ->dateTime('confirm_email_sent')
->allowEmptyDateTime('confirm_email_sent'); ->allowEmptyDateTime('confirm_email_sent');
$validator $validator
->dateTime('backend_email_sent') ->dateTime('backend_email_sent')
->allowEmptyDateTime('backend_email_sent'); ->allowEmptyDateTime('backend_email_sent');
return $validator; return $validator;
} }
/** /**
* @param EventInterface $event * @param \Cake\Event\EventInterface $event
* @param EntityInterface|ContactUsFormSubmission $contactUsFormSubmission * @param \Cake\Datasource\EntityInterface|\CakeContactUs\Model\Entity\ContactUsFormSubmission $contactUsFormSubmission
* @param \ArrayObject $options * @param \ArrayObject $options
* @return void * @return void
*/ */
public function afterSave(EventInterface $event, EntityInterface|ContactUsFormSubmission $contactUsFormSubmission, \ArrayObject $options) public function afterSave(EventInterface $event, EntityInterface|ContactUsFormSubmission $contactUsFormSubmission, ArrayObject $options) {
{ if (!$contactUsFormSubmission->isNew()) {
if (!$contactUsFormSubmission->isNew()) { return;
return; }
} $now = DateTime::now()->format(CakeContactUsPlugin::CAKE_CONTACT_US_MYSQL_DATETIME);
$now = DateTime::now()->format(CakeContactUsPlugin::CAKE_CONTACT_US_MYSQL_DATETIME); $updateData = [];
$updateData = []; if (Configure::read('ContactUs.email.confirmation', false) && isset($contactUsFormSubmission->email)) {
if (Configure::read('ContactUs.email.confirmation', false) && isset($contactUsFormSubmission->email)) { $mailer = Configure::read('ContactUs.email.mailerClass', 'CakeContactUs.ContactUsFormSubmissions');
$mailer = Configure::read('ContactUs.email.mailerClass', 'CakeContactUs.ContactUsFormSubmissions'); try {
try { $this->getMailer($mailer)->send('confirmation', [$contactUsFormSubmission]);
$this->getMailer($mailer)->send('confirmation', [$contactUsFormSubmission]); $updateData['confirm_email_sent'] = $now;
$updateData['confirm_email_sent'] = $now; } catch (CakeException $exception) {
} catch (CakeException $exception) { }
} }
}
if (Configure::read('ContactUs.email.backend.enabled', false)) {
$mailer = Configure::read('ContactUs.email.mailerClass', 'CakeContactUs.ContactUsFormSubmissions');
try {
$this->getMailer($mailer)->send('backend', [$contactUsFormSubmission]);
$updateData['backend_email_sent'] = $now;
} catch (CakeException $exception) {
}
}
if ($updateData) {
$contactUsFormSubmission = $this->patchEntity($contactUsFormSubmission, $updateData, ['validate' => false]);
$this->saveOrFail($contactUsFormSubmission);
}
}
if (Configure::read('ContactUs.email.backend.enabled', false)) {
$mailer = Configure::read('ContactUs.email.mailerClass', 'CakeContactUs.ContactUsFormSubmissions');
try {
$this->getMailer($mailer)->send('backend', [$contactUsFormSubmission]);
$updateData['backend_email_sent'] = $now;
} catch (CakeException $exception) {
}
}
if ($updateData) {
$contactUsFormSubmission = $this->patchEntity($contactUsFormSubmission, $updateData, ['validate' => false]);
$this->saveOrFail($contactUsFormSubmission);
}
}
} }

View File

@@ -8,28 +8,28 @@ use Cake\TestSuite\Fixture\TestFixture;
/** /**
* ContactUsFormSubmissionsFixture * ContactUsFormSubmissionsFixture
*/ */
class ContactUsFormSubmissionsFixture extends TestFixture class ContactUsFormSubmissionsFixture extends TestFixture {
{
/** /**
* Init method * Init method
* *
* @return void * @return void
*/ */
public function init(): void public function init(): void {
{ $this->records = [
$this->records = [ [
[ 'id' => '76fbe7fb-1949-4670-a3d2-c0b48eb98e8d',
'id' => '76fbe7fb-1949-4670-a3d2-c0b48eb98e8d', 'submitted_at' => '2025-01-03 09:16:50',
'submitted_at' => '2025-01-03 09:16:50', 'client_ip' => 'Lorem ipsum dolor sit amet',
'client_ip' => 'Lorem ipsum dolor sit amet', 'name' => 'Lorem ipsum dolor sit amet',
'name' => 'Lorem ipsum dolor sit amet', 'email' => 'Lorem ipsum dolor sit amet',
'email' => 'Lorem ipsum dolor sit amet', 'subject' => 'Lorem ipsum dolor sit amet',
'subject' => 'Lorem ipsum dolor sit amet', 'message' => 'Lorem ipsum dolor sit amet, aliquet feugiat. Convallis morbi fringilla gravida, phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla vestibulum massa neque ut et, id hendrerit sit, feugiat in taciti enim proin nibh, tempor dignissim, rhoncus duis vestibulum nunc mattis convallis.',
'message' => 'Lorem ipsum dolor sit amet, aliquet feugiat. Convallis morbi fringilla gravida, phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla vestibulum massa neque ut et, id hendrerit sit, feugiat in taciti enim proin nibh, tempor dignissim, rhoncus duis vestibulum nunc mattis convallis.', 'confirm_email_sent' => '2025-01-03 09:16:50',
'confirm_email_sent' => '2025-01-03 09:16:50', 'backend_email_sent' => '2025-01-03 09:16:50',
'backend_email_sent' => '2025-01-03 09:16:50', ],
], ];
]; parent::init();
parent::init(); }
}
} }

View File

@@ -4,42 +4,74 @@ declare(strict_types=1);
namespace CakeContactUs\Test\TestCase\Controller\Component; namespace CakeContactUs\Test\TestCase\Controller\Component;
use Cake\Controller\ComponentRegistry; use Cake\Controller\ComponentRegistry;
use Cake\Controller\Controller;
use Cake\Http\ServerRequest;
use Cake\TestSuite\TestCase; use Cake\TestSuite\TestCase;
use CakeContactUs\Controller\Component\ContactUsComponent; use CakeContactUs\Controller\Component\ContactUsComponent;
use CakeContactUs\Model\Entity\ContactUsFormSubmission;
/** /**
* CakeContactUs\Controller\Component\ContactUsComponent Test Case * CakeContactUs\Controller\Component\ContactUsComponent Test Case
*/ */
class ContactUsComponentTest extends TestCase class ContactUsComponentTest extends TestCase {
{
/** protected ContactUsComponent $component;
* Test subject protected Controller $controller;
*
* @var \CakeContactUs\Controller\Component\ContactUsComponent
*/
protected $ContactUs;
/** /**
* Fixtures
*
* @var array<string>
*/
protected array $fixtures = [
'plugin.CakeContactUs.ContactUsFormSubmissions',
];
/**
* setUp method * setUp method
* *
* @return void * @return void
*/ */
protected function setUp(): void protected function setUp(): void {
{ parent::setUp();
parent::setUp(); $request = new ServerRequest();
$registry = new ComponentRegistry(); $this->controller = new Controller($request);
$this->ContactUs = new ContactUsComponent($registry); $registry = new ComponentRegistry($this->controller);
}
/** $this->component = new ContactUsComponent($registry);
}
/**
* tearDown method * tearDown method
* *
* @return void * @return void
*/ */
protected function tearDown(): void protected function tearDown(): void {
{ unset($this->component);
unset($this->ContactUs);
parent::tearDown(); parent::tearDown();
}
public function testNewContactUsFormWithoutCaptcha()
{
$this->assertInstanceOf(ContactUsFormSubmission::class, $this->component->newContactUsForm());
}
public function testNewContactUsFormWithCaptcha()
{
$this->component->setConfig('requireCaptcha', true);
$this->assertInstanceOf(ContactUsFormSubmission::class, $this->component->newContactUsForm());
}
public function testProcessContactUsFormSaved()
{
$numSubmissionsBefore = $this->fetchTable('CakeContactUs/ContactUsFormSubmissions')->find()->count();
$result = $this->component->processContactUsForm($this->component->newContactUsForm(), [
'name' => 'Jane Doe',
'email' => 'test@example.com',
]);
$this->assertNotInstanceOf(ContactUsFormSubmission::class, $result);
$numSubmissionsAfter = $this->fetchTable('CakeContactUs/ContactUsFormSubmissions')->find()->count();
$this->assertEquals($numSubmissionsBefore + 1, $numSubmissionsAfter);
} }
} }

View File

@@ -3,317 +3,304 @@ declare(strict_types=1);
namespace CakeContactUs\Test\TestCase\Controller; namespace CakeContactUs\Test\TestCase\Controller;
use App\Model\Table\ContactUsFormSubmissionsTable;
use Cake\Controller\Controller;
use Cake\Core\Configure; use Cake\Core\Configure;
use Cake\Event\EventList; use Cake\Event\EventList;
use Cake\Event\EventManager; use Cake\Event\EventManager;
use Cake\Http\ServerRequest;
use Cake\Mailer\Transport\DebugTransport; use Cake\Mailer\Transport\DebugTransport;
use Cake\ORM\Table;
use Cake\TestSuite\EmailTrait; use Cake\TestSuite\EmailTrait;
use Cake\TestSuite\IntegrationTestTrait; use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase; use Cake\TestSuite\TestCase;
use CakeContactUs\CakeContactUsPlugin; use CakeContactUs\CakeContactUsPlugin;
use CakeContactUs\Controller\ContactUsFormSubmissionsController;
use PHPUnit\Exception;
/** /**
* CakeContactUs\Controller\ContactUsFormSubmissionsController Test Case * CakeContactUs\Controller\ContactUsFormSubmissionsController Test Case
* *
* @uses ContactUsFormSubmissionsController * @uses ContactUsFormSubmissionsController
*/ */
class ContactUsFormSubmissionsControllerTest extends TestCase class ContactUsFormSubmissionsControllerTest extends TestCase {
{
use IntegrationTestTrait;
use EmailTrait;
/** use IntegrationTestTrait;
* @var ContactUsFormSubmissionsTable|Table use EmailTrait;
/**
* @var \App\Model\Table\ContactUsFormSubmissionsTable|\Cake\ORM\Table
*/ */
protected $ContactUsFormSubmissions; protected $ContactUsFormSubmissions;
/** /**
* Fixtures * Fixtures
* *
* @var array<string> * @var array<string>
*/ */
protected array $fixtures = [ protected array $fixtures = [
'plugin.CakeContactUs.ContactUsFormSubmissions', 'plugin.CakeContactUs.ContactUsFormSubmissions',
]; ];
/** /**
* setUp method * setUp method
* *
* @return void * @return void
*/ */
protected function setUp(): void protected function setUp(): void {
{ parent::setUp();
parent::setUp(); $this->ContactUsFormSubmissions = $this->getTableLocator()->get('ContactUsFormSubmissions');
$this->ContactUsFormSubmissions = $this->getTableLocator()->get('ContactUsFormSubmissions');
EventManager::instance()->setEventList(new EventList()); EventManager::instance()->setEventList(new EventList());
} }
/** /**
* tearDown method * tearDown method
* *
* @return void * @return void
*/ */
protected function tearDown(): void protected function tearDown(): void {
{ unset($this->ContactUsFormSubmissions);
unset($this->ContactUsFormSubmissions);
parent::tearDown(); parent::tearDown();
} }
/** /**
* Test add method * Test add method
* *
* Tests the add action with a logged in user * Tests the add action with a logged in user
* *
* @return void * @uses ContactUsFormSubmissionsController::add
* @throws Exception * @throws Exception
* *
* @uses ContactUsFormSubmissionsController::add * @return void
*/ */
public function testAddGet(): void public function testAddGet(): void {
{ $cntBefore = $this->ContactUsFormSubmissions->find()->count();
$cntBefore = $this->ContactUsFormSubmissions->find()->count();
$url = [ $url = [
'plugin' => 'CakeContactUs', 'plugin' => 'CakeContactUs',
'controller' => 'ContactUsFormSubmissions', 'controller' => 'ContactUsFormSubmissions',
'action' => 'add', 'action' => 'add',
]; ];
$this->get($url); $this->get($url);
$this->assertResponseCode(200); $this->assertResponseCode(200);
$cntAfter = $this->ContactUsFormSubmissions->find()->count(); $cntAfter = $this->ContactUsFormSubmissions->find()->count();
$this->assertEquals($cntBefore, $cntAfter); $this->assertEquals($cntBefore, $cntAfter);
$this->assertNoMailSent(); $this->assertNoMailSent();
} }
/** /**
* Test add method * Test add method
* *
* Tests a POST request to the add action with a logged in user * Tests a POST request to the add action with a logged in user
* *
* @uses ContactUsFormSubmissionsController::add
* @throws Exception
*
* @return void * @return void
* @throws Exception
*
* @uses ContactUsFormSubmissionsController::add
*/ */
public function testAddPostSuccessNoEmail(): void public function testAddPostSuccessNoEmail(): void {
{ $cntBefore = $this->ContactUsFormSubmissions->find()->count();
$cntBefore = $this->ContactUsFormSubmissions->find()->count();
$url = [ $url = [
'plugin' => 'CakeContactUs', 'plugin' => 'CakeContactUs',
'controller' => 'ContactUsFormSubmissions', 'controller' => 'ContactUsFormSubmissions',
'action' => 'add', 'action' => 'add',
]; ];
$data = [ $data = [
'name' => 'valid name', 'name' => 'valid name',
'email' => 'valid_email@test.com', 'email' => 'valid_email@test.com',
'message' => 'valid message goes here', 'message' => 'valid message goes here',
]; ];
$this->post($url, $data); $this->post($url, $data);
$this->assertResponseCode(302); $this->assertResponseCode(302);
$cntAfter = $this->ContactUsFormSubmissions->find()->count(); $cntAfter = $this->ContactUsFormSubmissions->find()->count();
$this->assertEquals($cntBefore + 1, $cntAfter); $this->assertEquals($cntBefore + 1, $cntAfter);
$this->assertEventFired(CakeContactUsPlugin::EVENT_AFTER_CONTACT_US_FORM_SAVED); $this->assertEventFired(CakeContactUsPlugin::EVENT_AFTER_CONTACT_US_FORM_SAVED);
$this->assertNoMailSent(); $this->assertNoMailSent();
} }
/** /**
* Test add method * Test add method
* *
* Tests a POST request to the add action with a logged in user * Tests a POST request to the add action with a logged in user
* *
* @return void * @uses ContactUsFormSubmissionsController::add
* @throws Exception * @throws Exception
* *
* @uses ContactUsFormSubmissionsController::add * @return void
*/ */
public function testAddPostSuccessBothEmailsSent(): void public function testAddPostSuccessBothEmailsSent(): void {
{ Configure::write('ContactUs', [
Configure::write('ContactUs', [ 'fields' => [
'fields' => [ 'captcha' => false,
'captcha' => false, 'email' => true,
'email' => true, ],
], 'email' => [
'email' => [ 'mailerClass' => 'CakeContactUs.ContactUsFormSubmissions',
'mailerClass' => 'CakeContactUs.ContactUsFormSubmissions', 'confirmation' => true, // true or false
'confirmation' => true, // true or false 'backend' => [ // array with enabled and the to/cc/bcc/ fields as strings or arrays
'backend' => [ // array with enabled and the to/cc/bcc/ fields as strings or arrays 'enabled' => true,
'enabled' => true, 'to' => 'test@example.com',
'to' => 'test@example.com', ],
], ],
], ]);
]); Configure::write('EmailTransport', [
Configure::write('EmailTransport', [ 'default' => [
'default' => [ 'className' => DebugTransport::class,
'className' => DebugTransport::class, ],
] ]);
]);
$cntBefore = $this->ContactUsFormSubmissions->find()->count(); $cntBefore = $this->ContactUsFormSubmissions->find()->count();
$url = [ $url = [
'plugin' => 'CakeContactUs', 'plugin' => 'CakeContactUs',
'controller' => 'ContactUsFormSubmissions', 'controller' => 'ContactUsFormSubmissions',
'action' => 'add', 'action' => 'add',
]; ];
$data = [ $data = [
'name' => 'valid name', 'name' => 'valid name',
'email' => 'valid_email@test.com', 'email' => 'valid_email@test.com',
'message' => 'valid message goes here', 'message' => 'valid message goes here',
]; ];
$this->post($url, $data); $this->post($url, $data);
$this->assertResponseCode(302); $this->assertResponseCode(302);
$cntAfter = $this->ContactUsFormSubmissions->find()->count(); $cntAfter = $this->ContactUsFormSubmissions->find()->count();
$this->assertEquals($cntBefore + 1, $cntAfter); $this->assertEquals($cntBefore + 1, $cntAfter);
$this->assertEventFired(CakeContactUsPlugin::EVENT_AFTER_CONTACT_US_FORM_SAVED); $this->assertEventFired(CakeContactUsPlugin::EVENT_AFTER_CONTACT_US_FORM_SAVED);
$this->assertMailCount(2); // confirmation + backend emails $this->assertMailCount(2); // confirmation + backend emails
} }
/** /**
* Test add method * Test add method
* *
* Tests a POST request to the add action with a logged in user * Tests a POST request to the add action with a logged in user
* *
* @return void * @uses ContactUsFormSubmissionsController::add
* @throws Exception * @throws Exception
* *
* @uses ContactUsFormSubmissionsController::add * @return void
*/ */
public function testAddPostSuccessConfirmationEmailSent(): void public function testAddPostSuccessConfirmationEmailSent(): void {
{ Configure::write('ContactUs', [
Configure::write('ContactUs', [ 'fields' => [
'fields' => [ 'captcha' => false,
'captcha' => false, 'email' => true,
'email' => true, ],
], 'email' => [
'email' => [ 'mailerClass' => 'CakeContactUs.ContactUsFormSubmissions',
'mailerClass' => 'CakeContactUs.ContactUsFormSubmissions', 'confirmation' => true, // true or false
'confirmation' => true, // true or false 'backend' => [ // array with enabled and the to/cc/bcc/ fields as strings or arrays
'backend' => [ // array with enabled and the to/cc/bcc/ fields as strings or arrays 'enabled' => false,
'enabled' => false, 'to' => 'test@example.com',
'to' => 'test@example.com', ],
], ],
], ]);
]); $cntBefore = $this->ContactUsFormSubmissions->find()->count();
$cntBefore = $this->ContactUsFormSubmissions->find()->count();
$url = [ $url = [
'plugin' => 'CakeContactUs', 'plugin' => 'CakeContactUs',
'controller' => 'ContactUsFormSubmissions', 'controller' => 'ContactUsFormSubmissions',
'action' => 'add', 'action' => 'add',
]; ];
$data = [ $data = [
'name' => 'valid name', 'name' => 'valid name',
'email' => 'valid_email@test.com', 'email' => 'valid_email@test.com',
'message' => 'valid message goes here', 'message' => 'valid message goes here',
]; ];
$this->post($url, $data); $this->post($url, $data);
$this->assertResponseCode(302); $this->assertResponseCode(302);
$cntAfter = $this->ContactUsFormSubmissions->find()->count(); $cntAfter = $this->ContactUsFormSubmissions->find()->count();
$this->assertEquals($cntBefore + 1, $cntAfter); $this->assertEquals($cntBefore + 1, $cntAfter);
$this->assertEventFired(CakeContactUsPlugin::EVENT_AFTER_CONTACT_US_FORM_SAVED); $this->assertEventFired(CakeContactUsPlugin::EVENT_AFTER_CONTACT_US_FORM_SAVED);
$this->assertMailCount(1); // confirmation only $this->assertMailCount(1); // confirmation only
} }
/** /**
* Test add method * Test add method
* *
* Tests a POST request to the add action with a logged in user * Tests a POST request to the add action with a logged in user
* *
* @return void * @uses ContactUsFormSubmissionsController::add
* @throws Exception * @throws Exception
* *
* @uses ContactUsFormSubmissionsController::add * @return void
*/ */
public function testAddPostSuccessBackendEmailSent(): void public function testAddPostSuccessBackendEmailSent(): void {
{ Configure::write('ContactUs', [
Configure::write('ContactUs', [ 'fields' => [
'fields' => [ 'captcha' => false,
'captcha' => false, 'email' => true,
'email' => true, ],
], 'email' => [
'email' => [ 'mailerClass' => 'CakeContactUs.ContactUsFormSubmissions',
'mailerClass' => 'CakeContactUs.ContactUsFormSubmissions', 'confirmation' => false, // true or false
'confirmation' => false, // true or false 'backend' => [ // array with enabled and the to/cc/bcc/ fields as strings or arrays
'backend' => [ // array with enabled and the to/cc/bcc/ fields as strings or arrays 'enabled' => true,
'enabled' => true, 'to' => 'test@example.com',
'to' => 'test@example.com', ],
], ],
], ]);
]);
$cntBefore = $this->ContactUsFormSubmissions->find()->count(); $cntBefore = $this->ContactUsFormSubmissions->find()->count();
$url = [ $url = [
'plugin' => 'CakeContactUs', 'plugin' => 'CakeContactUs',
'controller' => 'ContactUsFormSubmissions', 'controller' => 'ContactUsFormSubmissions',
'action' => 'add', 'action' => 'add',
]; ];
$data = [ $data = [
'name' => 'valid name', 'name' => 'valid name',
'email' => 'valid_email@test.com', 'email' => 'valid_email@test.com',
'message' => 'valid message goes here', 'message' => 'valid message goes here',
]; ];
$this->post($url, $data); $this->post($url, $data);
$responseBody = (string)$this->_response->getBody(); $responseBody = (string)$this->_response->getBody();
$tmpLog = fopen(TMP . 'phpunit.log', 'w'); $tmpLog = fopen(TMP . 'phpunit.log', 'w');
if ($tmpLog) { if ($tmpLog) {
fwrite($tmpLog, $responseBody); fwrite($tmpLog, $responseBody);
} }
$this->assertResponseCode(302); $this->assertResponseCode(302);
$cntAfter = $this->ContactUsFormSubmissions->find()->count(); $cntAfter = $this->ContactUsFormSubmissions->find()->count();
$this->assertEquals($cntBefore + 1, $cntAfter); $this->assertEquals($cntBefore + 1, $cntAfter);
$this->assertEventFired(CakeContactUsPlugin::EVENT_AFTER_CONTACT_US_FORM_SAVED); $this->assertEventFired(CakeContactUsPlugin::EVENT_AFTER_CONTACT_US_FORM_SAVED);
$this->assertMailCount(1); // backend email only $this->assertMailCount(1); // backend email only
} }
/** /**
* Test add method * Test add method
* *
* Tests a POST request to the add action with a logged in user * Tests a POST request to the add action with a logged in user
* *
* @return void * @uses ContactUsFormSubmissionsController::add
* @throws Exception * @throws Exception
* *
* @uses ContactUsFormSubmissionsController::add * @return void
*/ */
public function testAddPostLoggedInFailure(): void public function testAddPostLoggedInFailure(): void {
{ $cntBefore = $this->ContactUsFormSubmissions->find()->count();
$cntBefore = $this->ContactUsFormSubmissions->find()->count();
// $this->loginUserByRole('admin'); // $this->loginUserByRole('admin');
$url = [ $url = [
'plugin' => 'CakeContactUs', 'plugin' => 'CakeContactUs',
'controller' => 'ContactUsFormSubmissions', 'controller' => 'ContactUsFormSubmissions',
'action' => 'add', 'action' => 'add',
]; ];
$data = [ $data = [
'name' => 'valid name', 'name' => 'valid name',
'email' => 'not_valid_email', 'email' => 'not_valid_email',
'message' => 'this is a valid message ', 'message' => 'this is a valid message ',
]; ];
$this->post($url, $data); $this->post($url, $data);
$this->assertResponseCode(200); $this->assertResponseCode(200);
$cntAfter = $this->ContactUsFormSubmissions->find()->count();
$this->assertEquals($cntBefore, $cntAfter);
$this->assertEventFired(CakeContactUsPlugin::EVENT_BEFORE_CONTACT_US_FORM_SAVED);
$this->assertNoMailSent();
}
$cntAfter = $this->ContactUsFormSubmissions->find()->count();
$this->assertEquals($cntBefore, $cntAfter);
$this->assertEventFired(CakeContactUsPlugin::EVENT_BEFORE_CONTACT_US_FORM_SAVED);
$this->assertNoMailSent();
}
} }

View File

@@ -9,83 +9,80 @@ use CakeContactUs\Model\Table\ContactUsFormSubmissionsTable;
/** /**
* CakeContactUs\Model\Table\ContactUsFormSubmissionsTable Test Case * CakeContactUs\Model\Table\ContactUsFormSubmissionsTable Test Case
*/ */
class ContactUsFormSubmissionsTableTest extends TestCase class ContactUsFormSubmissionsTableTest extends TestCase {
{
/** /**
* Test subject * Test subject
* *
* @var \CakeContactUs\Model\Table\ContactUsFormSubmissionsTable * @var \CakeContactUs\Model\Table\ContactUsFormSubmissionsTable
*/ */
protected $ContactUsFormSubmissions; protected $ContactUsFormSubmissions;
/** /**
* Fixtures * Fixtures
* *
* @var array<string> * @var array<string>
*/ */
protected array $fixtures = [ protected array $fixtures = [
'plugin.CakeContactUs.ContactUsFormSubmissions', 'plugin.CakeContactUs.ContactUsFormSubmissions',
]; ];
/** /**
* setUp method * setUp method
* *
* @return void * @return void
*/ */
protected function setUp(): void protected function setUp(): void {
{ parent::setUp();
parent::setUp(); $config = $this->getTableLocator()->exists('ContactUsFormSubmissions') ? [] : ['className' => ContactUsFormSubmissionsTable::class];
$config = $this->getTableLocator()->exists('ContactUsFormSubmissions') ? [] : ['className' => ContactUsFormSubmissionsTable::class]; $this->ContactUsFormSubmissions = $this->getTableLocator()->get('ContactUsFormSubmissions', $config);
$this->ContactUsFormSubmissions = $this->getTableLocator()->get('ContactUsFormSubmissions', $config); }
}
/** /**
* tearDown method * tearDown method
* *
* @return void * @return void
*/ */
protected function tearDown(): void protected function tearDown(): void {
{ unset($this->ContactUsFormSubmissions);
unset($this->ContactUsFormSubmissions);
parent::tearDown(); parent::tearDown();
} }
/** /**
* TestInitialize method * TestInitialize method
* *
* @return void
* @uses \CakeContactUs\Model\Table\ContactUsFormSubmissionsTable::initialize() * @uses \CakeContactUs\Model\Table\ContactUsFormSubmissionsTable::initialize()
* @return void
*/ */
public function testInitialize(): void public function testInitialize(): void {
{ // verify all associations loaded
// verify all associations loaded $expectedAssociations = [];
$expectedAssociations = []; $associations = $this->ContactUsFormSubmissions->associations();
$associations = $this->ContactUsFormSubmissions->associations();
$this->assertCount(count($expectedAssociations), $associations); $this->assertCount(count($expectedAssociations), $associations);
foreach ($expectedAssociations as $expectedAssociation) { foreach ($expectedAssociations as $expectedAssociation) {
$this->assertTrue($this->ContactUsFormSubmissions->hasAssociation($expectedAssociation)); $this->assertTrue($this->ContactUsFormSubmissions->hasAssociation($expectedAssociation));
} }
// verify all behaviors loaded // verify all behaviors loaded
$expectedBehaviors = []; $expectedBehaviors = [];
$behaviors = $this->ContactUsFormSubmissions->behaviors(); $behaviors = $this->ContactUsFormSubmissions->behaviors();
$this->assertCount(count($expectedBehaviors), $behaviors); $this->assertCount(count($expectedBehaviors), $behaviors);
foreach ($expectedBehaviors as $expectedBehavior) { foreach ($expectedBehaviors as $expectedBehavior) {
$this->assertTrue($this->ContactUsFormSubmissions->hasBehavior($expectedBehavior)); $this->assertTrue($this->ContactUsFormSubmissions->hasBehavior($expectedBehavior));
} }
} }
/** /**
* Test validationDefault method * Test validationDefault method
* *
* @return void
* @uses \CakeContactUs\Model\Table\ContactUsFormSubmissionsTable::validationDefault() * @uses \CakeContactUs\Model\Table\ContactUsFormSubmissionsTable::validationDefault()
* @return void
*/ */
public function testValidationDefault(): void public function testValidationDefault(): void {
{ $this->markTestIncomplete('Not implemented yet.');
$this->markTestIncomplete('Not implemented yet.'); }
}
} }

View File

@@ -10,20 +10,19 @@ use Cake\Datasource\ConnectionManager;
use Cake\Mailer\Mailer; use Cake\Mailer\Mailer;
use Cake\Mailer\Transport\DebugTransport; use Cake\Mailer\Transport\DebugTransport;
use Cake\Mailer\TransportFactory; use Cake\Mailer\TransportFactory;
use Cake\TestSuite\Fixture\SchemaLoader;
use CakeContactUs\CakeContactUsPlugin; use CakeContactUs\CakeContactUsPlugin;
use Migrations\TestSuite\Migrator; use Migrations\TestSuite\Migrator;
use TestApp\Controller\AppController; use TestApp\Controller\AppController;
if (!defined('DS')) { if (!defined('DS')) {
define('DS', DIRECTORY_SEPARATOR); define('DS', DIRECTORY_SEPARATOR);
} }
if (!defined('WINDOWS')) { if (!defined('WINDOWS')) {
if (DS === '\\' || substr(PHP_OS, 0, 3) === 'WIN') { if (DS === '\\' || substr(PHP_OS, 0, 3) === 'WIN') {
define('WINDOWS', true); define('WINDOWS', true);
} else { } else {
define('WINDOWS', false); define('WINDOWS', false);
} }
} }
define('PLUGIN_ROOT', dirname(__DIR__)); define('PLUGIN_ROOT', dirname(__DIR__));
@@ -48,42 +47,42 @@ require CORE_PATH . 'config/bootstrap.php';
require CAKE . 'functions.php'; require CAKE . 'functions.php';
Configure::write('App', [ Configure::write('App', [
'namespace' => 'TestApp', 'namespace' => 'TestApp',
'encoding' => 'UTF-8', 'encoding' => 'UTF-8',
'paths' => [ 'paths' => [
'testWebroot' => PLUGIN_ROOT . DS . 'tests' . DS . 'test_app' . DS . 'webroot' . DS, 'testWebroot' => PLUGIN_ROOT . DS . 'tests' . DS . 'test_app' . DS . 'webroot' . DS,
'webroot' => PLUGIN_ROOT . DS . 'webroot' . DS, 'webroot' => PLUGIN_ROOT . DS . 'webroot' . DS,
'templates' => [ 'templates' => [
PLUGIN_ROOT . DS . 'tests' . DS . 'test_app' . DS . 'templates' . DS, PLUGIN_ROOT . DS . 'tests' . DS . 'test_app' . DS . 'templates' . DS,
], ],
], ],
]); ]);
Configure::write('debug', true); Configure::write('debug', true);
Configure::write('ContactUs', [ Configure::write('ContactUs', [
'fields' => [ 'fields' => [
'captcha' => false, 'captcha' => false,
'email' => true, 'email' => true,
], ],
'email' => [ 'email' => [
'mailerClass' => 'CakeContactUs.ContactUsFormSubmissions', 'mailerClass' => 'CakeContactUs.ContactUsFormSubmissions',
'confirmation' => false, // true or false 'confirmation' => false, // true or false
'backend' => [ // array with enabled and the to/cc/bcc/ fields as strings or arrays 'backend' => [ // array with enabled and the to/cc/bcc/ fields as strings or arrays
'enabled' => false, 'enabled' => false,
'to' => 'test@example.com', 'to' => 'test@example.com',
], ],
], ],
]); ]);
Configure::write('EmailTransport', [ Configure::write('EmailTransport', [
'default' => [ 'default' => [
'className' => DebugTransport::class, 'className' => DebugTransport::class,
] ],
]); ]);
TransportFactory::setConfig('default', [ TransportFactory::setConfig('default', [
'className' => DebugTransport::class, 'className' => DebugTransport::class,
]); ]);
Configure::write('Email', [ Configure::write('Email', [
/* /*
* Email delivery profiles * Email delivery profiles
* *
* Delivery profiles allow you to predefine various properties about email * Delivery profiles allow you to predefine various properties about email
@@ -92,35 +91,35 @@ Configure::write('Email', [
* easier. Each profile accepts a number of keys. See `Cake\Mailer\Email` * easier. Each profile accepts a number of keys. See `Cake\Mailer\Email`
* for more information. * for more information.
*/ */
'default' => [ 'default' => [
'transport' => 'default', 'transport' => 'default',
'from' => 'test@example.com', 'from' => 'test@example.com',
/* /*
* Will by default be set to config value of App.encoding, if that exists otherwise to UTF-8. * Will by default be set to config value of App.encoding, if that exists otherwise to UTF-8.
*/ */
//'charset' => 'utf-8', //'charset' => 'utf-8',
//'headerCharset' => 'utf-8', //'headerCharset' => 'utf-8',
], ],
]); ]);
$cache = [ $cache = [
'default' => [ 'default' => [
'engine' => 'File', 'engine' => 'File',
'path' => CACHE, 'path' => CACHE,
], ],
'_cake_translations_' => [ '_cake_translations_' => [
'className' => 'File', 'className' => 'File',
'prefix' => 'crud_myapp_cake_core_', 'prefix' => 'crud_myapp_cake_core_',
'path' => CACHE . 'persistent/', 'path' => CACHE . 'persistent/',
'serialize' => true, 'serialize' => true,
'duration' => '+10 seconds', 'duration' => '+10 seconds',
], ],
'_cake_model_' => [ '_cake_model_' => [
'className' => 'File', 'className' => 'File',
'prefix' => 'crud_my_app_cake_model_', 'prefix' => 'crud_my_app_cake_model_',
'path' => CACHE . 'models/', 'path' => CACHE . 'models/',
'serialize' => 'File', 'serialize' => 'File',
'duration' => '+10 seconds', 'duration' => '+10 seconds',
], ],
]; ];
Cache::setConfig($cache); Cache::setConfig($cache);
@@ -133,15 +132,15 @@ Plugin::getCollection()->add(new CakeContactUsPlugin());
Chronos::setTestNow(Chronos::now()); Chronos::setTestNow(Chronos::now());
if (!getenv('DB_URL')) { if (!getenv('DB_URL')) {
putenv('DB_URL=sqlite:///:memory:'); putenv('DB_URL=sqlite:///:memory:');
} }
ConnectionManager::setConfig('test', [ ConnectionManager::setConfig('test', [
'className' => Connection::class, 'className' => Connection::class,
'url' => getenv('DB_URL') ?: null, 'url' => getenv('DB_URL') ?: null,
'timezone' => 'UTC', 'timezone' => 'UTC',
'quoteIdentifiers' => false, 'quoteIdentifiers' => false,
'cacheMetadata' => true, 'cacheMetadata' => true,
]); ]);
/** /**
@@ -156,7 +155,17 @@ ConnectionManager::setConfig('test', [
*/ */
// Load a schema dump file. // Load a schema dump file.
//(new SchemaLoader())->loadSqlFiles('tests/schema.sql', 'test'); //(new SchemaLoader())->loadSqlFiles('tests/schema.sql', 'test');
if (!defined('SECOND')) {
define('SECOND', 1);
define('MINUTE', 60);
define('HOUR', 3600);
define('DAY', 86400);
define('WEEK', 604800);
define('MONTH', 2592000);
define('YEAR', 31536000);
}
$migrator = new Migrator(); $migrator = new Migrator();
$migrator->run(['plugin' => 'CakeContactUs']); $migrator->run(['plugin' => 'CakeContactUs']);
$migrator->run(['plugin' => 'Captcha']);