public function process(ServerRequestInterface $request, DelegateInterface $delegate) : ResponseInterface
 {
     /* @var \PSR7Session\Session\SessionInterface $session */
     $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);
     // Generate csrf token
     if (!$session->get('csrf')) {
         $session->set('csrf', md5(random_bytes(32)));
     }
     // Generate form and inject csrf token
     $form = new FormFactory($this->template->render('app::contact-form', ['token' => $session->get('csrf')]), $this->inputFilterFactory);
     // Validate form
     $validationResult = $form->validateRequest($request);
     if ($validationResult->isValid()) {
         // Get filter submitted values
         $data = $validationResult->getValues();
         $this->logger->notice('Sending contact mail to {from} <{email}> with subject "{subject}": {body}', $data);
         // Create the message
         $message = new Message();
         $message->setFrom($this->config['from'])->setReplyTo($data['email'], $data['name'])->setTo($this->config['to'])->setSubject('[xtreamwayz-contact] ' . $data['subject'])->setBody($data['body']);
         $this->mailTransport->send($message);
         // Display thank you page
         return new HtmlResponse($this->template->render('app::contact-thank-you'), 200);
     }
     // Display form and inject error messages and submitted values
     return new HtmlResponse($this->template->render('app::contact', ['form' => $form->asString($validationResult)]), 200);
 }
示例#2
0
 /**
  * @param ServerRequestInterface $request
  * @param ResponseInterface      $response
  * @param callable|null          $next
  *
  * @return HtmlResponse
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
 {
     /* @var \PSR7Session\Session\SessionInterface $session */
     $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);
     // Generate csrf token
     if (!$session->get('csrf')) {
         $session->set('csrf', md5(uniqid(rand(), true)));
     }
     // Generate form and inject csrf token
     $form = FormFactory::fromHtml($this->template->render('app::contact-form', ['token' => $session->get('csrf')]));
     // Get request data
     $data = $request->getParsedBody() ?: [];
     if ($request->getMethod() !== 'POST') {
         // Display form
         return new HtmlResponse($this->template->render('app::contact', ['form' => $form->asString()]), 200);
     }
     // Validate form
     $validationResult = $form->validate($data);
     if (!$validationResult->isValid()) {
         // Display form and inject error messages and submitted values
         return new HtmlResponse($this->template->render('app::contact', ['form' => $form->asString($validationResult)]), 200);
     }
     // Create the message
     $message = Swift_Message::newInstance()->setFrom($this->config['from'])->setReplyTo($data['email'], $data['name'])->setTo($this->config['to'])->setSubject('[xtreamwayz-contact] ' . $data['subject'])->setBody($data['body']);
     if ($this->config['transport']['debug'] !== true) {
         $this->mailer->send($message);
     }
     // Display thank you page
     return new HtmlResponse($this->template->render('app::contact-thank-you'), 200);
 }
 /**
  * @dataProvider getIntegrationTests
  */
 public function testIntegration($htmlForm, $defaultValues, $submittedValues, $expectedValues, $expectedForm, $expectedErrors, $expectedException)
 {
     if ($expectedException) {
         $this->expectException($expectedException);
     }
     $form = FormFactory::fromHtml($htmlForm, $defaultValues);
     $result = $form->validate($submittedValues);
     self::assertInstanceOf(ValidationResult::class, $result);
     self::assertEquals($submittedValues, $result->getRawValues(), 'Failed asserting submitted values are equal.');
     self::assertEquals($expectedValues, $result->getValues(), 'Failed asserting filtered values are equal.');
     if ($expectedForm) {
         self::assertEqualForms($expectedForm, $form->asString($result));
     }
     if (count($expectedErrors) === 0 && count($result->getMessages()) === 0) {
         self::assertTrue($result->isValid(), 'Failed asserting the validation result is valid.');
     } else {
         self::assertFalse($result->isValid(), 'Failed asserting the validation result is invalid.');
     }
     self::assertEmpty($this->arrayDiff($expectedErrors, $result->getMessages()), 'Failed asserting that messages are equal.');
 }
 public function testSetValuesWithConstructor()
 {
     $htmlForm = '
         <form action="/" method="post">
             <input type="text" name="foo" data-reuse-submitted-value="true" />
             <input type="text" name="baz" data-filters="stringtrim" />
         </form>';
     $form = new FormFactory($htmlForm, null, ['foo' => 'bar', 'baz' => 'qux']);
     self::assertContains('<input type="text" name="foo" value="bar">', $form->asString());
     self::assertContains('<input type="text" name="baz" value="qux">', $form->asString());
 }
示例#5
0
        required
    ></textarea>
    <input type="submit"/>
</form>
HTML;
use Zend\Filter;
use Zend\InputFilter\BaseInputFilter;
use Zend\InputFilter\Input;
use Zend\Validator;
class ContactFilter extends BaseInputFilter
{
    public function __construct()
    {
        $name = new Input('name');
        $name->getValidatorChain()->attach(new Validator\StringLength(['encoding' => 'UTF-8', 'min' => 2, 'max' => 140]));
        $subject = new Input('subject');
        $subject->getValidatorChain()->attach(new Validator\StringLength(['encoding' => 'UTF-8', 'min' => 2, 'max' => 140]));
        $this->add($name)->add($subject);
    }
}
$_POST['name'] = '  Full Name  ';
$_POST['email'] = 'test@localhost';
$_POST['subject'] = 'Message subject  ';
$_POST['body'] = 'Body.';
//$form = FormFactory::fromHtml($htmlForm, new ContactFilter());
$form = FormFactory::fromHtml($htmlForm, ['body' => 'default value']);
echo $form->asString();
$result = $form->validate($_POST);
// Returns form validation result VO
var_dump($result);
echo $form->asString($result);