Skip to content

Commit

Permalink
[REF] Prelminary tidy up to support fix for dev/core#2344
Browse files Browse the repository at this point in the history
This is all the formatting, doc block & test support fixes to support my fix for https://lab.civicrm.org/dev/core/-/issues/2344

It should all be NFC - the key change is better test support for when pdfs or docs
are generated - we now throw an exception that can be handled in the test.
  • Loading branch information
eileenmcnaughton committed Feb 1, 2021
1 parent 2cdcd16 commit 6b2bb39
Show file tree
Hide file tree
Showing 8 changed files with 53 additions and 28 deletions.
3 changes: 2 additions & 1 deletion CRM/Contribute/Form/AdditionalInfo.php
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,8 @@ public static function emailReceipt(&$form, &$params, $ccContribution = FALSE) {
$eventTaxAmt = $template->get_template_vars('totalTaxAmount');
$prefixValue = Civi::settings()->get('contribution_invoice_settings');
$invoicing = $prefixValue['invoicing'] ?? NULL;
if ((!empty($taxAmt) || isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
// @todo - align with https://lab.civicrm.org/dev/financial/-/issues/162
if ((!empty($taxAmt) || isset($eventTaxAmt)) && (isset($invoicing) && !empty($prefixValue['is_email_pdf']))) {
$isEmailPdf = TRUE;
}
else {
Expand Down
12 changes: 4 additions & 8 deletions CRM/Contribute/Form/Task/PDFLetterCommon.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public static function postProcess(&$form, $formValues = NULL) {
if (empty($formValues)) {
$formValues = $form->controller->exportValues($form->getName());
}
list($formValues, $categories, $html_message, $messageToken, $returnProperties) = self::processMessageTemplate($formValues);
[$formValues, $categories, $html_message, $messageToken, $returnProperties] = self::processMessageTemplate($formValues);
$isPDF = FALSE;
$emailParams = [];
if (!empty($formValues['email_options'])) {
Expand Down Expand Up @@ -82,7 +82,7 @@ public static function postProcess(&$form, $formValues = NULL) {
//@todo - comment on what is stored there
$contributionIDs = $form->getVar('_contributionContactIds');
}
list($contributions, $contacts) = self::buildContributionArray($groupBy, $contributionIDs, $returnProperties, $skipOnHold, $skipDeceased, $messageToken, $task, $separator, $form->_includesSoftCredits);
[$contributions, $contacts] = self::buildContributionArray($groupBy, $contributionIDs, $returnProperties, $skipOnHold, $skipDeceased, $messageToken, $task, $separator, $form->_includesSoftCredits);
$html = [];
$contactHtml = $emailedHtml = [];
foreach ($contributions as $contributionId => $contribution) {
Expand Down Expand Up @@ -127,15 +127,11 @@ public static function postProcess(&$form, $formValues = NULL) {
self::createActivities($form, $html_message, $contactIds, CRM_Utils_Array::value('subject', $formValues, ts('Thank you letter')), CRM_Utils_Array::value('campaign_id', $formValues), $contactHtml);
$html = array_diff_key($html, $emailedHtml);

if (!empty($formValues['is_unit_test'])) {
return $html;
}

//CRM-19761
if (!empty($html)) {
$type = $formValues['document_type'];

if ($type == 'pdf') {
if ($type === 'pdf') {
CRM_Utils_PDF_Utils::html2pdf($html, "CiviLetter.pdf", FALSE, $formValues);
}
else {
Expand Down Expand Up @@ -265,7 +261,7 @@ public static function buildContributionArray($groupBy, $contributionIDs, $retur

if ($isIncludeSoftCredits) {
//@todo find out why this happens & add comments
list($contactID) = explode('-', $item);
[$contactID] = explode('-', $item);
$contactID = (int) $contactID;
}
else {
Expand Down
3 changes: 3 additions & 0 deletions CRM/Utils/PDF/Document.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ class CRM_Utils_PDF_Document {
* @param array|int $format
*/
public static function html2doc($pages, $fileName, $format = []) {
if (CIVICRM_UF === 'UnitTests') {
throw new CRM_Core_Exception_PrematureExitException('html2doc called', ['pages' => $pages]);
}
if (is_array($format)) {
// PDF Page Format parameters passed in - merge with defaults
$format += CRM_Core_BAO_PdfFormat::getDefaultValues();
Expand Down
3 changes: 3 additions & 0 deletions CRM/Utils/PDF/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ class CRM_Utils_PDF_Utils {
* @return string|void
*/
public static function html2pdf($text, $fileName = 'civicrm.pdf', $output = FALSE, $pdfFormat = NULL) {
if (CIVICRM_UF === 'UnitTests') {
throw new CRM_Core_Exception_PrematureExitException('html2pdf called', ['text' => $text]);
}
if (is_array($text)) {
$pages = &$text;
}
Expand Down
9 changes: 5 additions & 4 deletions CRM/Utils/Token.php
Original file line number Diff line number Diff line change
Expand Up @@ -1106,7 +1106,7 @@ public static function getTokens($string) {

if ($matches[1]) {
foreach ($matches[1] as $token) {
list($type, $name) = preg_split('/\./', $token, 2);
[$type, $name] = preg_split('/\./', $token, 2);
if ($name && $type) {
if (!isset($tokens[$type])) {
$tokens[$type] = [];
Expand Down Expand Up @@ -1135,7 +1135,7 @@ public static function getReturnProperties(&$string) {
);
if ($matches[1]) {
foreach ($matches[1] as $token) {
list($type, $name) = preg_split('/\./', $token, 2);
[$type, $name] = preg_split('/\./', $token, 2);
if ($name) {
$returnProperties["{$name}"] = 1;
}
Expand Down Expand Up @@ -1407,7 +1407,7 @@ public static function replaceGreetingTokens(&$tokenString, $contactDetails = NU
);
// Prepare variables for calling replaceHookTokens
$categories = array_keys($greetingTokens);
list($contact) = $greetingDetails;
[$contact] = $greetingDetails;
// Replace tokens defined in Hooks.
$tokenString = CRM_Utils_Token::replaceHookTokens($tokenString, $contact[$contactId], $categories);
}
Expand Down Expand Up @@ -1532,7 +1532,7 @@ function ($matches) use ($escapeSmarty) {
public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
$value = '';

list($objectName, $objectValue) = explode('-', $token, 2);
[$objectName, $objectValue] = explode('-', $token, 2);

switch ($objectName) {
case 'permission':
Expand Down Expand Up @@ -1792,6 +1792,7 @@ public static function getMembershipTokenReplacement($entity, $token, $membershi
* @param bool $escapeSmarty
*
* @return mixed|string
* @throws \CRM_Core_Exception
*/
public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
self::_buildContributionTokens();
Expand Down
4 changes: 2 additions & 2 deletions tests/phpunit/CRM/Contribute/Form/ContributionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1161,7 +1161,7 @@ public function testSubmitWithOutSaleTax() {
*
* @throws \Exception
*/
public function testReSubmitSaleTax($thousandSeparator) {
public function testReSubmitSaleTax($thousandSeparator): void {
$this->setCurrencySeparators($thousandSeparator);
$this->enableTaxAndInvoicing();
$this->addTaxAccountToFinancialType($this->_financialTypeId);
Expand Down Expand Up @@ -1205,7 +1205,7 @@ public function testReSubmitSaleTax($thousandSeparator) {
$mut->checkMailLog($strings);
$this->callAPISuccessGetCount('FinancialTrxn', [], 3);
$items = $this->callAPISuccess('FinancialItem', 'get', ['sequential' => 1])['values'];
$this->assertEquals(2, count($items));
$this->assertCount(2, $items);
$this->assertEquals('Contribution Amount', $items[0]['description']);
$this->assertEquals('Sales Tax', $items[1]['description']);

Expand Down
45 changes: 33 additions & 12 deletions tests/phpunit/CRM/Contribute/Form/Task/PDFLetterCommonTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class CRM_Contribute_Form_Task_PDFLetterCommonTest extends CiviUnitTestCase {

protected $_docTypes = NULL;

protected $_contactIds = NULL;
protected $_contactIds;

/**
* Count how many times the hookTokens is called.
Expand All @@ -41,6 +41,8 @@ protected function setUp() {

/**
* Clean up after each test.
*
* @throws \CRM_Core_Exception
*/
public function tearDown() {
$this->quickCleanUpFinancialEntities();
Expand All @@ -50,8 +52,10 @@ public function tearDown() {

/**
* Test the buildContributionArray function.
*
* @throws \CRM_Core_Exception
*/
public function testBuildContributionArray() {
public function testBuildContributionArray(): void {
$this->_individualId = $this->individualCreate();

$customGroup = $this->callAPISuccess('CustomGroup', 'create', [
Expand All @@ -69,7 +73,7 @@ public function testBuildContributionArray() {
];
$customField = $this->callAPISuccess('CustomField', 'create', $params);
$customFieldKey = 'custom_' . $customField['id'];
$campaignTitle = 'Test Campaign ' . substr(sha1(rand()), 0, 7);
$campaignTitle = 'Test Campaign ';

$params = [
'contact_id' => $this->_individualId,
Expand All @@ -94,7 +98,7 @@ public function testBuildContributionArray() {
],
];

list($contributions, $contacts) = CRM_Contribute_Form_Task_PDFLetterCommon::buildContributionArray('contact_id', $contributionIDs, $returnProperties, TRUE, TRUE, $messageToken, 'test', '**', FALSE);
[$contributions, $contacts] = CRM_Contribute_Form_Task_PDFLetterCommon::buildContributionArray('contact_id', $contributionIDs, $returnProperties, TRUE, TRUE, $messageToken, 'test', '**', FALSE);

$this->assertEquals('Anthony', $contacts[$this->_individualId]['first_name']);
$this->assertEquals('emo', $contacts[$this->_individualId]['favourite_emoticon']);
Expand Down Expand Up @@ -126,13 +130,15 @@ public function hookTokenValues(&$details, $contactIDs, $jobID, $tokens, $classN
/**
* Test contribution token replacement in
* html returned by postProcess function.
*
* @throws \CiviCRM_API3_Exception
* @throws \CRM_Core_Exception
*/
public function testPostProcess() {
public function testPostProcess(): void {
$this->createLoggedInUser();
$this->_individualId = $this->individualCreate();
foreach (['docx', 'odt'] as $docType) {
$formValues = [
'is_unit_test' => TRUE,
'group_by' => NULL,
'document_file' => [
'name' => __DIR__ . "/sample_documents/Template.$docType",
Expand All @@ -153,7 +159,12 @@ public function testPostProcess() {
$date = CRM_Utils_Date::getToday();
$displayDate = CRM_Utils_Date::customFormat($date, $format);

$html = CRM_Contribute_Form_Task_PDFLetterCommon::postProcess($form, $formValues);
try {
CRM_Contribute_Form_Task_PDFLetterCommon::postProcess($form, $formValues);
}
catch (CRM_Core_Exception_PrematureExitException $e) {
$html = $e->errorData['pages'];
}
$expectedValues = [
'Hello Anthony',
'$ 100.00',
Expand All @@ -171,10 +182,14 @@ public function testPostProcess() {
/**
* Test assignment of variables when using the group by function.
*
* We are looking to see that the contribution aggregate and contributions arrays reflect the most
* recent contact rather than a total aggregate, since we are using group by.
* We are looking to see that the contribution aggregate and contributions
* arrays reflect the most recent contact rather than a total aggregate,
* since we are using group by.
*
* @throws \CiviCRM_API3_Exception
* @throws \CRM_Core_Exception
*/
public function testPostProcessGroupByContact() {
public function testPostProcessGroupByContact(): void {
$this->createLoggedInUser();
$this->hookClass->setHook('civicrm_tokenValues', [$this, 'hook_aggregateTokenValues']);
$this->hookClass->setHook('civicrm_tokens', [$this, 'hook_tokens']);
Expand All @@ -183,12 +198,12 @@ public function testPostProcessGroupByContact() {
$this->_individualId2 = $this->individualCreate();
$htmlMessage = "{aggregate.rendered_token}";
$formValues = [
'is_unit_test' => TRUE,
'group_by' => 'contact_id',
'html_message' => $htmlMessage,
'email_options' => 'both',
'subject' => 'Testy test test',
'from' => 'info@example.com',
'document_type' => 'doc',
];

$contributionIDs = [];
Expand Down Expand Up @@ -218,7 +233,13 @@ public function testPostProcessGroupByContact() {
$form = new CRM_Contribute_Form_Task_PDFLetter();
$form->setContributionIds($contributionIDs);

$html = CRM_Contribute_Form_Task_PDFLetterCommon::postProcess($form, $formValues);
try {
CRM_Contribute_Form_Task_PDFLetterCommon::postProcess($form, $formValues);
}
catch (CRM_Core_Exception_PrematureExitException $e) {
$html = $e->errorData['pages'];
}

$this->assertEquals("<table border='1' cellpadding='2' cellspacing='0' class='table'>
<tbody>
<tr>
Expand Down
2 changes: 1 addition & 1 deletion tests/phpunit/CiviTest/CiviUnitTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -3065,7 +3065,7 @@ protected function enableTaxAndInvoicing($params = []) {
'due_date' => 10,
'due_date_period' => 'days',
'notes' => '',
'is_email_pdf' => 1,
'is_email_pdf' => FALSE,
'tax_term' => 'Sales Tax',
'tax_display_settings' => 'Inclusive',
]
Expand Down

0 comments on commit 6b2bb39

Please sign in to comment.