4 Commits
Author SHA1 Message Date
Alexandre Gain b138056e43 style: fix indentation, alignment, and docblock annotations
- Correct getChoices() docblock to reflect translated label => enum
  backing value order instead of value => label
- Re-indent Smart Links menu config to match actual array nesting
- Align assignment operators in RefreshStatsCommand
- Add missing newline at end of RefreshStatsCommand.php
2026-11-21 11:23:33 +01:00
Alexandre Gain 07773acb8d docs(readme): follow the repository rename to mautic-marketing-program-bundle 2026-11-16 23:18:21 +01:00
Alexandre Gain 9d81d6c815 refactor(naming): normalise the Smart Links domain to the bundle's canonical names (0.18.1)
One bundle, two domains (Marketing Programs and Smart Links), one naming scheme.\nNothing in the database changed (no tables, columns, URLs or stored data);\nthe runtime was rebuilt and verified live.\n\n- Route names mautic_smartlinks_* -> mt3s_smartlinks_* (paths unchanged);\n  the menu ids follow\n- Model service aliases collapsed to one canonical alias per model:\n  mautic.mt3smarketingprogram.model.<entity> (core's mautic.<x>.model.<x>\n  pattern), so getModel('mt3smarketingprogram.smart_link'); the dead\n  mt3s.* and mautic.mt3smp.*-era aliases are gone\n- Translation keys mautic.smartlinks.* -> mt3s.smart_links.*\n  (mautic.config.tab.smartlinksconfig stays: core derives it)\n- Settings parameters smartlinks_utm_config/smartlinks_config ->\n  mt3s_smart_links_utm_config/mt3s_smart_links_config, with both legacy\n  keys (smartlinks_* of the standalone bundle, utm_manager_* of the\n  UtmManagerBundle era) still readable until the settings are saved again\n- JS loader prefixes smartlinksSmartLink/smartlinksUtmTaxonomy ->\n  mt3sMpSmartLink/mt3sMpUtmTaxonomy (the mt3sMp* family of the program\n  domain)\n- Integration/Support/ConfigSupport -> SmartlinksConfigSupport; integration\n  display names aligned ('MT3S Marketing Program' / 'Smart Links'); the\n  dead mautic.plugin.smartlinks.name catalog keys removed\n- phpunit suite renamed UtmManagerBundle -> MT3SMarketingProgramBundle;\n  version 0.18.1\n\nVerified: full php -l, 90/90 unit tests (phpunit 11.5 phar), cache clear +\nwarm + assets regenerate + plugins reload (as www-data), live: both lists\nand forms (mauticContent mt3sMpSmartLink/mt3sMpUtmTaxonomy), both config\ntabs, the menu labels, the program pages (regression), the public /l/y32b\nredirect through the legacy utm_manager_* settings (302 with the taxonomy's\nUTM values, wrong host and unknown slug 404), all ini catalogs parse, zero\nnew log errors.
2026-11-16 15:47:30 +01:00
Alexandre Gain dce849610c Merge the Smartlinks plugin (SmartlinksBundle 0.6.0) into the bundle as the Smart Links domain (0.18.0)
Two domains, one MT3S bundle: Marketing Programs (unchanged) and the
imported Smart Links (smart links + UTM taxonomies), each keeping its
own menu, tables, routes and translations.

- Code moved from MauticPlugin\SmartlinksBundle\ to
  MauticPlugin\MT3SMarketingProgramBundle\; template namespace
  @Smartlinks/ -> @MT3SMarketingProgram/; smartlinks.js ->
  Assets/js/mt3s-mp-smartlinks.js; icon -> Assets/img/smartlinks-icon.svg.
- Incoming migrations renamed Version_0_X_0_SmartLinks.php to avoid
  the class-name collision; schema untouched, data intact.
- Permissions folded into MT3SMarketingProgramPermissions:
  smart_links + taxonomies under the mt3smarketingprogram: base
  (roles that had the old smartlinks: grants must be re-granted).
- config.php: Smart Links routes + menu group, public /l/{slug},
  SmartlinksIntegration services, smartlinks_* parameters (legacy
  utm_manager_* keys still readable), version 0.18.0. The 0.17.0
  placeholder /s/marketing-program-utm-taxonomies is replaced by the
  real /s/utm-taxonomies.
- Translations merged (en_US) and added (fr_FR); Tests/ + phpunit moved
  in; readme documents both domains and the 0.18.0 merge history.

Verified live: menus, both config tabs, both lists + forms, program
pages, public redirect with taxonomy UTM values, host + unknown-slug
404s, 90/90 unit tests, full php -l, all ini catalogs parse.
2026-11-16 13:48:13 +01:00
128 changed files with 8777 additions and 219 deletions

No files matched your search

+2
View File
@@ -4,3 +4,5 @@
*.log *.log
.vscode/ .vscode/
.claude/ .claude/
.phpunit.result.cache
.phpunit.result/
+28
View File
@@ -0,0 +1,28 @@
# Coding standards of the plugin: the same ruleset Mautic core runs
# (@Symfony + the core tweaks, see .php-cs-fixer.dist.php) and PHPStan level 6
# (see phpstan.neon). `composer install` in the plugin directory pulls
# mautic/core-lib (^7.0) so the analysis sees the real Mautic signatures.
#
# The PHPUnit suite is not run here: it needs a full Mautic installation
# (see Tests/bootstrap.php). Run it from the mautic-dev-env container:
# vendor/bin/phpunit -c docroot/plugins/MT3SMarketingProgramBundle/phpunit.xml.dist
stages:
- lint
.default-before-script: &default-before-script
- composer install --no-interaction --no-progress --prefer-dist
php-cs-fixer:
stage: lint
image: composer:2
before_script: *default-before-script
script:
- composer cs-check
phpstan:
stage: lint
image: composer:2
before_script: *default-before-script
script:
- composer phpstan
+1
View File
@@ -0,0 +1 @@
{"php":"8.3.36","version":"3.95.32:v3.95.32#c12acc751f4039935429057f1fadf0e5f62601c1","indent":" ","lineEnding":"\n","rules":{"align_multiline_comment":true,"backtick_to_shell_exec":true,"binary_operator_spaces":{"operators":{"=>":"align","=":"align"}},"blank_line_before_statement":{"statements":["return"]},"braces_position":{"allow_single_line_anonymous_functions":true,"allow_single_line_empty_anonymous_classes":true},"class_attributes_separation":{"elements":{"method":"one"}},"class_definition":{"single_line":true},"class_reference_name_casing":true,"clean_namespace":true,"concat_space":true,"declare_parentheses":true,"echo_tag_syntax":true,"empty_loop_body":{"style":"braces"},"empty_loop_condition":true,"fully_qualified_strict_types":true,"function_declaration":{"closure_fn_spacing":"one"},"general_phpdoc_tag_rename":{"replacements":{"inheritDocs":"inheritDoc"}},"global_namespace_import":{"import_classes":false,"import_constants":false,"import_functions":false},"include":true,"increment_style":true,"integer_literal_case":true,"lambda_not_used_import":true,"linebreak_after_opening_tag":true,"magic_constant_casing":true,"magic_method_casing":true,"method_argument_space":{"after_heredoc":true,"on_multiline":"ignore"},"native_function_casing":true,"native_type_declaration_casing":true,"no_alias_language_construct_call":true,"no_binary_string":true,"no_blank_lines_after_phpdoc":true,"no_empty_comment":true,"no_empty_phpdoc":true,"no_empty_statement":true,"no_extra_blank_lines":{"tokens":["attribute","case","continue","curly_brace_block","default","extra","parenthesis_brace_block","square_brace_block","switch","throw","use"]},"no_leading_namespace_whitespace":true,"no_mixed_echo_print":true,"no_multiline_whitespace_around_double_arrow":true,"no_null_property_initialization":true,"no_short_bool_cast":true,"no_singleline_whitespace_before_semicolons":true,"no_spaces_around_offset":true,"no_superfluous_phpdoc_tags":{"allow_mixed":true},"no_trailing_comma_in_singleline":true,"no_unneeded_braces":{"namespaces":true},"no_unneeded_control_parentheses":{"statements":["break","clone","continue","echo_print","negative_instanceof","others","return","switch_case","yield","yield_from"]},"no_unneeded_import_alias":true,"no_unset_cast":true,"no_unused_imports":true,"no_useless_concat_operator":true,"no_useless_else":true,"no_useless_nullsafe_operator":true,"no_useless_return":true,"no_whitespace_before_comma_in_array":{"after_heredoc":true},"normalize_index_brace":true,"object_operator_without_whitespace":true,"operator_linebreak":{"only_booleans":true},"ordered_imports":true,"php_unit_fqcn_annotation":true,"php_unit_method_casing":true,"phpdoc_align":true,"phpdoc_annotation_without_dot":true,"phpdoc_indent":true,"phpdoc_inline_tag_normalizer":true,"phpdoc_no_access":true,"phpdoc_no_alias_tag":{"replacements":{"const":"var","link":"see","property-read":"property","property-write":"property","type":"var"}},"phpdoc_no_package":true,"phpdoc_no_useless_inheritdoc":true,"phpdoc_order":{"order":["param","return","throws"]},"phpdoc_return_self_reference":true,"phpdoc_scalar":{"types":["boolean","callback","double","integer","never-return","never-returns","no-return","real","str"]},"phpdoc_separation":{"groups":[["Annotation","NamedArgumentConstructor","Target"],["author","copyright","license"],["category","package","subpackage"],["property","property-read","property-write"],["deprecated","link","see","since"]],"skip_unlisted_annotations":false},"phpdoc_single_line_var_spacing":true,"phpdoc_summary":true,"phpdoc_tag_type":{"tags":{"inheritDoc":"inline"}},"phpdoc_trim":true,"phpdoc_trim_consecutive_blank_line_separation":true,"phpdoc_types":true,"phpdoc_types_order":{"null_adjustment":"always_last","sort_algorithm":"none"},"phpdoc_var_annotation_correct_order":true,"phpdoc_var_without_name":true,"protected_to_private":true,"semicolon_after_instruction":true,"simple_to_complex_string_variable":true,"single_import_per_statement":true,"single_line_comment_spacing":true,"single_line_comment_style":{"comment_types":["hash"]},"single_line_throw":true,"single_quote":true,"single_space_around_construct":true,"space_after_semicolon":{"remove_in_empty_for_expressions":true},"standardize_increment":true,"standardize_not_equals":true,"statement_indentation":{"stick_comment_to_next_continuous_control_statement":true},"switch_continue_to_break":true,"trailing_comma_in_multiline":{"after_heredoc":true,"elements":["array_destructuring","arrays","match","parameters"]},"trim_array_spaces":true,"type_declaration_spaces":{"elements":["function","property"]},"unary_operator_spaces":true,"whitespace_after_comma_in_array":true,"yoda_style":true,"nullable_type_declaration":true,"ordered_types":{"null_adjustment":"always_last","sort_algorithm":"none"},"single_class_element_per_statement":true,"types_spaces":true,"array_indentation":true,"array_syntax":{"syntax":"short"},"attribute_block_no_spaces":true,"cast_spaces":true,"new_with_parentheses":{"anonymouLine truncated
+72
View File
@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
/*
* PHP-CS-Fixer configuration of the plugin: the same ruleset Mautic core runs
* (see its .php-cs-fixer.php), minus the custom fixer of the mautic/coding-standards
* package, which a standalone plugin repository cannot require.
*
* Check the coding style (CI runs this with --dry-run --diff):
*
* vendor/bin/php-cs-fixer fix --dry-run --diff --config=.php-cs-fixer.dist.php
*
* Fix in place:
*
* vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.dist.php
*/
$finder = (new PhpCsFixer\Finder())
->in([
__DIR__.'/Catalog',
__DIR__.'/Command',
__DIR__.'/Config',
__DIR__.'/Controller',
__DIR__.'/DependencyInjection',
__DIR__.'/Entity',
__DIR__.'/Event',
__DIR__.'/EventListener',
__DIR__.'/Form',
__DIR__.'/Integration',
__DIR__.'/Migrations',
__DIR__.'/Model',
__DIR__.'/Security',
__DIR__.'/Service',
__DIR__.'/Tests',
__DIR__.'/Twig',
__DIR__.'/Validator',
])
->append([
__DIR__.'/MT3SMarketingProgramBundle.php',
]);
return (new PhpCsFixer\Config())
->setRules([
'@Symfony' => true,
'binary_operator_spaces' => [
'operators' => [
'=>' => 'align',
'=' => 'align',
],
],
'phpdoc_to_comment' => false,
'ordered_imports' => true,
'array_syntax' => [
'syntax' => 'short',
],
'no_unused_imports' => true,
/**
* The plugin's templates use the alternative syntax (endforeach, endif, ...)
* that Mautic's Twig templates rely on, so the rule stays off like in core.
*/
'no_alternative_syntax' => false,
'header_comment' => [
'header' => '',
],
'multiline_whitespace_before_semicolons' => true,
'nullable_type_declaration_for_default_null_value' => false, // Enforces potential BC breaks.
'no_superfluous_phpdoc_tags' => [
'allow_mixed' => true,
],
])
->setFinder($finder);
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="12" fill="#4e5e9e"/><text x="32" y="41" font-family="Arial,sans-serif" font-size="22" font-weight="bold" fill="#fff" text-anchor="middle">UTM</text></svg>

After

Width:  |  Height:  |  Size: 248 B

+240
View File
@@ -0,0 +1,240 @@
/**
* Smart Links (the plugin's second domain)
*
* - Settings > Configuration > Smart Links Settings tab: delegated handlers only (the
* configuration page is loaded through Ajax). Showing / hiding the value editor by
* mode is done by Mautic's own data-show-on switcher.
* - Smart Link form: short link preview, "Generate" a random slug, destination URL shown
* only for external redirects. Started by Mautic.mt3sMpSmartLinkOnLoad(), which Mautic
* calls after it loads any page whose mauticContent is "mt3sMpSmartLink".
*/
(function ($) {
'use strict';
if (typeof $ === 'undefined') {
return;
}
var NS = '.smartlinks';
/**
* Rows are renumbered 0..n-1 in DOM order after every change, so the submitted order is the
* displayed order (Symfony collections keep the order of their keys).
*/
var reindexValues = function ($list) {
$list.children('.utm-value-row').each(function (index) {
$(this).find('input, select, textarea').each(function () {
var $input = $(this);
var name = $input.attr('name');
var id = $input.attr('id');
if (name) {
$input.attr('name', name.replace(/^(.*\[values\]\[)[^\]]+(\].*)$/, '$1' + index + '$2'));
}
if (id) {
$input.attr('id', id.replace(/^(.*_values_)[^_]+(_.*)$/, '$1' + index + '$2'));
}
});
});
refreshEditor($list.closest('.utm-values-editor'));
};
var refreshEditor = function ($editor) {
var count = $editor.find('.utm-value-row').length;
$editor.find('.utm-values-empty').toggleClass('hide', count > 0);
$editor.find('[data-utm-load-suggestions]').toggleClass('hide', count > 0);
};
var getList = function ($editor) {
return $editor.find('.utm-values-list').first();
};
var existingValues = function ($editor) {
var values = {};
$editor.find('.utm-value-input').each(function () {
values[$.trim($(this).val())] = true;
});
return values;
};
var addValueRow = function ($editor, value, label) {
var $list = getList($editor);
var index = $list.children('.utm-value-row').length;
var $row = $($list.attr('data-prototype').replace(/__value__/g, index));
$list.append($row);
if (typeof value !== 'undefined') {
$row.find('.utm-value-input').val(value);
$row.find('.utm-label-input').val(label || value);
}
reindexValues($list);
return $row;
};
/**
* Appends rows for the given {value, label} items, skipping values already in the list.
*/
var appendValues = function ($editor, items) {
var existing = existingValues($editor);
$.each(items, function (i, item) {
if (item.value === '' || existing[item.value]) {
return;
}
existing[item.value] = true;
addValueRow($editor, item.value, item.label);
});
};
var refreshFieldStates = function ($element) {
// Re-runs Mautic's data-show-on switcher (bound to the form's change event).
$element.closest('form').trigger('change');
};
$(document)
.on('click' + NS, '.smartlinks-utm-config [data-utm-add-value]', function () {
var $row = addValueRow($(this).closest('.utm-values-editor'));
$row.find('.utm-value-input').trigger('focus');
})
.on('click' + NS, '.smartlinks-utm-config [data-utm-remove-value]', function () {
var $list = $(this).closest('.utm-values-list');
$(this).closest('.utm-value-row').remove();
reindexValues($list);
})
.on('change' + NS, '.smartlinks-utm-config .utm-value-default', function () {
// Only one default value per parameter.
if ($(this).is(':checked')) {
$(this).closest('.utm-values-list').find('.utm-value-default').not(this).prop('checked', false);
}
})
.on('mouseenter' + NS, '.smartlinks-utm-config .utm-values-list', function () {
var $list = $(this);
if ($list.data('utmSortable') || typeof $list.sortable !== 'function') {
return;
}
$list.data('utmSortable', true).sortable({
items: '> .utm-value-row',
handle: '.utm-value-handle',
axis: 'y',
stop: function () {
reindexValues($list);
}
});
})
.on('click' + NS, '.smartlinks-utm-config [data-utm-import]', function () {
var $editor = $(this).closest('.utm-values-editor');
var $text = $editor.find('.utm-import-text');
var items = [];
$.each(($text.val() || '').split(/\r?\n/), function (i, line) {
var parts = line.split(';');
var value = $.trim(parts.shift());
if (value !== '') {
items.push({value: value, label: $.trim(parts.join(';')) || value});
}
});
appendValues($editor, items);
$text.val('');
})
.on('click' + NS, '.smartlinks-utm-config [data-utm-load-suggestions]', function () {
appendValues($(this).closest('.utm-values-editor'), JSON.parse($(this).attr('data-utm-suggestions') || '[]'));
})
.on('click' + NS, '.smartlinks-utm-config [data-utm-add-parameter]', function () {
var $config = $(this).closest('.smartlinks-utm-config');
var $container = $config.find('.utm-custom-parameters');
var index = parseInt($container.attr('data-index'), 10) || 0;
var $panel = $($container.attr('data-prototype').replace(/__param__/g, index));
$container.attr('data-index', index + 1).append($panel);
$config.find('.utm-custom-empty').addClass('hide');
refreshFieldStates($container);
$panel.find('.utm-custom-key').trigger('focus');
})
.on('click' + NS, '.smartlinks-utm-config [data-utm-remove-parameter]', function () {
var $config = $(this).closest('.smartlinks-utm-config');
$(this).closest('[data-utm-parameter]').remove();
$config.find('.utm-custom-empty').toggleClass('hide', $config.find('.utm-custom-parameters [data-utm-parameter]').length > 0);
})
.on('input' + NS, '.smartlinks-utm-config .utm-custom-key', function () {
var key = $.trim($(this).val());
var $code = $(this).closest('[data-utm-parameter]').find('.utm-parameter-key').first();
$code.text(key !== '' ? key : $code.text());
});
// ---------------------------------------------------------------------------
// Smart Link form (menu: Smart Links)
// ---------------------------------------------------------------------------
/**
* The short link the user is building: https://{short link domain}/l/{slug}. Spaces are
* replaced by the configured character, uppercase turned to lowercase, exactly like the
* server does on save (SmartLinkModel::applySlugRules).
*/
Mautic.smartLinkPreview = function ($wrapper) {
var $slugInput = $wrapper.find('.smart-link-slug');
var domain = $.trim($('#smartLinkDomainReminder').attr('data-domain') || '');
var slug = $.trim($slugInput.val() || '');
var replacement = $.trim($('#smartLinkDomainReminder').attr('data-separator') || '-');
slug = slug.replace(/\s+/g, replacement);
if (parseInt($('#smartLinkDomainReminder').attr('data-lowercase') || '1', 10)) {
slug = slug.toLowerCase();
}
$('#smartLinkPreview').text(domain !== '' && slug !== '' ? domain + '/l/' + slug : '');
};
/**
* The destination depends on the redirect type: the URL for external redirects, the
* landing page or the standalone form for Mautic ones.
*/
Mautic.smartLinkToggleDestination = function ($wrapper) {
var type = $wrapper.find('.smart-link-redirect-type').val();
$('#smartLinkDestinationUrlWrapper').toggleClass('hide', type === 'mautic');
$('#smartLinkMauticDestinationWrapper').toggleClass('hide', type !== 'mautic');
};
Mautic.mt3sMpSmartLinkOnLoad = function (container) {
var $wrapper = $(container).find('.smart-link-slug-group').first();
if ($wrapper.length) {
Mautic.smartLinkPreview($wrapper);
// The redirect type lives outside the slug group: scope the toggle to the form.
Mautic.smartLinkToggleDestination($wrapper.closest('form'));
}
};
$(document)
.on('input', '.smart-link-slug', function () {
Mautic.smartLinkPreview($(this).closest('.smart-link-slug-group'));
})
.on('change', '.smart-link-redirect-type', function () {
Mautic.smartLinkToggleDestination($(this).closest('form'));
})
.on('click', '#smartLinkGenerateSlug', function () {
var $button = $(this);
var generated = $.trim($button.attr('data-generated') || '');
var $slugInput = $button.closest('.smart-link-slug-group').find('.smart-link-slug');
if (generated !== '') {
$slugInput.val(generated).trigger('input');
// The next click proposes a different slug; the page isn't reloaded between clicks.
$button.attr('data-generated', Mautic.smartLinkRandomSlug());
}
});
/**
* Random slug of 4 letters and digits for the "Generate" button (client-side fallback; the
* server proposes one on each page load and the validator checks uniqueness on submit).
*/
Mautic.smartLinkRandomSlug = function () {
var alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789';
var slug = '';
for (var i = 0; i < 4; i++) {
slug += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
}
return slug;
};
})(window.mQuery);
+35
View File
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Catalog;
/**
* HTTP status used for the redirect. 301 and 308 are permanent, 302 and 307 temporary.
*/
enum SmartLinkRedirectCode: int
{
use SmartLinkRedirectEnumHelper;
public const ALLOWED = [301, 302, 307, 308];
public const MOVED_PERMANENTLY = 301;
public const FOUND = 302;
public const TEMPORARY_REDIRECT = 307;
public const PERMANENT_REDIRECT = 308;
case MovedPermanently = self::MOVED_PERMANENTLY;
case Found = self::FOUND;
case TemporaryRedirect = self::TEMPORARY_REDIRECT;
case PermanentRedirect = self::PERMANENT_REDIRECT;
public function getLabelKey(): string
{
return 'mt3s.smart_links.smart_links.redirect_code.'.$this->value;
}
public function isPermanent(): bool
{
return in_array($this->value, [self::MOVED_PERMANENTLY, self::PERMANENT_REDIRECT], true);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Catalog;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Choice labels for Smart Link redirect enums: t("mt3s.smart_links.smart_links.redirect_<x>.<value>")
* gives "301 - Moved permanently (permanent)" style labels shared by the form and the list view.
*/
trait SmartLinkRedirectEnumHelper
{
/**
* The choices of the form's redirect dropdowns and the list views: translated label => backing value.
*
* @return array<string, int|string> translated label => backing value of the enum case
*/
public static function getChoices(TranslatorInterface $translator): array
{
$choices = [];
foreach (self::cases() as $case) {
$choices[$translator->trans($case->getLabelKey())] = $case->value;
}
return $choices;
}
public function getTranslatedLabel(TranslatorInterface $translator): string
{
return $translator->trans($this->getLabelKey());
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Catalog;
/**
* Where a Smart Link sends the visitor. Mautic redirects are not processed yet.
*/
enum SmartLinkRedirectType: string
{
public const ALLOWED = [self::MAUTIC, self::EXTERNAL];
public const MAUTIC = 'mautic';
public const EXTERNAL = 'external';
case Mautic = self::MAUTIC;
case External = self::EXTERNAL;
public function getLabelKey(): string
{
return 'mt3s.smart_links.smart_links.redirect_type.'.($this->isMautic() ? self::MAUTIC : self::EXTERNAL);
}
public function isMautic(): bool
{
return self::MAUTIC === $this->value;
}
public function isExternal(): bool
{
return self::EXTERNAL === $this->value;
}
}
+109
View File
@@ -0,0 +1,109 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Catalog;
/**
* System catalog of the parameters offered by UTM Manager. Administrators can't edit it;
* they can only configure each entry and add custom parameters next to it.
*/
final class UtmParameterCatalog
{
public const GROUP_STANDARD = 'standard';
public const GROUP_PLATFORM = 'platform';
public const GROUP_CUSTOM = 'custom';
public const CUSTOM_KEY_PATTERN = '/^[a-z][a-z0-9_]{1,40}$/';
/** Query keys used by Mautic itself (ct = click-through tracking). */
private const RESERVED_KEYS = ['ct'];
/** "utm" is reserved for catalog entries, "mtc_" for Mautic tracking parameters. */
private const RESERVED_PREFIXES = ['utm', 'mtc_'];
/**
* Standard Google Analytics / GA4 parameters: key => [default mode, suggested values].
*/
private const STANDARD = [
'utm_source' => [UtmParameterMode::DROPDOWN, ['newsletter', 'linkedin', 'facebook', 'instagram', 'google', 'youtube', 'x', 'tiktok', 'partner', 'direct']],
'utm_medium' => [UtmParameterMode::DROPDOWN, ['email', 'cpc', 'social', 'social_paid', 'display', 'affiliate', 'referral', 'qr', 'sms', 'print', 'event']],
'utm_campaign' => [UtmParameterMode::FREE, []],
'utm_term' => [UtmParameterMode::FREE, []],
'utm_content' => [UtmParameterMode::FREE, []],
'utm_id' => [UtmParameterMode::FREE, []],
'utm_source_platform' => [UtmParameterMode::DROPDOWN, ['google_ads', 'meta_ads', 'linkedin_ads', 'microsoft_ads', 'tiktok_ads']],
'utm_creative_format' => [UtmParameterMode::DROPDOWN, ['banner', 'video', 'carousel', 'text', 'native']],
'utm_marketing_tactic' => [UtmParameterMode::DROPDOWN, ['prospecting', 'remarketing', 'retargeting', 'brand', 'nurturing']],
];
/**
* Click IDs appended automatically by ad platforms. Disabled by default.
*/
private const PLATFORM = ['gclid', 'gbraid', 'wbraid', 'dclid', 'fbclid', 'msclkid', 'ttclid', 'li_fat_id', 'twclid', 'epik'];
/**
* @var array<string, UtmParameterDefinition>
*/
private array $definitions = [];
public function __construct()
{
foreach (self::STANDARD as $key => [$mode, $suggestions]) {
$this->definitions[$key] = new UtmParameterDefinition($key, self::GROUP_STANDARD, $mode, false, $suggestions);
}
foreach (self::PLATFORM as $key) {
$this->definitions[$key] = new UtmParameterDefinition($key, self::GROUP_PLATFORM, UtmParameterMode::DISABLED, true);
}
}
/**
* @return array<string, UtmParameterDefinition> In display order
*/
public function all(): array
{
return $this->definitions;
}
/**
* @return array<string, UtmParameterDefinition>
*/
public function getByGroup(string $group): array
{
return array_filter($this->definitions, fn (UtmParameterDefinition $definition): bool => $definition->group === $group);
}
public function has(string $key): bool
{
return isset($this->definitions[$key]);
}
public function get(string $key): ?UtmParameterDefinition
{
return $this->definitions[$key] ?? null;
}
/**
* Keys that a custom parameter can't use: catalog keys, Mautic query keys and reserved prefixes.
*/
public function isReservedKey(string $key): bool
{
if ($this->has($key) || in_array($key, self::RESERVED_KEYS, true)) {
return true;
}
foreach (self::RESERVED_PREFIXES as $prefix) {
if (str_starts_with($key, $prefix)) {
return true;
}
}
return false;
}
public function isValidCustomKey(string $key): bool
{
return 1 === preg_match(self::CUSTOM_KEY_PATTERN, $key) && !$this->isReservedKey($key);
}
}
+59
View File
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Catalog;
/**
* One entry of the system catalog of UTM / click-ID parameters.
*/
final class UtmParameterDefinition
{
private const TRANSLATION_PREFIX = 'mt3s.smart_links.config.parameter.';
/**
* @param string[] $suggestions Suggested values offered by the "Load suggested values" button
*/
public function __construct(
public readonly string $key,
public readonly string $group,
public readonly string $defaultMode,
public readonly bool $autoGenerated = false,
public readonly array $suggestions = [],
) {
}
public function getLabelKey(): string
{
return self::TRANSLATION_PREFIX.$this->key.'.label';
}
public function getDescriptionKey(): string
{
return self::TRANSLATION_PREFIX.$this->key.'.description';
}
/**
* Auto-generated click IDs can't be restricted to a list of values.
*
* @return string[]
*/
public function getAllowedModes(): array
{
if ($this->autoGenerated) {
return [UtmParameterMode::FREE, UtmParameterMode::DISABLED];
}
return UtmParameterMode::ALL;
}
public function isModeAllowed(string $mode): bool
{
return in_array($mode, $this->getAllowedModes(), true);
}
public static function getSuggestionLabelKey(string $value): string
{
return 'mt3s.smart_links.config.suggestion.'.$value;
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Catalog;
/**
* How a parameter is presented by the link builder.
*/
final class UtmParameterMode
{
/** The link builder shows a selector restricted to the configured values. */
public const DROPDOWN = 'dropdown';
/** The link builder shows a free text input. No values are configured. */
public const FREE = 'free';
/** The parameter is not used. */
public const DISABLED = 'disabled';
public const ALL = [self::DROPDOWN, self::FREE, self::DISABLED];
private function __construct()
{
}
}
+1 -1
View File
@@ -64,7 +64,7 @@ class RefreshStatsCommand extends Command
$rows = []; $rows = [];
foreach ($programs as $program) { foreach ($programs as $program) {
$id = (string) $program->getId(); $id = (string) $program->getId();
$rows[] = [ $rows[] = [
$id, $id,
$program->getName(), $program->getName(),
+91 -6
View File
@@ -4,8 +4,8 @@ declare(strict_types=1);
return [ return [
'name' => 'MT3S Marketing Program', 'name' => 'MT3S Marketing Program',
'description' => 'Marketing Program for Mautic.', 'description' => 'MT3S Marketing: programs, tasks, audiences, and smart links with their UTM taxonomies.',
'version' => '0.17.0', 'version' => '0.18.1',
'author' => 'Experiential', 'author' => 'Experiential',
'routes' => [ 'routes' => [
@@ -46,12 +46,24 @@ return [
'path' => '/marketing-program-audiences/{objectAction}/{objectId}', 'path' => '/marketing-program-audiences/{objectAction}/{objectId}',
'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\AudienceController::executeAction', 'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\AudienceController::executeAction',
], ],
// UTM Taxonomies: a placeholder page for the coming feature, kept out of the menu // Smart Links domain: the list and its object actions.
// (the route stays; the page is reachable at /s/marketing-program-utm-taxonomies). 'mt3s_smart_links_index' => [
'mt3s_marketing_program_utm_taxonomy_index' => [ 'path' => '/smart-links/{page}',
'path' => '/marketing-program-utm-taxonomies/{page}', 'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\SmartLinkController::indexAction',
],
'mt3s_smart_links_action' => [
'path' => '/smart-links/{objectAction}/{objectId}',
'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\SmartLinkController::executeAction',
],
// UTM Taxonomies: the list and its object actions.
'mt3s_smart_links_taxonomies' => [
'path' => '/utm-taxonomies/{page}',
'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\UtmTaxonomyController::indexAction', 'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\UtmTaxonomyController::indexAction',
], ],
'mt3s_smart_links_taxonomy_action' => [
'path' => '/utm-taxonomies/{objectAction}/{objectId}',
'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\UtmTaxonomyController::executeAction',
],
// The type lists of the plugin's items (Insights, allocations, objectives, tasks, // The type lists of the plugin's items (Insights, allocations, objectives, tasks,
// stakeholders, audience values), moved out of Settings > Configuration. // stakeholders, audience values), moved out of Settings > Configuration.
'mt3s_marketing_program_item_types_index' => [ 'mt3s_marketing_program_item_types_index' => [
@@ -59,6 +71,14 @@ return [
'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\ItemTypesController::indexAction', 'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\ItemTypesController::indexAction',
], ],
], ],
// https://{short_link_domain}/l/{slug}: the public entry point of the Smart Links.
// Public routes are served without the /s/ prefix and without authentication.
'public' => [
'mt3s_smart_links_go' => [
'path' => '/l/{slug}',
'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\PublicController::goAction',
],
],
], ],
// Top-level "Programs" menu. Future program objects go in its children, after Programs. // Top-level "Programs" menu. Future program objects go in its children, after Programs.
@@ -102,6 +122,37 @@ return [
], ],
], ],
], ],
// Top-level "Smart Links" menu: UTM Taxonomies above the Smart Links list. The two
// domains (Marketing Program and Smart Links) stay separate menu groups.
'mt3s.smart_links.menu.root' => [
'id' => 'mt3s_smart_links',
'route' => 'mt3s_smart_links_index',
'iconClass' => 'ri-links-line',
'access' => [
'mt3smarketingprogram:smart_links:viewown',
'mt3smarketingprogram:smart_links:viewother',
'mt3smarketingprogram:taxonomies:viewown',
'mt3smarketingprogram:taxonomies:viewother',
],
'priority' => 4,
'children' => [
'mt3s.smart_links.menu.taxonomies' => [
'id' => 'mt3s_smart_links_taxonomies',
'route' => 'mt3s_smart_links_taxonomies',
'iconClass' => 'ri-price-tag-3-line',
'access' => ['mt3smarketingprogram:taxonomies:viewown', 'mt3smarketingprogram:taxonomies:viewother'],
'priority' => 5,
],
'mt3s.smart_links.menu.smartlinks' => [
'id' => 'mt3s_smart_links_index',
'route' => 'mt3s_smart_links_index',
'iconClass' => 'ri-link',
'access' => ['mt3smarketingprogram:smart_links:viewown', 'mt3smarketingprogram:smart_links:viewother'],
'priority' => 4,
],
],
],
], ],
], ],
@@ -120,6 +171,19 @@ return [
'mautic.config_integration', 'mautic.config_integration',
], ],
], ],
'mt3s.smart_links.integration' => [
'class' => MauticPlugin\MT3SMarketingProgramBundle\Integration\SmartlinksIntegration::class,
'tags' => [
'mautic.integration',
'mautic.basic_integration',
],
],
'mt3s.smart_links.integration.configuration' => [
'class' => MauticPlugin\MT3SMarketingProgramBundle\Integration\Support\SmartlinksConfigSupport::class,
'tags' => [
'mautic.config_integration',
],
],
], ],
], ],
@@ -169,5 +233,26 @@ return [
// ItemTypeProvider (kinds "audience_decision_role" and "audience_tone"). // ItemTypeProvider (kinds "audience_decision_role" and "audience_tone").
'mt3s_marketing_program_audience_decision_roles' => [], 'mt3s_marketing_program_audience_decision_roles' => [],
'mt3s_marketing_program_audience_tones' => [], 'mt3s_marketing_program_audience_tones' => [],
// Stored by Settings > Configuration > Smart Links Settings (SmartLinksConfigSubscriber).
// Read through UtmConfigurationProvider; the default stays empty, the catalog
// defaults are applied by UtmConfigurationNormalizer.
'mt3s_smart_links_utm_config' => [],
'mt3s_smart_links_config' => [
'short_link_domain' => '',
],
// Legacy keys of the earlier eras. Declared so the read fallbacks
// (UtmConfigurationProvider, SmartLinkModel, SmartLinkShortUrlBuilder) can serve
// upgrades from local.php until the settings are saved again; new values are
// always written to the new keys: `smartlinks_*` (the standalone
// SmartlinksBundle, 0.1.0–0.18.0) and `utm_manager_*` (the UtmManagerBundle, < 0.5.0).
'smartlinks_utm_config' => [],
'smartlinks_config' => [
'short_link_domain' => '',
],
'utm_manager_config' => [],
'utm_manager_smart_links' => [
'short_link_domain' => '',
],
], ],
]; ];
+11 -12
View File
@@ -13,6 +13,8 @@ return function (ContainerConfigurator $configurator): void {
->public(); ->public();
$excludes = [ $excludes = [
'Catalog/UtmParameterDefinition.php',
'Catalog/UtmParameterMode.php',
'Tests', 'Tests',
]; ];
@@ -23,16 +25,13 @@ return function (ContainerConfigurator $configurator): void {
$services->load('MauticPlugin\\MT3SMarketingProgramBundle\\Entity\\', '../Entity/*Repository.php') $services->load('MauticPlugin\\MT3SMarketingProgramBundle\\Entity\\', '../Entity/*Repository.php')
->tag(Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\ServiceRepositoryCompilerPass::REPOSITORY_SERVICE_TAG); ->tag(Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\ServiceRepositoryCompilerPass::REPOSITORY_SERVICE_TAG);
// Lets core resolve the model with getModel('mt3smp.program'). // Core resolves getModel('mt3smarketingprogram.<entity>') to mautic.mt3smarketingprogram.model.<entity>:
$services->alias('mt3s.marketing_program.model.program', MauticPlugin\MT3SMarketingProgramBundle\Model\ProgramModel::class); // exactly one alias per model, under the bundle's canonical prefix.
$services->alias('mautic.mt3smp.model.program', MauticPlugin\MT3SMarketingProgramBundle\Model\ProgramModel::class); $services->alias('mautic.mt3smarketingprogram.model.program', MauticPlugin\MT3SMarketingProgramBundle\Model\ProgramModel::class);
// getModel('mt3smp.task'). $services->alias('mautic.mt3smarketingprogram.model.task', MauticPlugin\MT3SMarketingProgramBundle\Model\TaskModel::class);
$services->alias('mt3s.marketing_program.model.task', MauticPlugin\MT3SMarketingProgramBundle\Model\TaskModel::class); $services->alias('mautic.mt3smarketingprogram.model.stakeholder', MauticPlugin\MT3SMarketingProgramBundle\Model\StakeholderModel::class);
$services->alias('mautic.mt3smp.model.task', MauticPlugin\MT3SMarketingProgramBundle\Model\TaskModel::class); $services->alias('mautic.mt3smarketingprogram.model.audience', MauticPlugin\MT3SMarketingProgramBundle\Model\AudienceModel::class);
// getModel('mt3smp.stakeholder'). // Smart Links domain: getModel('mt3smarketingprogram.smart_link') / getModel('mt3smarketingprogram.utm_taxonomy').
$services->alias('mt3s.marketing_program.model.stakeholder', MauticPlugin\MT3SMarketingProgramBundle\Model\StakeholderModel::class); $services->alias('mautic.mt3smarketingprogram.model.smart_link', MauticPlugin\MT3SMarketingProgramBundle\Model\SmartLinkModel::class);
$services->alias('mautic.mt3smp.model.stakeholder', MauticPlugin\MT3SMarketingProgramBundle\Model\StakeholderModel::class); $services->alias('mautic.mt3smarketingprogram.model.utm_taxonomy', MauticPlugin\MT3SMarketingProgramBundle\Model\UtmTaxonomyModel::class);
// getModel('mt3smp.audience').
$services->alias('mt3s.marketing_program.model.audience', MauticPlugin\MT3SMarketingProgramBundle\Model\AudienceModel::class);
$services->alias('mautic.mt3smp.model.audience', MauticPlugin\MT3SMarketingProgramBundle\Model\AudienceModel::class);
}; };
+2 -2
View File
@@ -14,7 +14,7 @@ use Symfony\Component\HttpFoundation\Response;
* link to them from their Audiences tab (ProgramAudience carries the audience's priority in that * link to them from their Audiences tab (ProgramAudience carries the audience's priority in that
* program). * program).
* *
* Model mt3smp.audience (mt3s.marketing_program.model.audience), permission base mt3smarketingprogram:audiences, translation * Model mt3smarketingprogram.audience (mautic.mt3smarketingprogram.model.audience), permission base mt3smarketingprogram:audiences, translation
* base mt3s.marketing_program.audience. * base mt3s.marketing_program.audience.
*/ */
class AudienceController extends AbstractStandardFormController class AudienceController extends AbstractStandardFormController
@@ -24,7 +24,7 @@ class AudienceController extends AbstractStandardFormController
protected function getModelName(): string protected function getModelName(): string
{ {
return 'mt3smp.audience'; return 'mt3smarketingprogram.audience';
} }
protected function getTemplateBase(): string protected function getTemplateBase(): string
+8 -7
View File
@@ -11,10 +11,11 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
/** /**
* List, view, create, edit and delete plans, using core's standard CRUD flow. * List, view, create, edit and delete marketing programs, using core's standard CRUD flow.
* *
* Core derives most names from the model name "program": model mt3s.marketing_program.model.program, permission base * Core derives the model alias and the permission base from the model name
* mt3smarketingprogram:programs (from ProgramModel), translation base mt3s.marketing_program, session base mt3s.marketing_program. * "mt3smarketingprogram.program": model mautic.mt3smarketingprogram.model.program, permission
* base mt3smarketingprogram:programs (from ProgramModel). The views translate under mt3s.marketing_program.*.
*/ */
class ProgramController extends AbstractStandardFormController class ProgramController extends AbstractStandardFormController
{ {
@@ -23,7 +24,7 @@ class ProgramController extends AbstractStandardFormController
protected function getModelName(): string protected function getModelName(): string
{ {
return 'mt3smp.program'; return 'mt3smarketingprogram.program';
} }
protected function getTemplateBase(): string protected function getTemplateBase(): string
@@ -47,7 +48,7 @@ class ProgramController extends AbstractStandardFormController
/** /**
* The OnLoad JS prefix: core dispatches Mautic[getJsLoadMethodPrefix() + "OnLoad"]() * The OnLoad JS prefix: core dispatches Mautic[getJsLoadMethodPrefix() + "OnLoad"]()
* (mt3sMpProgramOnLoad in Assets/js/mt3s-mp-program.js). Without this override, core * (mt3sMpProgramOnLoad in Assets/js/mt3s-mp-program.js). Without this override, core
* falls back to the model name ("mt3smp.program"), which nothing listens to. * falls back to the model name ("mt3smarketingprogram.program"), which nothing listens to.
*/ */
protected function getJsLoadMethodPrefix(): string protected function getJsLoadMethodPrefix(): string
{ {
@@ -79,7 +80,7 @@ class ProgramController extends AbstractStandardFormController
} }
if (!$this->checkActionPermission('view', $program)) { if (!$this->checkActionPermission('view', $program)) {
return $this->accessDenied(); $this->throwAccessDenied();
} }
$base = $this->getPermissionBase(); $base = $this->getPermissionBase();
@@ -148,7 +149,7 @@ class ProgramController extends AbstractStandardFormController
private function getTaskModel(): TaskModel private function getTaskModel(): TaskModel
{ {
$model = $this->getModel('mt3smp.task'); $model = $this->getModel('mt3smarketingprogram.task');
\assert($model instanceof TaskModel); \assert($model instanceof TaskModel);
return $model; return $model;
+95
View File
@@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Controller;
use Doctrine\Persistence\ManagerRegistry;
use Mautic\CoreBundle\Controller\CommonController;
use Mautic\CoreBundle\Factory\ModelFactory;
use Mautic\CoreBundle\Helper\CoreParametersHelper;
use Mautic\CoreBundle\Helper\UserHelper;
use Mautic\CoreBundle\Security\Permissions\CorePermissions;
use Mautic\CoreBundle\Service\FlashBag;
use Mautic\CoreBundle\Translation\Translator;
use MauticPlugin\MT3SMarketingProgramBundle\Model\SmartLinkModel;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
/**
* The public side of the Smart Links: https://{short_link_domain}/l/{slug}.
*
* The short link only works when Mautic is entered through the configured short link
* domain (Settings > Configuration > Smart Links Settings): the call is redirected to
* the link's destination — its external URL, or its landing page / standalone form for
* Mautic redirects — with its UTM parameters, and one hit is recorded for the statistics.
* On any other host, unknown slug, unpublished link or link without destination the
* short link doesn't exist: 404.
*/
class PublicController extends CommonController
{
public function __construct(
private readonly SmartLinkModel $smartLinkModel,
private readonly LoggerInterface $logger,
ManagerRegistry $doctrine,
ModelFactory $modelFactory,
UserHelper $userHelper,
CoreParametersHelper $coreParametersHelper,
EventDispatcherInterface $dispatcher,
Translator $translator,
FlashBag $flashBag,
RequestStack $requestStack,
CorePermissions $security,
) {
parent::__construct($doctrine, $modelFactory, $userHelper, $coreParametersHelper, $dispatcher, $translator, $flashBag, $requestStack, $security);
}
public function goAction(Request $request, string $slug): Response
{
// The "if and only if" rule: only the short link domain is an entry point for /l/.
$domain = $this->smartLinkModel->getShortLinkDomain();
if ('' === $domain || 0 !== strcasecmp(trim($request->getHost()), $domain)) {
return $this->notFound();
}
$slug = trim($slug);
if ('' === $slug) {
return $this->notFound();
}
$link = $this->smartLinkModel->getRepository()->findOneBy(['slug' => $slug]);
if (null === $link || !$link->isPublished()) {
return $this->notFound();
}
// A link without destination goes nowhere, whatever its type.
if ($link->getRedirectType()->isMautic()) {
if (null === $link->getPage() && null === $link->getForm()) {
return $this->notFound();
}
} elseif ('' === trim((string) $link->getDestinationUrl())) {
return $this->notFound();
}
try {
$this->smartLinkModel->recordHit($link, $request);
} catch (\Throwable $e) {
// Statistics must never block the redirect.
$this->logger->error(
'Smart Link hit could not be recorded for slug "{slug}": {message}',
[
'slug' => $slug,
'message' => $e->getMessage(),
'exception' => $e,
]
);
}
return new RedirectResponse($this->smartLinkModel->buildRedirectUrl($link), $link->getRedirectCode()->value);
}
}
+177
View File
@@ -0,0 +1,177 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Controller;
use Mautic\CoreBundle\Controller\AbstractStandardFormController;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink;
use MauticPlugin\MT3SMarketingProgramBundle\Model\SmartLinkModel;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Create, edit and delete Smart Links (main menu > Smart Links), using core's standard CRUD flow.
*
* Model mt3smarketingprogram.smart_link (mautic.mt3smarketingprogram.model.smart_link), permission base
* mt3smarketingprogram:smart_links, translation base mt3s.smart_links.smart_links.
*
* The slug of a saved link is immutable: the form disables the field, the model refuses another
* slug, and this controller drops the submitted value (nothing to re-check). There is no clone:
* a new link gets a new slug (the "Generate" button offers one).
*/
class SmartLinkController extends AbstractStandardFormController
{
public const ROUTE_INDEX = 'mt3s_smart_links_index';
public const ROUTE_ACTION = 'mt3s_smart_links_action';
protected function getModelName(): string
{
return 'mt3smarketingprogram.smart_link';
}
protected function getTemplateBase(): string
{
return '@MT3SMarketingProgram/SmartLink';
}
protected function getIndexRoute(): string
{
return self::ROUTE_INDEX;
}
protected function getActionRoute(): string
{
return self::ROUTE_ACTION;
}
/**
* The OnLoad JS prefix: core dispatches Mautic[getJsLoadMethodPrefix() + "OnLoad"]()
* (Mautic.mt3sMpSmartLinkOnLoad in Assets/js/mt3s-mp-smartlinks.js). Without this
* override, core falls back to the model name, which nothing listens to.
*/
protected function getJsLoadMethodPrefix(): string
{
return 'mt3sMpSmartLink';
}
/**
* Core builds mautic.<model name> (singular smart_link); every key of the feature lives
* under mt3s.smart_links.smart_links.
*/
protected function getTranslationBase(): string
{
return 'mt3s.smart_links.smart_links';
}
/**
* @param int $page
*/
public function indexAction(Request $request, $page = 1): Response
{
return $this->indexStandard($request, $page);
}
public function newAction(Request $request): Response
{
return $this->newStandard($request);
}
/**
* @param int $objectId
* @param bool $ignorePost
*/
public function editAction(Request $request, $objectId, $ignorePost = false): Response
{
return $this->editStandard($request, $objectId, $ignorePost);
}
/**
* @param int $objectId
*/
public function deleteAction(Request $request, $objectId): Response
{
return $this->deleteStandard($request, $objectId);
}
public function batchDeleteAction(Request $request): Response
{
return $this->batchDeleteStandard($request);
}
/**
* Never save the slug of an existing link: it is immutable once created. The field is
* disabled in the form, so nothing is submitted for it, this is a safety net.
*
* @param SmartLink $entity
* @param string $action
* @param int|null $objectId
* @param bool $isClone
*/
protected function beforeEntitySave($entity, Form $form, $action, $objectId = null, $isClone = false): bool
{
if ($entity instanceof SmartLink && null !== $entity->getId()) {
$formSlug = $form->has('slug') ? (string) $form->get('slug')->getData() : '';
if ('' !== $formSlug && $formSlug !== (string) $entity->getSlug()) {
$this->addFlashMessage('mt3s.smart_links.smart_links.error.slug_immutable', ['%slug%' => $formSlug], \Mautic\CoreBundle\Service\FlashBag::LEVEL_ERROR);
return false;
}
}
return parent::beforeEntitySave($entity, $form, $action, $objectId, $isClone);
}
/**
* The list shows the short link, built from the configured domain (a reminder of it is
* also displayed above the form of a link), and the number of hits of each link.
*
* @param array<string, mixed> $args
* @param string $action
*
* @return array<string, mixed>
*/
protected function getViewArguments(array $args, $action): array
{
$args = parent::getViewArguments($args, $action);
if ('index' === $action) {
$model = $this->getModel($this->getModelName());
\assert($model instanceof SmartLinkModel);
$args['viewParameters']['shortLinkDomain'] = $model->getShortLinkDomain();
$args['viewParameters']['hitCounts'] = $model->getHitCounts();
}
return $args;
}
/**
* Order by slug: the entity has no "name" column.
*/
protected function getDefaultOrderColumn(): string
{
return 'slug';
}
/**
* Smart Links don't have a detail page; after Save or Cancel go back to the list.
*
* @param string $action
*/
protected function getPostActionControllerAction($action): string
{
return 'index';
}
/**
* A saved Smart Link is never cloned: its slug is immutable, and a clone would need a new one.
*
* @param int|null $objectId
*/
public function cloneAction(Request $request, $objectId): Response
{
$this->throwAccessDenied();
}
}
+2 -2
View File
@@ -13,7 +13,7 @@ use Symfony\Component\HttpFoundation\Response;
* core's standard CRUD flow. Stakeholders are independent of programs; programs link to them from their * core's standard CRUD flow. Stakeholders are independent of programs; programs link to them from their
* Stakeholders tab. * Stakeholders tab.
* *
* Model mt3smp.stakeholder (mt3s.marketing_program.model.stakeholder), permission base mt3smarketingprogram:stakeholders, * Model mt3smarketingprogram.stakeholder (mautic.mt3smarketingprogram.model.stakeholder), permission base mt3smarketingprogram:stakeholders,
* translation base mt3s.marketing_program.stakeholder. * translation base mt3s.marketing_program.stakeholder.
*/ */
class StakeholderController extends AbstractStandardFormController class StakeholderController extends AbstractStandardFormController
@@ -23,7 +23,7 @@ class StakeholderController extends AbstractStandardFormController
protected function getModelName(): string protected function getModelName(): string
{ {
return 'mt3smp.stakeholder'; return 'mt3smarketingprogram.stakeholder';
} }
protected function getTemplateBase(): string protected function getTemplateBase(): string
+16 -4
View File
@@ -14,7 +14,7 @@ use Symfony\Component\HttpFoundation\Response;
/** /**
* List, create, edit and delete tasks (Programs > Tasks), using core's standard CRUD flow. * List, create, edit and delete tasks (Programs > Tasks), using core's standard CRUD flow.
* *
* Model mt3smp.task (mt3s.marketing_program.model.task), permission base mt3smarketingprogram:tasks, translation base mt3s.marketing_program.task. * Model mt3smarketingprogram.task (mautic.mt3smarketingprogram.model.task), permission base mt3smarketingprogram:tasks, translation base mt3s.marketing_program.task.
* *
* Where the user lands after Save or Cancel depends on where the task form was opened from: * Where the user lands after Save or Cancel depends on where the task form was opened from:
* - from Programs > Tasks: back to the task list (core's default); * - from Programs > Tasks: back to the task list (core's default);
@@ -51,7 +51,7 @@ class TaskController extends AbstractStandardFormController
protected function getModelName(): string protected function getModelName(): string
{ {
return 'mt3smp.task'; return 'mt3smarketingprogram.task';
} }
protected function getTemplateBase(): string protected function getTemplateBase(): string
@@ -97,7 +97,7 @@ class TaskController extends AbstractStandardFormController
*/ */
public function editAction(Request $request, $objectId, $ignorePost = false): Response public function editAction(Request $request, $objectId, $ignorePost = false): Response
{ {
$task = $this->getModel($this->getModelName())->getEntity((int) $objectId); $task = $this->getModel($this->getModelName())->getEntity((int) $objectId);
$programId = $task instanceof Task ? $task->getProgram()?->getId() : null; $programId = $task instanceof Task ? $task->getProgram()?->getId() : null;
$this->returnProgramId = $this->resolveReturnProgram($request, (string) (int) $objectId, $programId); $this->returnProgramId = $this->resolveReturnProgram($request, (string) (int) $objectId, $programId);
@@ -137,6 +137,10 @@ class TaskController extends AbstractStandardFormController
} }
/** /**
* @param string $action
* @param int|null $objectId
* @param bool $isClone
*
* @return object|null * @return object|null
*/ */
protected function getFormEntity($action, &$objectId = null, &$isClone = false) protected function getFormEntity($action, &$objectId = null, &$isClone = false)
@@ -144,7 +148,7 @@ class TaskController extends AbstractStandardFormController
$entity = parent::getFormEntity($action, $objectId, $isClone); $entity = parent::getFormEntity($action, $objectId, $isClone);
if ('new' === $action && $entity instanceof Task && null === $entity->getProgram() && null !== $this->preselectedProgramId) { if ('new' === $action && $entity instanceof Task && null === $entity->getProgram() && null !== $this->preselectedProgramId) {
$program = $this->getModel('mt3smp.program')->getEntity($this->preselectedProgramId); $program = $this->getModel('mt3smarketingprogram.program')->getEntity($this->preselectedProgramId);
if ($program instanceof Program) { if ($program instanceof Program) {
$entity->setProgram($program); $entity->setProgram($program);
} }
@@ -153,6 +157,13 @@ class TaskController extends AbstractStandardFormController
return $entity; return $entity;
} }
/**
* @param Task $entity
* @param string $action
* @param mixed $pass
*
* @return mixed
*/
protected function afterEntitySave($entity, Form $form, $action, $pass = null) protected function afterEntitySave($entity, Form $form, $action, $pass = null)
{ {
if ($entity instanceof Task) { if ($entity instanceof Task) {
@@ -167,6 +178,7 @@ class TaskController extends AbstractStandardFormController
* was moved to another program, go to its new program. Otherwise keep core's default: the task list. * was moved to another program, go to its new program. Otherwise keep core's default: the task list.
* *
* @param array<string, mixed> $args * @param array<string, mixed> $args
* @param string $action
* *
* @return array<string, mixed> * @return array<string, mixed>
*/ */
+104 -19
View File
@@ -4,37 +4,122 @@ declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Controller; namespace MauticPlugin\MT3SMarketingProgramBundle\Controller;
use Mautic\CoreBundle\Controller\CommonController; use Mautic\CoreBundle\Controller\AbstractStandardFormController;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
/** /**
* UTM Taxonomies: a placeholder page for the coming feature, kept out of the menu since * Create, edit and delete UTM Taxonomies (Smart Links > UTM Taxonomies), using core's standard
* 0.17.0 (the route stays; the page is reachable at /s/marketing-program-utm-taxonomies). * CRUD flow.
* The content (classifying the UTM parameters of the programs' campaigns and links) comes *
* later; until then the page shows an empty content block. * Model mt3smarketingprogram.utm_taxonomy (mautic.mt3smarketingprogram.model.utm_taxonomy), permission base
* mt3smarketingprogram:taxonomies, translation base mt3s.smart_links.taxonomies.
*
* A taxonomy is never cloned: its name is unique, and a clone would collide immediately. A new
* taxonomy is created from scratch.
*/ */
class UtmTaxonomyController extends CommonController class UtmTaxonomyController extends AbstractStandardFormController
{ {
public const ROUTE_INDEX = 'mt3s_marketing_program_utm_taxonomy_index'; public const ROUTE_INDEX = 'mt3s_smart_links_taxonomies';
public const ROUTE_ACTION = 'mt3s_smart_links_taxonomy_action';
protected function getModelName(): string
{
return 'mt3smarketingprogram.utm_taxonomy';
}
protected function getTemplateBase(): string
{
return '@MT3SMarketingProgram/UtmTaxonomy';
}
protected function getIndexRoute(): string
{
return self::ROUTE_INDEX;
}
protected function getActionRoute(): string
{
return self::ROUTE_ACTION;
}
/**
* The OnLoad JS prefix (no Mautic.mt3sMpUtmTaxonomyOnLoad exists: the form needs none),
* deterministic for future use; core's fallback, the model name, would nothing listen to.
*/
protected function getJsLoadMethodPrefix(): string
{
return 'mt3sMpUtmTaxonomy';
}
/**
* Core builds mautic.<model name>; every key of the feature lives under mt3s.smart_links.taxonomies.
*/
protected function getTranslationBase(): string
{
return 'mt3s.smart_links.taxonomies';
}
/** /**
* @param int $page * @param int $page
*/ */
public function indexAction(Request $request, $page = 1): Response public function indexAction(Request $request, $page = 1): Response
{ {
$tmpl = $request->isXmlHttpRequest() ? $request->get('tmpl', 'index') : 'index'; return $this->indexStandard($request, $page);
}
return $this->delegateView([ public function newAction(Request $request): Response
'viewParameters' => [ {
'tmpl' => $tmpl, return $this->newStandard($request);
], }
'contentTemplate' => '@MT3SMarketingProgram/UtmTaxonomy/list.html.twig',
'passthroughVars' => [ /**
'activeLink' => '#'.self::ROUTE_INDEX, * @param int $objectId
'mauticContent' => 'mt3sMpProgramUtmTaxonomy', * @param bool $ignorePost
'route' => $this->generateUrl(self::ROUTE_INDEX), */
], public function editAction(Request $request, $objectId, $ignorePost = false): Response
]); {
return $this->editStandard($request, $objectId, $ignorePost);
}
/**
* @param int $objectId
*/
public function deleteAction(Request $request, $objectId): Response
{
return $this->deleteStandard($request, $objectId);
}
public function batchDeleteAction(Request $request): Response
{
return $this->batchDeleteStandard($request);
}
/**
* Taxonomies don't have a detail page; after Save or Cancel go back to the list.
*
* @param string $action
*/
protected function getPostActionControllerAction($action): string
{
return 'index';
}
/**
* Order by name: the taxonomy has no other sortable business column.
*/
protected function getDefaultOrderColumn(): string
{
return 'name';
}
/**
* A saved taxonomy is never cloned: its name is unique, and a clone would collide on save.
*
* @param int|null $objectId
*/
public function cloneAction(Request $request, $objectId): Response
{
$this->throwAccessDenied();
} }
} }
+15 -15
View File
@@ -141,16 +141,16 @@ class Audience extends FormEntity
public function __construct() public function __construct()
{ {
$this->stages = new ArrayCollection(); $this->stages = new ArrayCollection();
$this->segments = new ArrayCollection(); $this->segments = new ArrayCollection();
$this->programLinks = new ArrayCollection(); $this->programLinks = new ArrayCollection();
} }
public function __clone() public function __clone()
{ {
$this->id = null; $this->id = null;
$this->stages = new ArrayCollection(); $this->stages = new ArrayCollection();
$this->segments = new ArrayCollection(); $this->segments = new ArrayCollection();
$this->programLinks = new ArrayCollection(); $this->programLinks = new ArrayCollection();
parent::__clone(); parent::__clone();
@@ -171,21 +171,21 @@ class Audience extends FormEntity
// Mapped on the raw metadata: ClassMetadataBuilder::addField() forces every string to VARCHAR(191). // Mapped on the raw metadata: ClassMetadataBuilder::addField() forces every string to VARCHAR(191).
$metadata->mapField([ $metadata->mapField([
'fieldName' => 'audienceType', 'fieldName' => 'audienceType',
'columnName' => 'audience_type', 'columnName' => 'audience_type',
'type' => Types::STRING, 'type' => Types::STRING,
'length' => 30, 'length' => 30,
'enumType' => AudienceType::class, 'enumType' => AudienceType::class,
'options' => ['default' => AudienceType::Persona->value], 'options' => ['default' => AudienceType::Persona->value],
]); ]);
foreach ([ foreach ([
'tagline' => 'tagline', 'tagline' => 'tagline',
'profileCriteria' => 'profile_criteria', 'profileCriteria' => 'profile_criteria',
'motivations' => 'motivations', 'motivations' => 'motivations',
'barriers' => 'barriers', 'barriers' => 'barriers',
'frustrations' => 'frustrations', 'frustrations' => 'frustrations',
'triggers' => 'triggers', 'triggers' => 'triggers',
] as $field => $column) { ] as $field => $column) {
$metadata->mapField([ $metadata->mapField([
'fieldName' => $field, 'fieldName' => $field,
+10 -8
View File
@@ -105,12 +105,12 @@ class Program extends FormEntity implements DateRangeInterface
public function __construct() public function __construct()
{ {
$this->objectives = new ArrayCollection(); $this->objectives = new ArrayCollection();
$this->descriptionItems = new ArrayCollection(); $this->descriptionItems = new ArrayCollection();
$this->allocationItems = new ArrayCollection(); $this->allocationItems = new ArrayCollection();
$this->audiences = new ArrayCollection(); $this->audiences = new ArrayCollection();
$this->stakeholders = new ArrayCollection(); $this->stakeholders = new ArrayCollection();
$this->tasks = new ArrayCollection(); $this->tasks = new ArrayCollection();
} }
public function __clone() public function __clone()
@@ -163,8 +163,10 @@ class Program extends FormEntity implements DateRangeInterface
->setCustomRepositoryClass(ProgramRepository::class) ->setCustomRepositoryClass(ProgramRepository::class)
->addIndex(['status'], 'program_status'); ->addIndex(['status'], 'program_status');
// id and name; no description column (replaced by description items). // id and name; no description column (replaced by description items). The false is
$builder->addIdColumns('name', false); // core's own way to skip the column (addIdColumns checks it for truthiness); core's
// @param string docblock just doesn't mention it.
$builder->addIdColumns('name', false); // @phpstan-ignore argument.type (false is core's own way to skip the column; its @param string docblock doesn't mention it)
// Mapped on the raw metadata: ClassMetadataBuilder::addField() forces every string to VARCHAR(191). // Mapped on the raw metadata: ClassMetadataBuilder::addField() forces every string to VARCHAR(191).
$metadata->mapField([ $metadata->mapField([
@@ -468,7 +470,7 @@ class Program extends FormEntity implements DateRangeInterface
} }
/** /**
* @template T of ProgramObjective|ProgramDescriptionItem|ProgramAllocationItem|Audience|ProgramStakeholder * @template T of ProgramObjective|ProgramDescriptionItem|ProgramAllocationItem|ProgramAudience|ProgramStakeholder
* *
* @param Collection<int, T> $collection * @param Collection<int, T> $collection
* *
+1 -1
View File
@@ -49,7 +49,7 @@ class ProgramAllocationItem
public function __clone() public function __clone()
{ {
$this->id = null; $this->id = null;
$this->program = null; $this->program = null;
} }
+1 -1
View File
@@ -43,7 +43,7 @@ class ProgramAudience
public function __clone() public function __clone()
{ {
$this->id = null; $this->id = null;
$this->program = null; $this->program = null;
} }
+1 -1
View File
@@ -39,7 +39,7 @@ class ProgramDescriptionItem
public function __clone() public function __clone()
{ {
$this->id = null; $this->id = null;
$this->program = null; $this->program = null;
} }
+1 -1
View File
@@ -53,7 +53,7 @@ class ProgramObjective
public function __clone() public function __clone()
{ {
$this->id = null; $this->id = null;
$this->program = null; $this->program = null;
} }
+1 -1
View File
@@ -40,7 +40,7 @@ class ProgramStakeholder
public function __clone() public function __clone()
{ {
$this->id = null; $this->id = null;
$this->program = null; $this->program = null;
} }
+4 -4
View File
@@ -24,10 +24,10 @@ enum ProgramStatus: string
public function getLabelClass(): string public function getLabelClass(): string
{ {
return match ($this) { return match ($this) {
self::Active => 'label-success', self::Active => 'label-success',
self::Completed => 'label-info', self::Completed => 'label-info',
self::Paused => 'label-warning', self::Paused => 'label-warning',
self::Archived => 'label-default', self::Archived => 'label-default',
self::Draft, self::Planned => 'label-primary', self::Draft, self::Planned => 'label-primary',
}; };
} }
+304
View File
@@ -0,0 +1,304 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Entity;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping\ClassMetadata as OrmClassMetadata;
use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder;
use Mautic\CoreBundle\Entity\FormEntity;
use Mautic\FormBundle\Entity\Form;
use Mautic\PageBundle\Entity\Page;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\SmartLinkRedirectCode;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\SmartLinkRedirectType;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* A Smart Link: a short link ({shortLinkDomain}/l/{slug}) that carries the UTM parameters.
*
* The slug is applied when the link is created (spaces replaced, lowercase enforced) and is
* immutable afterwards. Destination URLs only exist for external redirects; Mautic redirects
* are not processed yet.
*/
class SmartLink extends FormEntity
{
public const TABLE_NAME = 'smart_links';
public const SLUG_MAX_LENGTH = 9; // "text length < 10"
private ?int $id = null;
private ?string $slug = null;
private SmartLinkRedirectType $redirectType = SmartLinkRedirectType::External;
private SmartLinkRedirectCode $redirectCode = SmartLinkRedirectCode::Found;
private ?string $destinationUrl = null;
/**
* Values of the UTM parameters of the link: parameter key => value.
*
* @var array<string, string>
*/
private array $utmParameters = [];
/**
* The landing page of a Mautic redirect (null for external ones).
*/
private ?Page $page = null;
/**
* The standalone form of a Mautic redirect (null for external ones).
*/
private ?Form $form = null;
/**
* The UTM Taxonomy of the link: every UTM value is chosen among its allowed values.
* Null only on links that predate the feature; the form then demands one.
*/
private ?UtmTaxonomy $taxonomy = null;
public static function loadMetadata(OrmClassMetadata $metadata): void
{
$builder = new ClassMetadataBuilder($metadata);
$builder->setTable(self::TABLE_NAME)
->setCustomRepositoryClass(SmartLinkRepository::class)
->addIndex(['slug'], 'smart_link_slug');
$builder->addId();
$builder->createField('slug', Types::STRING)
->length(self::SLUG_MAX_LENGTH)
->unique()
->build();
// Mapped on the raw metadata: ClassMetadataBuilder::addField() forces VARCHAR(191) on strings
// and doesn't accept enum types.
$metadata->mapField([
'fieldName' => 'redirectType',
'columnName'=> 'redirect_type',
'type' => Types::STRING,
'length' => 20,
'enumType' => SmartLinkRedirectType::class,
'options' => ['default' => SmartLinkRedirectType::External->value],
]);
$metadata->mapField([
'fieldName' => 'redirectCode',
'columnName'=> 'redirect_code',
'type' => Types::INTEGER,
'enumType' => SmartLinkRedirectCode::class,
'options' => ['default' => SmartLinkRedirectCode::Found->value],
]);
$metadata->mapField([
'fieldName' => 'destinationUrl',
'columnName'=> 'destination_url',
'type' => Types::TEXT,
'nullable' => true,
]);
$metadata->mapField([
'fieldName' => 'utmParameters',
'columnName'=> 'utm_parameters',
'type' => Types::JSON,
]);
// Mautic destinations: a landing page or a standalone form. Deleting the page or the
// form keeps the link (the column becomes null, the link then 404s until reconfigured).
$builder->createManyToOne('page', Page::class)
->addJoinColumn('page_id', 'id', true, false, 'SET NULL')
->build();
$builder->createManyToOne('form', Form::class)
->addJoinColumn('form_id', 'id', true, false, 'SET NULL')
->build();
// The UTM Taxonomy of the link. Deleting the taxonomy keeps the link (the column becomes
// null): it keeps redirecting with the values it already carries, and its next edit
// demands a new taxonomy.
$builder->createManyToOne('taxonomy', UtmTaxonomy::class)
->addJoinColumn('utm_taxonomy_id', 'id', true, false, 'SET NULL')
->build();
}
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addPropertyConstraint('slug', new NotBlank(message: 'mt3s.smart_links.smart_links.error.slug_required'));
$metadata->addPropertyConstraint('slug', new Length(
max: self::SLUG_MAX_LENGTH,
maxMessage: 'mt3s.smart_links.smart_links.error.slug_length',
));
}
public function getId(): ?int
{
return $this->id;
}
/**
* Core's standard list actions and flash messages call getName(); the slug is the
* link's name.
*/
public function getName(): string
{
return (string) $this->slug;
}
/**
* The short link, for example https://lnk.example.com/l/ab3x. Empty when no domain is set.
*/
public function getShortLink(string $domain): string
{
$domain = trim((string) $domain);
return '' === $domain || '' === (string) $this->slug ? '' : 'https://'.rtrim($domain, '/').'/l/'.$this->slug;
}
public function getSlug(): ?string
{
return $this->slug;
}
/**
* The slug of a saved link is immutable: once set at creation time, it can't change.
*/
public function setSlug(?string $slug): static
{
$immutable = null !== $this->id && null !== $this->slug && '' !== $this->slug;
if ($immutable && null !== $slug && $slug !== $this->slug) {
throw new \LogicException('The slug of a saved smart link cannot be changed.');
}
$this->isChanged('slug', $slug);
$this->slug = $slug;
return $this;
}
public function getRedirectType(): SmartLinkRedirectType
{
return $this->redirectType;
}
public function setRedirectType(SmartLinkRedirectType $redirectType): static
{
if ($redirectType !== $this->redirectType) {
// isChanged() can't log enums (they aren't stringable), so log the backing values.
$this->addChange('redirectType', [$this->redirectType->value, $redirectType->value]);
$this->redirectType = $redirectType;
}
// The destination only exists for external redirects.
if ($redirectType->isMautic()) {
$this->setDestinationUrl(null);
}
return $this;
}
public function getRedirectCode(): SmartLinkRedirectCode
{
return $this->redirectCode;
}
public function setRedirectCode(SmartLinkRedirectCode $redirectCode): static
{
if ($redirectCode !== $this->redirectCode) {
$this->addChange('redirectCode', [$this->redirectCode->value, $redirectCode->value]);
$this->redirectCode = $redirectCode;
}
return $this;
}
public function getDestinationUrl(): ?string
{
return $this->destinationUrl;
}
public function setDestinationUrl(?string $destinationUrl): static
{
if (null !== $destinationUrl && '' === trim($destinationUrl)) {
$destinationUrl = null;
}
$this->isChanged('destinationUrl', $destinationUrl);
$this->destinationUrl = $destinationUrl;
return $this;
}
/**
* @return array<string, string>
*/
public function getUtmParameters(): array
{
return $this->utmParameters;
}
/**
* @param array<string, string>|null $utmParameters
*/
public function setUtmParameters(?array $utmParameters): static
{
$this->isChanged('utmParameters', $utmParameters);
$this->utmParameters = $utmParameters ?? [];
return $this;
}
public function getPage(): ?Page
{
return $this->page;
}
public function setPage(?Page $page): static
{
$this->isChanged('page', $page);
$this->page = $page;
return $this;
}
public function getForm(): ?Form
{
return $this->form;
}
public function setForm(?Form $form): static
{
$this->isChanged('form', $form);
$this->form = $form;
return $this;
}
public function getTaxonomy(): ?UtmTaxonomy
{
return $this->taxonomy;
}
public function setTaxonomy(?UtmTaxonomy $taxonomy): static
{
$this->isChanged('taxonomy', $taxonomy);
$this->taxonomy = $taxonomy;
return $this;
}
/**
* The title of the destination, whatever its type: the slug for external links, the page
* title or the form name for Mautic ones. Used by the list and the flash messages.
*/
public function getDestinationLabel(): string
{
if ($this->redirectType->isMautic()) {
return $this->page?->getTitle() ?? $this->form?->getName() ?? '';
}
return (string) ($this->destinationUrl ?? '');
}
}
+118
View File
@@ -0,0 +1,118 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Entity;
use Doctrine\ORM\Mapping\ClassMetadata as OrmClassMetadata;
use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder;
use Mautic\CoreBundle\Entity\FormEntity;
/**
* One call of a Smart Link: the short link was requested by a visitor and redirected them.
* One row is written per hit; the Smart Links list shows the derived counts.
*
* date_added and the other audit columns are inherited from FormEntity (mapped there).
*/
class SmartLinkHit extends FormEntity
{
public const TABLE_NAME = 'smart_link_hits';
private ?int $id = null;
private ?SmartLink $smartLink = null;
private ?string $ipAddress = null;
private ?string $referer = null;
private ?string $userAgent = null;
public static function loadMetadata(OrmClassMetadata $metadata): void
{
$builder = new ClassMetadataBuilder($metadata);
$builder->setTable(self::TABLE_NAME)
->setCustomRepositoryClass(SmartLinkHitRepository::class)
->addIndex(['smart_link_id'], 'smart_link_hit_link');
$builder->addId();
// Deleting the link deletes its hits.
$builder->createManyToOne('smartLink', SmartLink::class)
->addJoinColumn('smart_link_id', 'id', false, false, 'CASCADE')
->build();
$builder->createField('ipAddress', 'string')
->columnName('ip_address')
->length(45) // IPv6
->nullable()
->build();
$builder->createField('referer', 'text')
->nullable()
->build();
$builder->createField('userAgent', 'text')
->columnName('user_agent')
->nullable()
->build();
}
public function getId(): ?int
{
return $this->id;
}
public function getSmartLink(): ?SmartLink
{
return $this->smartLink;
}
public function setSmartLink(?SmartLink $smartLink): static
{
$this->isChanged('smartLink', $smartLink);
$this->smartLink = $smartLink;
return $this;
}
public function getIpAddress(): ?string
{
return $this->ipAddress;
}
public function setIpAddress(?string $ipAddress): static
{
$this->isChanged('ipAddress', $ipAddress);
$this->ipAddress = $ipAddress;
return $this;
}
public function getReferer(): ?string
{
return $this->referer;
}
public function setReferer(?string $referer): static
{
$this->isChanged('referer', $referer);
$this->referer = $referer;
return $this;
}
public function getUserAgent(): ?string
{
return $this->userAgent;
}
public function setUserAgent(?string $userAgent): static
{
$this->isChanged('userAgent', $userAgent);
$this->userAgent = $userAgent;
return $this;
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Entity;
use Mautic\CoreBundle\Entity\CommonRepository;
/**
* @extends CommonRepository<SmartLinkHit>
*/
class SmartLinkHitRepository extends CommonRepository
{
public function getTableAlias(): string
{
return 'slh';
}
/**
* Hit counts of every Smart Link, in one query (list view): link id => number of hits.
*
* @return array<int, int>
*/
public function getHitCounts(): array
{
$alias = $this->getTableAlias();
$rows = $this->createQueryBuilder($alias)
->select('IDENTITY('.$alias.'.smartLink) AS link_id, COUNT('.$alias.'.id) AS hit_count')
->groupBy($alias.'.smartLink')
->getQuery()
->getArrayResult();
$counts = [];
foreach ($rows as $row) {
$counts[(int) $row['link_id']] = (int) $row['hit_count'];
}
return $counts;
}
/**
* The last hits of a link, most recent first.
*
* @return SmartLinkHit[]
*/
public function findRecentBySmartLink(SmartLink $smartLink, int $limit = 10): array
{
return $this->createQueryBuilder($this->getTableAlias())
->where($this->getTableAlias().'.smartLink = :link')
->setParameter('link', $smartLink)
->orderBy($this->getTableAlias().'.dateAdded', 'DESC')
->setMaxResults($limit)
->getQuery()
->getResult();
}
}
+108
View File
@@ -0,0 +1,108 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Entity;
use Mautic\CoreBundle\Entity\CommonRepository;
/**
* @extends CommonRepository<SmartLink>
*/
class SmartLinkRepository extends CommonRepository
{
public function getTableAlias(): string
{
return 'sl';
}
/**
* Loads the page and the form with the links, so that the list doesn't query them one by one.
*
* @param array<string, mixed> $args
*/
public function getEntities(array $args = [])
{
$alias = $this->getTableAlias();
// The hit count of each link as a HIDDEN scalar: not hydrated into the entities, but
// available as an order by column ("sl.hitCount") for the Hits column of the list.
$hitCount = '(SELECT COUNT(h.id) FROM '.SmartLinkHit::class.' h WHERE h.smartLink = '.$alias.'.id) AS HIDDEN hitCount';
$args['qb'] = $this->createQueryBuilder($alias)
->select($alias, 'pg', 'fm', $hitCount)
->leftJoin($alias.'.page', 'pg')
->leftJoin($alias.'.form', 'fm');
return parent::getEntities($args);
}
/**
* True when another link already uses this slug. A link being edited never collides with itself.
*/
public function slugExists(string $slug, ?int $ignoreId = null): bool
{
if ('' === $slug) {
return false;
}
$qb = $this->createQueryBuilder($this->getTableAlias())
->select('COUNT('.$this->getTableAlias().'.id)')
->where($this->getTableAlias().'.slug = :slug')
->setParameter('slug', $slug);
if (null !== $ignoreId) {
$qb->andWhere($this->getTableAlias().'.id != :id')
->setParameter('id', $ignoreId);
}
return (int) $qb->getQuery()->getSingleScalarResult() > 0;
}
/**
* The list's search box matches the slug and the destination URL.
*
* @return array<int, mixed>
*/
protected function addCatchAllWhereClause($q, $filter): array
{
return $this->addStandardCatchAllWhereClause($q, $filter, [
$this->getTableAlias().'.slug',
$this->getTableAlias().'.destinationUrl',
]);
}
/**
* The Hits column of the list sorts by the number of hits of each link: the virtual
* "hitCount" order by maps to the HIDDEN hitCount scalar of the list query. Everything
* else falls back to core's column handling.
*
* @param array<string, mixed> $args
*/
protected function buildOrderByClause($q, array $args): void
{
$alias = $this->getTableAlias();
$orderBy = (string) ($args['orderBy'] ?? '');
$virtual = $alias.'.hitCount' === $orderBy || 'hitCount' === $orderBy;
if ($virtual && $q instanceof \Doctrine\ORM\QueryBuilder) {
$orderByDir = $this->sanitize((string) ($args['orderByDir'] ?? 'ASC'));
$q->addOrderBy('hitCount', $orderByDir);
return;
}
parent::buildOrderByClause($q, $args);
}
/**
* @return array<array{0: string, 1: string}>
*/
protected function getDefaultOrder(): array
{
return [
[$this->getTableAlias().'.slug', 'ASC'],
];
}
}
+3 -2
View File
@@ -19,9 +19,10 @@ class StakeholderRepository extends CommonRepository
} }
/** /**
* The list's search box matches the name, email, role and type. * The list's search box matches the name, email, role and type. Core passes the filter
* as an object with ->string and ->strict (its own docblock), not an array.
* *
* @param array<int, mixed> $filter * @param \stdClass $filter
* *
* @return array<int, mixed> * @return array<int, mixed>
*/ */
+5 -5
View File
@@ -51,12 +51,12 @@ class TaskDependency
->build(); ->build();
$metadata->mapField([ $metadata->mapField([
'fieldName' => 'dependencyType', 'fieldName' => 'dependencyType',
'columnName' => 'dependency_type', 'columnName' => 'dependency_type',
'type' => Types::STRING, 'type' => Types::STRING,
'length' => 20, 'length' => 20,
'enumType' => DependencyType::class, 'enumType' => DependencyType::class,
'options' => ['default' => DependencyType::EndToStart->value], 'options' => ['default' => DependencyType::EndToStart->value],
]); ]);
$builder->createField('position', Types::INTEGER) $builder->createField('position', Types::INTEGER)
+1 -1
View File
@@ -4,9 +4,9 @@ declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Entity; namespace MauticPlugin\MT3SMarketingProgramBundle\Entity;
use Doctrine\DBAL\Types\Types;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping\ClassMetadata as OrmClassMetadata; use Doctrine\ORM\Mapping\ClassMetadata as OrmClassMetadata;
use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder; use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder;
+143
View File
@@ -0,0 +1,143 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Entity;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping\ClassMetadata as OrmClassMetadata;
use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder;
use Mautic\CoreBundle\Entity\FormEntity;
/**
* A UTM Taxonomy: a named set of allowed values for the UTM parameters.
*
* A Smart Link carries one taxonomy; every UTM value of the link is chosen
* among the values the taxonomy defines for its parameter.
*
* The allowed values live in the `parameters` array: parameter key => list of
* {value, label} rows. Only the parameters enabled in Settings > Configuration
* > Smart Links Settings can be given values (the form only offers those).
*/
class UtmTaxonomy extends FormEntity
{
public const TABLE_NAME = 'utm_taxonomies';
public const NAME_MAX_LENGTH = 50;
private ?int $id = null;
private ?string $name = null;
private ?string $description = null;
/**
* Allowed values per parameter: parameter key => list of {value, label}.
*
* @var array<string, list<array{value: string, label: string}>>
*/
private array $parameters = [];
public static function loadMetadata(OrmClassMetadata $metadata): void
{
$builder = new ClassMetadataBuilder($metadata);
$builder->setTable(self::TABLE_NAME)
->setCustomRepositoryClass(UtmTaxonomyRepository::class)
->addIndex(['name'], 'utm_taxonomy_name');
$builder->addId();
$builder->createField('name', Types::STRING)
->length(self::NAME_MAX_LENGTH)
->unique()
->build();
$builder->createField('description', Types::TEXT)
->nullable()
->build();
// Mapped on the raw metadata: ClassMetadataBuilder::addField() forces VARCHAR(191) on strings.
$metadata->mapField([
'fieldName' => 'parameters',
'columnName' => 'parameters',
'type' => Types::JSON,
]);
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name): static
{
$this->isChanged('name', $name);
$this->name = '' !== trim((string) $name) ? $name : null;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): static
{
if (null !== $description && '' === trim($description)) {
$description = null;
}
$this->isChanged('description', $description);
$this->description = $description;
return $this;
}
/**
* @return array<string, list<array{value: string, label: string}>>
*/
public function getParameters(): array
{
return $this->parameters;
}
/**
* @param array<string, list<array{value: string, label: string}>>|null $parameters
*/
public function setParameters(?array $parameters): static
{
$this->isChanged('parameters', $parameters);
$this->parameters = $parameters ?? [];
ksort($this->parameters);
return $this;
}
/**
* The allowed values of one parameter, keyed by value (labels are unique per value).
*
* @return list<array{value: string, label: string}>
*/
public function getParameterValues(string $key): array
{
return $this->parameters[$key] ?? [];
}
/**
* The parameter keys the taxonomy defines, in display order.
*
* @return list<string>
*/
public function getParameterKeys(): array
{
return array_keys($this->parameters);
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Entity;
use Mautic\CoreBundle\Entity\CommonRepository;
/**
* @extends CommonRepository<UtmTaxonomy>
*/
class UtmTaxonomyRepository extends CommonRepository
{
public function getTableAlias(): string
{
return 'ut';
}
/**
* True when another taxonomy already uses this name. A taxonomy being edited never collides with itself.
*/
public function nameExists(string $name, ?int $ignoreId = null): bool
{
if ('' === $name) {
return false;
}
$qb = $this->createQueryBuilder($this->getTableAlias())
->select('COUNT('.$this->getTableAlias().'.id)')
->where($this->getTableAlias().'.name = :name')
->setParameter('name', $name);
if (null !== $ignoreId) {
$qb->andWhere($this->getTableAlias().'.id != :id')
->setParameter('id', $ignoreId);
}
return (int) $qb->getQuery()->getSingleScalarResult() > 0;
}
/**
* The list's search box matches the name and the description.
*
* @return array<int, mixed>
*/
protected function addCatchAllWhereClause($q, $filter): array
{
return $this->addStandardCatchAllWhereClause($q, $filter, [
$this->getTableAlias().'.name',
$this->getTableAlias().'.description',
]);
}
/**
* @return array<array{0: string, 1: string}>
*/
protected function getDefaultOrder(): array
{
return [
[$this->getTableAlias().'.name', 'ASC'],
];
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\EventListener;
use Mautic\ConfigBundle\ConfigEvents;
use Mautic\ConfigBundle\Event\ConfigBuilderEvent;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Type\SmartLinksConfigType;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Adds the "Smart Links Settings" tab to Settings > Configuration.
*/
final class SmartLinksConfigSubscriber implements EventSubscriberInterface
{
public const FORM_ALIAS = 'smartlinksconfig';
public static function getSubscribedEvents(): array
{
return [
ConfigEvents::CONFIG_ON_GENERATE => ['onConfigGenerate', 0],
];
}
public function onConfigGenerate(ConfigBuilderEvent $event): void
{
$event->addForm([
'bundle' => 'MT3SMarketingProgramBundle',
'formAlias' => self::FORM_ALIAS,
'formType' => SmartLinksConfigType::class,
'formTheme' => '@MT3SMarketingProgram/FormTheme/Config/_config_smartlinksconfig_widget.html.twig',
'parameters' => $event->getParametersFromConfig('MT3SMarketingProgramBundle'),
]);
}
}
@@ -0,0 +1,146 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\DataTransformer;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterCatalog;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterMode;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationNormalizer;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Converts between the stored `mt3s_smart_links_utm_config` array (parameters keyed by their key)
* and the form structure (catalog parameters + a collection of custom parameters).
*
* @implements DataTransformerInterface<mixed, array<string, mixed>>
*/
final class UtmSettingsTransformer implements DataTransformerInterface
{
public function __construct(
private readonly UtmConfigurationNormalizer $normalizer,
private readonly UtmParameterCatalog $catalog,
private readonly TranslatorInterface $translator,
) {
}
/**
* Stored configuration => form data.
*
* @return array<string, mixed>
*/
public function transform(mixed $value): array
{
$config = $this->normalizer->normalize($value);
$parameters = [];
$custom = [];
foreach ($config['parameters'] as $key => $parameter) {
$definition = $this->catalog->get($key);
$row = [
'enabled' => $parameter['enabled'],
'label' => $parameter['label'],
'mode' => $parameter['mode'],
'values' => $this->valuesToForm($parameter['values'] ?? [], $parameter['default'] ?? null),
];
if (null === $definition) {
$custom[] = ['key' => $key] + $row;
continue;
}
if ('' === $row['label']) {
$row['label'] = $this->translator->trans($definition->getLabelKey());
}
$parameters[$key] = $row;
}
return [
'enforce_lowercase' => $config['enforce_lowercase'],
'separator_replacement' => $config['separator_replacement'],
'parameters' => $parameters,
'custom_parameters' => $custom,
];
}
/**
* Form data => stored configuration.
*
* @return array<string, mixed>
*/
public function reverseTransform(mixed $value): array
{
$value = is_array($value) ? $value : [];
$parameters = [];
foreach ($value['parameters'] ?? [] as $key => $parameter) {
$parameters[(string) $key] = $this->parameterToStorage($parameter);
}
foreach ($value['custom_parameters'] ?? [] as $parameter) {
$key = trim((string) ($parameter['key'] ?? ''));
if ('' !== $key) {
$parameters[$key] = $this->parameterToStorage($parameter);
}
}
return [
'enforce_lowercase' => UtmConfigurationNormalizer::toBool($value['enforce_lowercase'] ?? true),
'separator_replacement' => (string) ($value['separator_replacement'] ?? UtmConfigurationNormalizer::DEFAULT_SEPARATOR),
'parameters' => $parameters,
];
}
/**
* Only `dropdown` parameters keep values and a default; nothing else is stored for the other modes.
*
* @param array<string, mixed> $parameter
*
* @return array<string, mixed>
*/
private function parameterToStorage(array $parameter): array
{
$mode = (string) ($parameter['mode'] ?? UtmParameterMode::DISABLED);
$stored = [
'enabled' => UtmConfigurationNormalizer::toBool($parameter['enabled'] ?? false),
'label' => trim((string) ($parameter['label'] ?? '')),
'mode' => $mode,
];
if (UtmParameterMode::DROPDOWN !== $mode) {
return $stored;
}
$stored['values'] = [];
$stored['default'] = '';
foreach ($parameter['values'] ?? [] as $row) {
$rowValue = trim((string) ($row['value'] ?? ''));
if ('' === $rowValue) {
continue;
}
$stored['values'][] = ['value' => $rowValue, 'label' => trim((string) ($row['label'] ?? ''))];
if ('' === $stored['default'] && !empty($row['is_default'])) {
$stored['default'] = $rowValue;
}
}
return $stored;
}
/**
* @param list<array{value: string, label: string}> $values
*
* @return list<array{value: string, label: string, is_default: bool}>
*/
private function valuesToForm(array $values, ?string $default): array
{
return array_map(
fn (array $row): array => $row + ['is_default' => $row['value'] === $default],
$values
);
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Extension;
use Mautic\EmailBundle\Form\Type\EmailUtmTagsType;
use MauticPlugin\MT3SMarketingProgramBundle\Form\UtmFieldsApplicator;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Applies the UTM taxonomy to the "UTM tags" subform. Core uses EmailUtmTagsType for both
* the Email form (EmailType) and the Focus Item form (FocusType), so this covers both.
*
* Registered as `form.type_extension` by autoconfiguration (Config/services.php).
*/
final class UtmTagsTypeExtension extends AbstractTypeExtension
{
public function __construct(
private readonly UtmFieldsApplicator $applicator,
) {
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$this->applicator->apply($builder);
}
/**
* @return iterable<class-string>
*/
public static function getExtendedTypes(): iterable
{
return [EmailUtmTagsType::class];
}
}
+1 -3
View File
@@ -28,8 +28,6 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
* fixed type (persona, ICP, …), the segments (purely informational), then the persona attributes * fixed type (persona, ICP, …), the segments (purely informational), then the persona attributes
* the admin switched on in Settings > Configuration > Program Settings (AudienceAttributes): one * the admin switched on in Settings > Configuration > Program Settings (AudienceAttributes): one
* toggle per attribute, so a b2b install and a b2c install define their personas differently. * toggle per attribute, so a b2b install and a b2c install define their personas differently.
*
* @extends AbstractType<Audience>
*/ */
class AudienceType extends AbstractType class AudienceType extends AbstractType
{ {
@@ -167,7 +165,7 @@ class AudienceType extends AbstractType
if (in_array('stages', $enabled, true)) { if (in_array('stages', $enabled, true)) {
$builder->add('stages', EntityType::class, [ $builder->add('stages', EntityType::class, [
'label' => 'mt3s.marketing_program.audience.field.stages', 'label' => 'mt3s.marketing_program.audience.field.stages',
'label_attr' => ['class' => 'control-label'], 'label_attr' => ['class' => 'control-label'],
'attr' => ['class' => 'form-control'], 'attr' => ['class' => 'form-control'],
'class' => Stage::class, 'class' => Stage::class,
+2 -4
View File
@@ -4,13 +4,13 @@ declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Type; namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Type;
use Mautic\CoreBundle\Form\Type\YesNoButtonGroupType;
use MauticPlugin\MT3SMarketingProgramBundle\Model\StakeholderModel; use MauticPlugin\MT3SMarketingProgramBundle\Model\StakeholderModel;
use MauticPlugin\MT3SMarketingProgramBundle\Service\CurrencyProvider;
use MauticPlugin\MT3SMarketingProgramBundle\Service\AudienceAttributes; use MauticPlugin\MT3SMarketingProgramBundle\Service\AudienceAttributes;
use MauticPlugin\MT3SMarketingProgramBundle\Service\CurrencyProvider;
use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\Core\Type\TextType;
use Mautic\CoreBundle\Form\Type\YesNoButtonGroupType;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\NotBlank;
@@ -24,8 +24,6 @@ use Symfony\Component\Validator\Constraints\NotBlank;
* *
* The item type lists moved to their own page under Programs (ItemTypesController, Programs > * The item type lists moved to their own page under Programs (ItemTypesController, Programs >
* Item types). * Item types).
*
* @extends AbstractType<array<string, mixed>>
*/ */
class ConfigType extends AbstractType class ConfigType extends AbstractType
{ {
-2
View File
@@ -25,8 +25,6 @@ use Symfony\Component\Validator\Constraints\NotBlank;
* *
* The key is hidden. It is generated when the type is created and never changes, so that renaming a * The key is hidden. It is generated when the type is created and never changes, so that renaming a
* type doesn't affect the items that use it. * type doesn't affect the items that use it.
*
* @extends AbstractType<array<string, mixed>>
*/ */
class ItemTypeConfigType extends AbstractType class ItemTypeConfigType extends AbstractType
{ {
+6 -8
View File
@@ -17,8 +17,6 @@ use Symfony\Component\Form\FormBuilderInterface;
* an audience's decision roles and tones. Each child is one of ItemTypeProvider::PARAMETERS, * an audience's decision roles and tones. Each child is one of ItemTypeProvider::PARAMETERS,
* keyed exactly by the local.php parameter that stores the list, so saving is a straight merge * keyed exactly by the local.php parameter that stores the list, so saving is a straight merge
* into the local configuration. * into the local configuration.
*
* @extends AbstractType<array<string, mixed>>
*/ */
class ItemTypesType extends AbstractType class ItemTypesType extends AbstractType
{ {
@@ -29,15 +27,15 @@ class ItemTypesType extends AbstractType
$withIcon = !in_array($kind, [ItemTypeProvider::KIND_AUDIENCE_DECISION_ROLE, ItemTypeProvider::KIND_AUDIENCE_TONE], true); $withIcon = !in_array($kind, [ItemTypeProvider::KIND_AUDIENCE_DECISION_ROLE, ItemTypeProvider::KIND_AUDIENCE_TONE], true);
$builder->add($parameter, CollectionType::class, [ $builder->add($parameter, CollectionType::class, [
'label' => false, 'label' => false,
'entry_type' => ItemTypeConfigType::class, 'entry_type' => ItemTypeConfigType::class,
'entry_options' => ['label' => false, 'with_icon' => $withIcon], 'entry_options' => ['label' => false, 'with_icon' => $withIcon],
'allow_add' => true, 'allow_add' => true,
'allow_delete' => true, 'allow_delete' => true,
'prototype' => true, 'prototype' => true,
'prototype_name' => '__type__', 'prototype_name' => '__type__',
'required' => false, 'required' => false,
'error_bubbling' => false, 'error_bubbling' => false,
]); ]);
// Stored as a clean list (0..n-1, empty texts dropped), in the order shown on the page. // Stored as a clean list (0..n-1, empty texts dropped), in the order shown on the page.
-2
View File
@@ -21,8 +21,6 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
* real cost (both in the general currency). Works like ProgramDescriptionItemType (type description shown * real cost (both in the general currency). Works like ProgramDescriptionItemType (type description shown
* under the dropdown and its pictogram next to it, hidden position kept in display order by * under the dropdown and its pictogram next to it, hidden position kept in display order by
* Assets/js/mt3s-mp-program.js). * Assets/js/mt3s-mp-program.js).
*
* @extends AbstractType<ProgramAllocationItem>
*/ */
class ProgramAllocationItemType extends AbstractType class ProgramAllocationItemType extends AbstractType
{ {
-2
View File
@@ -20,8 +20,6 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
* One row of the audiences collection in ProgramType: an audience of the global directory (only the * One row of the audiences collection in ProgramType: an audience of the global directory (only the
* active ones are offered), the audience's priority in this plan, and possibly a program-specific * active ones are offered), the audience's priority in this plan, and possibly a program-specific
* message. The position field is hidden and kept in display order by Assets/js/mt3s-mp-program.js. * message. The position field is hidden and kept in display order by Assets/js/mt3s-mp-program.js.
*
* @extends AbstractType<ProgramAudience>
*/ */
class ProgramAudienceType extends AbstractType class ProgramAudienceType extends AbstractType
{ {
-2
View File
@@ -18,8 +18,6 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
* types set up in Settings > Configuration > Program; each option carries the type's description, which * types set up in Settings > Configuration > Program; each option carries the type's description, which
* Assets/js/mt3s-mp-program.js shows under the dropdown. The position field is hidden and kept in display order by * Assets/js/mt3s-mp-program.js shows under the dropdown. The position field is hidden and kept in display order by
* mt3s-mp-program.js. * mt3s-mp-program.js.
*
* @extends AbstractType<ProgramDescriptionItem>
*/ */
class ProgramDescriptionItemType extends AbstractType class ProgramDescriptionItemType extends AbstractType
{ {
+1 -3
View File
@@ -20,8 +20,6 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
* One row of the objectives collection in ProgramType: type, title, priority, description and the achieved * One row of the objectives collection in ProgramType: type, title, priority, description and the achieved
* flag. Works like ProgramDescriptionItemType (type description shown under the dropdown and its pictogram * flag. Works like ProgramDescriptionItemType (type description shown under the dropdown and its pictogram
* next to it, hidden position kept in display order by Assets/js/mt3s-mp-program.js). * next to it, hidden position kept in display order by Assets/js/mt3s-mp-program.js).
*
* @extends AbstractType<ProgramObjective>
*/ */
class ProgramObjectiveType extends AbstractType class ProgramObjectiveType extends AbstractType
{ {
@@ -58,7 +56,7 @@ class ProgramObjectiveType extends AbstractType
'label' => 'mt3s.marketing_program.objective.field.priority', 'label' => 'mt3s.marketing_program.objective.field.priority',
'label_attr' => ['class' => 'control-label'], 'label_attr' => ['class' => 'control-label'],
'invalid_message' => 'mt3s.marketing_program.objective.priority.range', 'invalid_message' => 'mt3s.marketing_program.objective.priority.range',
'attr' => [ 'attr' => [
'class' => 'form-control', 'class' => 'form-control',
'min' => ProgramObjective::PRIORITY_MIN, 'min' => ProgramObjective::PRIORITY_MIN,
'max' => ProgramObjective::PRIORITY_MAX, 'max' => ProgramObjective::PRIORITY_MAX,
-2
View File
@@ -18,8 +18,6 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
* One row of the stakeholders collection in ProgramType: a stakeholder of the global directory (only the * One row of the stakeholders collection in ProgramType: a stakeholder of the global directory (only the
* active ones are offered) and the stakeholder's role in this plan. The position field is hidden and * active ones are offered) and the stakeholder's role in this plan. The position field is hidden and
* kept in display order by Assets/js/mt3s-mp-program.js. * kept in display order by Assets/js/mt3s-mp-program.js.
*
* @extends AbstractType<ProgramStakeholder>
*/ */
class ProgramStakeholderType extends AbstractType class ProgramStakeholderType extends AbstractType
{ {
+9 -14
View File
@@ -16,8 +16,6 @@ use Mautic\UserBundle\Form\Type\UserListType;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\Program; use MauticPlugin\MT3SMarketingProgramBundle\Entity\Program;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\ProgramStatus; use MauticPlugin\MT3SMarketingProgramBundle\Entity\ProgramStatus;
use MauticPlugin\MT3SMarketingProgramBundle\Service\CurrencyProvider; use MauticPlugin\MT3SMarketingProgramBundle\Service\CurrencyProvider;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Type\ProgramAudienceType;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Type\ProgramStakeholderType;
use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType; use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\EnumType; use Symfony\Component\Form\Extension\Core\Type\EnumType;
@@ -27,9 +25,6 @@ use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* @extends AbstractType<Program>
*/
class ProgramType extends AbstractType class ProgramType extends AbstractType
{ {
public function __construct( public function __construct(
@@ -81,15 +76,15 @@ class ProgramType extends AbstractType
// The Audiences tab's links to the global directory. by_reference false: Symfony calls // The Audiences tab's links to the global directory. by_reference false: Symfony calls
// Program::addAudience()/removeAudience(). // Program::addAudience()/removeAudience().
$builder->add('audiences', CollectionType::class, [ $builder->add('audiences', CollectionType::class, [
'label' => 'mt3s.marketing_program.field.audiences', 'label' => 'mt3s.marketing_program.field.audiences',
'entry_type' => ProgramAudienceType::class, 'entry_type' => ProgramAudienceType::class,
'entry_options' => ['label' => false], 'entry_options' => ['label' => false],
'allow_add' => true, 'allow_add' => true,
'allow_delete' => true, 'allow_delete' => true,
'by_reference' => false, 'by_reference' => false,
'prototype' => true, 'prototype' => true,
'prototype_name' => '__audience__', 'prototype_name' => '__audience__',
'required' => false, 'required' => false,
]); ]);
// The Stakeholders tab's links to the global directory. by_reference false: Symfony calls // The Stakeholders tab's links to the global directory. by_reference false: Symfony calls
@@ -110,7 +105,7 @@ class ProgramType extends AbstractType
'label' => 'mt3s.marketing_program.field.version', 'label' => 'mt3s.marketing_program.field.version',
'label_attr' => ['class' => 'control-label'], 'label_attr' => ['class' => 'control-label'],
'invalid_message' => 'mt3s.marketing_program.version.range', 'invalid_message' => 'mt3s.marketing_program.version.range',
'attr' => [ 'attr' => [
'class' => 'form-control', 'class' => 'form-control',
'min' => Program::VERSION_MIN, 'min' => Program::VERSION_MIN,
'max' => Program::VERSION_MAX, 'max' => Program::VERSION_MAX,
+603
View File
@@ -0,0 +1,603 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Type;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Mautic\CoreBundle\Form\Type\FormButtonsType;
use Mautic\FormBundle\Entity\Form as MauticForm;
use Mautic\PageBundle\Entity\Page;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\SmartLinkRedirectCode;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\SmartLinkRedirectType;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\UtmTaxonomy;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Validator\SmartLinkValidator;
use MauticPlugin\MT3SMarketingProgramBundle\Model\SmartLinkModel;
use MauticPlugin\MT3SMarketingProgramBundle\Service\SmartLinkShortUrlBuilder;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationProvider;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\EnumType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\UrlType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Regex;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Create / edit a Smart Link.
*
* - the slug is disabled once the link is saved (a saved link can only be deleted, never renamed);
* - a "Generate" button (JavaScript) offers a random 4-character slug of letters and digits;
* - the destination URL only applies to external redirect types (Mautic redirects are not
* processed yet);
* - the link carries a UTM Taxonomy (required): one fieldset per taxonomy is rendered, each
* field a select restricted to the values the taxonomy allows for its parameter. Mautic's
* data-show-on switcher shows the fieldset of the chosen taxonomy; the values posted for
* the others are dropped on submit. A stored value outside the list stays selectable,
* labelled "(not in taxonomy)", so an old link is still editable.
*/
final class SmartLinkType extends AbstractType
{
/**
* The values the link carried when the form was built: a value outside its taxonomy stays
* acceptable (it was chosen when the taxonomy allowed it), so a plain re-save never errors.
*
* @var array<string, string>
*/
private array $originalUtmParameters = [];
public function __construct(
private readonly SmartLinkValidator $validator,
private readonly SmartLinkShortUrlBuilder $shortUrlBuilder,
private readonly UtmConfigurationProvider $utmConfiguration,
private readonly SmartLinkModel $smartLinkModel,
private readonly TranslatorInterface $translator,
private readonly EntityManagerInterface $entityManager,
) {
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
/** @var SmartLink $smartLink */
$smartLink = $options['data'];
$isSaved = null !== $smartLink->getId();
$this->originalUtmParameters = $smartLink->getUtmParameters();
// -- Slug --------------------------------------------------------------
// Spaces are replaced by the configured character and lowercase is enforced by the model
// on save, exactly like the live preview does. The constraints only guard the raw input;
// spaces are allowed here because they are turned into the separator on save.
$builder->add('slug', TextType::class, [
'label' => 'mt3s.smart_links.smart_links.slug',
'required' => true,
'disabled' => $isSaved,
'attr' => [
'class' => 'form-control smart-link-slug',
'maxlength' => SmartLink::SLUG_MAX_LENGTH,
'tooltip' => 'mt3s.smart_links.smart_links.slug.tooltip',
// Live preview of the short link: the JS fills the span next to the field.
'data-preview' => 'smart-link-preview',
],
'constraints' => $isSaved ? [] : [
new NotBlank(message: 'mt3s.smart_links.smart_links.error.slug_required'),
new Length(max: SmartLink::SLUG_MAX_LENGTH, maxMessage: 'mt3s.smart_links.smart_links.error.slug_length'),
new Regex(
pattern: '/^[\p{L}0-9\-_. ]*$/u',
message: 'mt3s.smart_links.smart_links.error.slug_characters'
),
new Callback(callback: $this->validateSlug(...)),
],
]);
// -- Redirect ------------------------------------------------------------
$builder->add('redirectType', EnumType::class, [
'label' => 'mt3s.smart_links.smart_links.redirect_type',
'class' => SmartLinkRedirectType::class,
'choice_label' => fn (SmartLinkRedirectType $type): string => $this->translator->trans($type->getLabelKey()),
'attr' => ['class' => 'form-control smart-link-redirect-type'],
]);
$builder->add('redirectCode', EnumType::class, [
'label' => 'mt3s.smart_links.smart_links.redirect_code',
'class' => SmartLinkRedirectCode::class,
'choice_label' => fn (SmartLinkRedirectCode $code): string => $code->getTranslatedLabel($this->translator),
'attr' => ['class' => 'form-control smart-link-redirect-code'],
]);
$builder->add('destinationUrl', UrlType::class, [
'label' => 'mt3s.smart_links.smart_links.destination_url',
'required' => false,
'attr' => [
'class' => 'form-control smart-link-destination',
'tooltip' => 'mt3s.smart_links.smart_links.destination_url.tooltip',
],
'constraints' => [new Callback(callback: $this->validateDestination(...))],
]);
// -- Mautic destination: a landing page or a standalone form -------------------------
$builder->add('destination', ChoiceType::class, [
'label' => 'mt3s.smart_links.smart_links.destination',
'required' => false,
'mapped' => false,
'attr' => [
'class' => 'form-control smart-link-mautic-destination',
'tooltip' => 'mt3s.smart_links.smart_links.destination.tooltip',
],
'choices' => $this->buildMauticDestinationChoices($smartLink),
'placeholder' => 'mt3s.smart_links.form.choose',
'data' => $this->currentMauticDestination($smartLink),
]);
// -- UTM Taxonomy ------------------------------------------------------------
// The taxonomy of the link drives its UTM values. Required: a link always carries one
// from now on; a link that predates the feature picks one on its next edit. A stored
// taxonomy that is no longer published stays selectable, so an old link is still
// editable (a new one can always be chosen instead).
$builder->add('taxonomy', ChoiceType::class, [
'label' => 'mt3s.smart_links.smart_links.taxonomy',
'required' => true,
'placeholder' => 'mt3s.smart_links.form.choose',
'choices' => $this->buildTaxonomyChoices($smartLink),
'choice_value' => fn (?UtmTaxonomy $taxonomy): string => (string) ($taxonomy?->getId() ?? ''),
'attr' => [
'class' => 'form-control smart-link-taxonomy',
'tooltip' => 'mt3s.smart_links.smart_links.taxonomy.tooltip',
],
'constraints' => [new NotBlank(message: 'mt3s.smart_links.smart_links.error.taxonomy_required')],
]);
// -- UTM parameters ------------------------------------------------------------
// One fieldset per taxonomy, one select per parameter the taxonomy defines: the choices
// are the values the taxonomy allows. All the fieldsets are rendered at once;
// Mautic's data-show-on switcher (form.vars.smart_link_utm_fieldsets) shows the one of
// the chosen taxonomy, and the SUBMIT listener below drops the values of the others.
$builder->add('utmParameters', FormType::class, [
'label' => false,
'constraints' => [new Callback(callback: $this->validateUtmParameters(...))],
]);
$taxonomies = $this->getFormTaxonomies($smartLink);
foreach ($taxonomies as $taxonomy) {
// The dropdown parameters the taxonomy limits: a select with its subset as choices.
foreach ($this->getTaxonomyParameterKeys($taxonomy) as $key) {
$builder->get('utmParameters')->add(
self::fieldsetChildName($taxonomy, $key),
ChoiceType::class,
$this->buildTaxonomyFieldOptions($taxonomy, $key, $smartLink)
);
}
}
// The stored values (parameter key => value) feed the fieldset children
// (t<taxonomyId>_<key>): every select shows what the link already carries.
$builder->get('utmParameters')->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($taxonomies): void {
$stored = is_array($event->getData()) ? $event->getData() : [];
$expanded = [];
foreach ($taxonomies as $taxonomy) {
foreach ($this->getTaxonomyFieldsetKeys($taxonomy) as $key) {
$expanded[self::fieldsetChildName($taxonomy, $key)] = (string) ($stored[$key] ?? '');
}
}
$event->setData($expanded);
});
// Back to the stored shape: only the fieldset of the chosen taxonomy survives,
// stripped of its prefix, without the empty values, keys in display order.
$builder->get('utmParameters')->addEventListener(FormEvents::SUBMIT, function (FormEvent $event): void {
$data = $event->getData();
if (!is_array($data)) {
$event->setData([]);
return;
}
$taxonomy = $this->submittedTaxonomy($event->getForm());
$flat = [];
if (null !== $taxonomy) {
$prefix = self::fieldsetPrefix($taxonomy);
foreach ($data as $name => $value) {
if (\is_string($value) && '' !== trim($value) && str_starts_with((string) $name, $prefix)) {
$flat[substr((string) $name, \strlen($prefix))] = trim($value);
}
}
}
ksort($flat);
$event->setData($flat);
});
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($isSaved): void {
$data = $event->getData();
if (!is_array($data)) {
return;
}
$type = SmartLinkRedirectType::tryFrom((string) ($data['redirectType'] ?? ''));
// The URL only exists for external redirects; the Mautic destination only for
// Mautic ones. Drop whatever doesn't apply before the form is processed.
if (null === $type || $type->isMautic()) {
unset($data['destinationUrl']);
} else {
unset($data['destination']);
}
// Never accept a modified slug from a stale form (the field is disabled on edit).
if ($isSaved && \array_key_exists('slug', $data)) {
unset($data['slug']);
}
$event->setData($data);
});
// The unmapped "destination" choice becomes the page or the form of the link.
$builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event): void {
$link = $event->getData();
$form = $event->getForm();
$value = $form->has('destination') ? $form->get('destination')->getData() : null;
if (!$link instanceof SmartLink) {
return;
}
[$kind, $id] = false !== strpos((string) $value, ':') ? explode(':', (string) $value, 2) : [null, null];
$page = 'page' === $kind && null !== $id ? $this->getPageRepository()->find($id) : null;
$form = 'form' === $kind && null !== $id ? $this->getFormRepository()->find($id) : null;
$link->setPage($page instanceof Page ? $page : null);
$link->setForm($form instanceof MauticForm ? $form : null);
});
$builder->add('buttons', FormButtonsType::class);
if (!empty($options['action'])) {
$builder->setAction($options['action']);
}
}
/**
* The taxonomies rendered on the form: the published ones, plus the taxonomy the link
* carries even when it is no longer published (so an old link stays editable).
*
* @return list<UtmTaxonomy>
*/
private function getFormTaxonomies(SmartLink $smartLink): array
{
$taxonomies = $this->getTaxonomyRepository()->findBy(['isPublished' => true], ['name' => 'ASC']);
$stored = $smartLink->getTaxonomy();
if (null !== $stored && !\in_array($stored, $taxonomies, true)) {
$taxonomies[] = $stored;
}
return $taxonomies;
}
/**
* The parameter keys a taxonomy offers on the Smart Link form: the ones it defines values
* for and that are still enabled in Smart Links Settings.
*
* @return list<string>
*/
private function getTaxonomyParameterKeys(UtmTaxonomy $taxonomy): array
{
return array_values(array_intersect(
$taxonomy->getParameterKeys(),
array_keys($this->utmConfiguration->getEnabledParameters())
));
}
/**
* The choices of the taxonomy select: the published taxonomies (label = name), plus the
* taxonomy the link carries even when it is no longer published.
*
* @return array<string, UtmTaxonomy>
*/
private function buildTaxonomyChoices(SmartLink $smartLink): array
{
$choices = [];
foreach ($this->getFormTaxonomies($smartLink) as $taxonomy) {
$label = (string) $taxonomy->getName();
if (!$taxonomy->isPublished()) {
$label = $this->translator->trans('mt3s.smart_links.taxonomies.unpublished_choice', ['%name%' => $label]);
}
$choices[$label] = $taxonomy;
}
return $choices;
}
/**
* One UTM parameter select of a taxonomy fieldset: the choices are the values the taxonomy
* allows. A stored value outside the list stays selectable, labelled "(not in taxonomy)",
* so an old link is still editable (it is rejected on save by SmartLinkValidator).
*
* @return array<string, mixed>
*/
private function buildTaxonomyFieldOptions(UtmTaxonomy $taxonomy, string $key, SmartLink $smartLink): array
{
$choices = [];
foreach ($taxonomy->getParameterValues($key) as $row) {
$choices[$row['label']] = $row['value'];
}
$stored = (string) ($smartLink->getUtmParameters()[$key] ?? '');
if ('' !== $stored && !\in_array($stored, $choices, true)) {
$choices = [
$this->translator->trans('mt3s.smart_links.form.legacy_choice', ['%value%' => $stored]) => $stored,
] + $choices;
}
$parameter = $this->utmConfiguration->getParameter($key);
return [
'label' => (string) ($parameter['label'] ?? $key),
'required' => false,
'choices' => $choices,
'placeholder' => 'mt3s.smart_links.form.choose',
'attr' => ['class' => 'form-control smart-link-utm'],
];
}
/**
* The keys of one taxonomy fieldset: the dropdown parameters the taxonomy limits plus the
* parameters the admin left free, in display order.
*
* @return list<string>
*/
private function getTaxonomyFieldsetKeys(UtmTaxonomy $taxonomy): array
{
return $this->getTaxonomyParameterKeys($taxonomy);
}
/**
* The prefix of the utmParameters children of one taxonomy fieldset: t<taxonomyId>_.
*/
private static function fieldsetPrefix(UtmTaxonomy $taxonomy): string
{
return 't'.(string) $taxonomy->getId().'_';
}
private static function fieldsetChildName(UtmTaxonomy $taxonomy, string $key): string
{
return self::fieldsetPrefix($taxonomy).$key;
}
/**
* The submitted taxonomy of the form (null when none was chosen).
*/
private function submittedTaxonomy(FormInterface $utmParameters): ?UtmTaxonomy
{
$taxonomy = $utmParameters->getParent()?->get('taxonomy')->getData();
return $taxonomy instanceof UtmTaxonomy ? $taxonomy : null;
}
private function getTaxonomyRepository(): EntityRepository
{
$repository = $this->entityManager->getRepository(UtmTaxonomy::class);
\assert($repository instanceof EntityRepository);
return $repository;
}
public function buildView(FormView $view, FormInterface $form, array $options): void
{
/** @var SmartLink $smartLink */
$smartLink = $form->getData();
$view->vars['smart_link_domain'] = $this->shortUrlBuilder->getShortLinkDomain();
$view->vars['smart_link_is_saved'] = null !== $smartLink->getId();
$view->vars['smart_link_slug'] = (string) ($smartLink->getSlug() ?? '');
$view->vars['smart_link_preview'] = $this->shortUrlBuilder->buildShortUrl($smartLink);
$view->vars['smart_link_separator'] = $this->utmConfiguration->getSeparatorReplacement();
$view->vars['smart_link_lowercase'] = $this->utmConfiguration->isLowercaseEnforced();
// Slug proposed by the "Generate" button; the empty "new" form starts with one.
$view->vars['smart_link_generated'] = null === $smartLink->getId() ? $this->smartLinkModel->generateSlug() : '';
// One rendered fieldset per taxonomy: the template wraps each in a data-show-on container
// keyed by the taxonomy select, so Mautic's switcher shows the chosen one.
$view->vars['smart_link_utm_fieldsets'] = [];
foreach ($this->getFormTaxonomies($smartLink) as $taxonomy) {
$view->vars['smart_link_utm_fieldsets'][(string) $taxonomy->getId()] = [
'id' => (string) $taxonomy->getId(),
'name' => (string) $taxonomy->getName(),
'prefix' => self::fieldsetPrefix($taxonomy),
'keys' => $this->getTaxonomyFieldsetKeys($taxonomy),
];
}
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(['data_class' => SmartLink::class]);
}
public function getBlockPrefix(): string
{
return 'smartlinks_smart_link';
}
private function separator(): string
{
return $this->utmConfiguration->getSeparatorReplacement();
}
/**
* The repositories of the Mautic destinations, resolved lazily (the entity manager is
* injected once; the repositories are cheap Doctrine lookups).
*/
private function getPageRepository(): EntityRepository
{
$repository = $this->entityManager->getRepository(Page::class);
\assert($repository instanceof EntityRepository);
return $repository;
}
private function getFormRepository(): EntityRepository
{
$repository = $this->entityManager->getRepository(MauticForm::class);
\assert($repository instanceof EntityRepository);
return $repository;
}
private function validateSlug(mixed $slug, ExecutionContextInterface $context): void
{
/** @var SmartLink $smartLink */
$smartLink = $context->getRoot()->getData();
if (!$smartLink instanceof SmartLink) {
return;
}
$this->addViolations($context, $this->validator->validateSlug(
$this->normalizeSlug((string) $slug),
$smartLink->getId()
));
}
private function validateDestination(mixed $url, ExecutionContextInterface $context): void
{
/** @var SmartLink $smartLink */
$smartLink = $context->getRoot()->getData();
if (!$smartLink instanceof SmartLink) {
return;
}
$this->addViolations($context, $this->validator->validateDestination(
$smartLink->getRedirectType(),
is_string($url) ? $url : null,
$smartLink->getPage(),
$smartLink->getForm()
));
}
/**
* The published landing pages and standalone forms of the instance, grouped, with the
* link's current destination preselected. Only activated (published) ones are offered.
*
* @return array<string, string>
*/
private function buildMauticDestinationChoices(SmartLink $smartLink): array
{
$choices = [];
$values = [];
$pages = $this->getPageRepository()->findBy(['isPublished' => true], ['title' => 'ASC']);
foreach ($pages as $page) {
$value = 'page:'.$page->getId();
$choices['mt3s.smart_links.smart_links.destination.pages'][$page->getTitle()] = $value;
$values[] = $value;
}
$forms = $this->getFormRepository()->findBy(['isPublished' => true], ['name' => 'ASC']);
foreach ($forms as $form) {
$value = 'form:'.$form->getId();
$choices['mt3s.smart_links.smart_links.destination.forms'][$form->getName()] = $value;
$values[] = $value;
}
// A stored destination that is no longer published stays selectable, so an old link
// is still editable (it 404s until the page or the form is activated again). The
// guard must skip the "no destination" case: a null choice would make Symfony fall
// back to index-based values for every option.
$current = $this->currentMauticDestination($smartLink);
if (null !== $current && !in_array($current, $values, true)) {
$label = $smartLink->getPage()?->getTitle() ?? $smartLink->getForm()?->getName() ?? '';
$choices['mt3s.smart_links.smart_links.destination.unpublished'][$label] = $current;
}
return $choices;
}
/**
* The value of the unmapped destination field for the link's current page or form.
*/
private function currentMauticDestination(SmartLink $smartLink): ?string
{
if (null !== $smartLink->getPage()) {
return 'page:'.$smartLink->getPage()->getId();
}
if (null !== $smartLink->getForm()) {
return 'form:'.$smartLink->getForm()->getId();
}
return null;
}
/**
* Applies the UTM Manager settings to a typed slug, the same way the model will on save,
* so the uniqueness check compares the final slug.
*/
private function normalizeSlug(string $slug): string
{
$slug = str_replace(' ', $this->separator(), trim($slug));
if ($this->utmConfiguration->isLowercaseEnforced()) {
$slug = mb_strtolower($slug);
}
return $slug;
}
/**
* Runs SmartLinkValidator::validateUtmParameters() on the submitted values: against the
* chosen taxonomy, and with the values the link carried before the edit as allowed extras
* (a stored value outside the list can be saved unchanged: it was chosen when the list
* allowed it, and a plain re-save must never error).
*/
private function validateUtmParameters(mixed $values, ExecutionContextInterface $context): void
{
$form = $context->getObject();
if (!$form instanceof FormInterface) {
return;
}
// The model rebuilds the values (lowercase, filtered) in saveEntity(); the form hands
// the raw array: keys the user left empty are removed before validating.
$submitted = [];
foreach (is_array($values) ? $values : [] as $key => $value) {
if (\is_string($value) && '' !== trim($value)) {
$submitted[(string) $key] = trim($value);
}
}
$this->addViolations($context, $this->validator->validateUtmParameters(
$submitted,
$this->submittedTaxonomy($form),
$this->originalUtmParameters
));
}
/**
* @param list<array{0: string, 1: array<string, string>}> $errors
*/
private function addViolations(ExecutionContextInterface $context, array $errors): void
{
foreach ($errors as [$key, $parameters]) {
$context->buildViolation($key)->setParameters($parameters)->addViolation();
}
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Type;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationProvider;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* The single "Smart Links Settings" tab of Settings > Configuration: the general UTM rules and
* the short link domain (section "UTM Settings"), the catalog and custom parameters (section
* "Parameters"). Each child is a local.php parameter.
*/
final class SmartLinksConfigType extends AbstractType
{
/** Stored in local.php under this key (an array: short_link_domain => domain). */
public const CONFIG_PARAMETER = 'mt3s_smart_links_config';
/** Key of the standalone SmartlinksBundle era (0.1.0–0.18.0); still honored until the domain is saved again. */
public const LEGACY_SMARTLINKS_PARAMETER = 'smartlinks_config';
/** Key of the UtmManagerBundle era (< 0.5.0); still honored until the domain is saved again. */
public const LEGACY_CONFIG_PARAMETER = 'utm_manager_smart_links';
public function buildForm(FormBuilderInterface $builder, array $options): void
{
// The general rules and the parameters: read everywhere through UtmConfigurationProvider.
$builder->add(UtmConfigurationProvider::CONFIG_PARAMETER, SmartlinksSettingsType::class);
$builder->add(self::CONFIG_PARAMETER, FormType::class, ['label' => false]);
$builder->get(self::CONFIG_PARAMETER)->add('short_link_domain', TextType::class, [
'label' => 'mt3s.smart_links.settings.short_link_domain',
'required' => false,
'attr' => [
'class' => 'form-control',
'tooltip' => 'mt3s.smart_links.settings.short_link_domain.tooltip',
],
]);
}
public function getBlockPrefix(): string
{
// The Configuration tab title key: mautic.config.tab.smartlinksconfig.
return 'smartlinksconfig';
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Type;
use Mautic\CoreBundle\Form\Type\YesNoButtonGroupType;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterCatalog;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterMode;
use MauticPlugin\MT3SMarketingProgramBundle\Form\DataTransformer\UtmSettingsTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* The `mt3s_smart_links_utm_config` parameter: general settings, catalog parameters and custom parameters.
*/
final class SmartlinksSettingsType extends AbstractType
{
public function __construct(
private readonly UtmParameterCatalog $catalog,
private readonly UtmSettingsTransformer $transformer,
) {
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('enforce_lowercase', YesNoButtonGroupType::class, [
'label' => 'mt3s.smart_links.config.enforce_lowercase',
'attr' => ['tooltip' => 'mt3s.smart_links.config.enforce_lowercase.tooltip'],
]);
$builder->add('separator_replacement', ChoiceType::class, [
'label' => 'mt3s.smart_links.config.separator_replacement',
'choices' => [
'mt3s.smart_links.config.separator.hyphen' => '-',
'mt3s.smart_links.config.separator.underscore' => '_',
'mt3s.smart_links.config.separator.dot' => '.',
],
'placeholder' => false,
'attr' => [
'class' => 'form-control',
'tooltip' => 'mt3s.smart_links.config.separator_replacement.tooltip',
],
'invalid_message' => 'mt3s.smart_links.config.error.separator_invalid',
]);
$parameters = $builder->create('parameters', FormType::class, ['label' => false]);
foreach ($this->catalog->all() as $key => $definition) {
$parameters->add($key, UtmParameterType::class, ['definition' => $definition]);
}
$builder->add($parameters);
$builder->add('custom_parameters', CollectionType::class, [
'label' => false,
'entry_type' => UtmParameterType::class,
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'prototype_name' => '__param__',
'prototype_data' => [
'key' => '',
'enabled' => true,
'label' => '',
'mode' => UtmParameterMode::FREE,
'values' => [],
],
'by_reference' => false,
'error_bubbling' => false,
'required' => false,
]);
$builder->addModelTransformer($this->transformer);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(['label' => false]);
}
public function getBlockPrefix(): string
{
return 'mt3s_smart_links_utm_settings';
}
}
+2 -4
View File
@@ -4,10 +4,10 @@ declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Type; namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Type;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\Stakeholder;
use MauticPlugin\MT3SMarketingProgramBundle\Service\ItemTypeProvider;
use Mautic\CoreBundle\Form\Type\FormButtonsType; use Mautic\CoreBundle\Form\Type\FormButtonsType;
use Mautic\CoreBundle\Form\Type\YesNoButtonGroupType; use Mautic\CoreBundle\Form\Type\YesNoButtonGroupType;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\Stakeholder;
use MauticPlugin\MT3SMarketingProgramBundle\Service\ItemTypeProvider;
use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\EmailType; use Symfony\Component\Form\Extension\Core\Type\EmailType;
@@ -18,8 +18,6 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
/** /**
* The create and edit form of a stakeholder of the global directory (Programs > Stakeholders). * The create and edit form of a stakeholder of the global directory (Programs > Stakeholders).
*
* @extends AbstractType<Stakeholder>
*/ */
class StakeholderType extends AbstractType class StakeholderType extends AbstractType
{ {
-2
View File
@@ -20,8 +20,6 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
* One row of the dependencies collection in TaskType: the task this one depends on, and the type of * One row of the dependencies collection in TaskType: the task this one depends on, and the type of
* the relation. Only the tasks of the same program are offered; cycles and self-edges are refused by * the relation. Only the tasks of the same program are offered; cycles and self-edges are refused by
* ValidTaskDependency. * ValidTaskDependency.
*
* @extends AbstractType<TaskDependency>
*/ */
class TaskDependencyType extends AbstractType class TaskDependencyType extends AbstractType
{ {
-2
View File
@@ -19,8 +19,6 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
/** /**
* One row of the RACI collection in TaskType: a role (R/A/C/I) and the stakeholders carrying it. * One row of the RACI collection in TaskType: a role (R/A/C/I) and the stakeholders carrying it.
* The stakeholders are picked from the program's assigned stakeholders; several may share a role. * The stakeholders are picked from the program's assigned stakeholders; several may share a role.
*
* @extends AbstractType<TaskRaci>
*/ */
class TaskRaciType extends AbstractType class TaskRaciType extends AbstractType
{ {
+1 -3
View File
@@ -30,8 +30,6 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
* Kind rules: a milestone's end date is enslaved to its start date (the entity's setTaskKind copies * Kind rules: a milestone's end date is enslaved to its start date (the entity's setTaskKind copies
* the start onto the end, and the TaskDates validator keeps it in step); a phase has no status * the start onto the end, and the TaskDates validator keeps it in step); a phase has no status
* field — its state comes from its tasks. * field — its state comes from its tasks.
*
* @extends AbstractType<Task>
*/ */
class TaskType extends AbstractType class TaskType extends AbstractType
{ {
@@ -45,7 +43,7 @@ class TaskType extends AbstractType
$builder->addEventSubscriber(new CleanFormSubscriber(['description' => 'strict_html'])); $builder->addEventSubscriber(new CleanFormSubscriber(['description' => 'strict_html']));
/** @var Task $task */ /** @var Task $task */
$task = $options['data']; $task = $options['data'];
$program = $task->getProgram(); $program = $task->getProgram();
$kind = ItemTypeProvider::KIND_TASK; $kind = ItemTypeProvider::KIND_TASK;
+217
View File
@@ -0,0 +1,217 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Type;
use Mautic\CoreBundle\Form\Type\YesNoButtonGroupType;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterCatalog;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterDefinition;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterMode;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Validator\UtmSettingsValidator;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Regex;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* One parameter row: a catalog entry (option `definition`) or a custom parameter (`definition` = null).
*/
final class UtmParameterType extends AbstractType
{
public function __construct(
private readonly UtmSettingsValidator $validator,
private readonly TranslatorInterface $translator,
) {
}
/**
* Labels are written to local.php, where "%" would be read as a container parameter.
*
* @return Constraint[]
*/
public static function labelConstraints(): array
{
return [
new NotBlank(message: 'mt3s.smart_links.config.error.label_required'),
new Length(max: UtmSettingsValidator::MAX_LENGTH, maxMessage: 'mt3s.smart_links.config.error.label_length'),
new Regex(pattern: '/%/', match: false, message: 'mt3s.smart_links.config.error.label_invalid'),
];
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
/** @var UtmParameterDefinition|null $definition */
$definition = $options['definition'];
$allowedModes = $definition?->getAllowedModes() ?? UtmParameterMode::ALL;
if (null === $definition) {
$builder->add('key', TextType::class, [
'label' => 'mt3s.smart_links.config.parameter.key',
'attr' => [
'class' => 'form-control utm-custom-key',
'tooltip' => 'mt3s.smart_links.config.parameter.key.tooltip',
'maxlength' => 41,
],
'constraints' => [
new NotBlank(message: 'mt3s.smart_links.config.error.key_required'),
new Callback(callback: $this->validateCustomKey(...)),
],
]);
}
$builder->add('enabled', YesNoButtonGroupType::class, [
'label' => 'mt3s.smart_links.config.parameter.enabled',
]);
$builder->add('label', TextType::class, [
'label' => 'mt3s.smart_links.config.parameter.label',
'attr' => ['class' => 'form-control', 'maxlength' => UtmSettingsValidator::MAX_LENGTH],
'constraints' => self::labelConstraints(),
]);
$modeAttr = ['class' => 'form-control utm-mode'];
if ($definition?->autoGenerated) {
$modeAttr['tooltip'] = 'mt3s.smart_links.config.auto_generated.tooltip';
}
$builder->add('mode', ChoiceType::class, [
'label' => 'mt3s.smart_links.config.parameter.mode',
'choices' => array_combine(
array_map(fn (string $mode): string => 'mt3s.smart_links.config.mode.'.$mode, $allowedModes),
$allowedModes
),
'placeholder' => false,
'attr' => $modeAttr,
'invalid_message' => 'mt3s.smart_links.config.error.mode_invalid',
'constraints' => [new NotBlank(message: 'mt3s.smart_links.config.error.mode_invalid')],
]);
// Values only exist in dropdown mode: drop anything submitted for other modes (or for parameters
// that can't be dropdowns) before it is processed.
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event): void {
$data = $event->getData();
if (is_array($data) && (UtmParameterMode::DROPDOWN !== ($data['mode'] ?? null) || !$event->getForm()->has('values'))) {
unset($data['values']);
$event->setData($data);
}
});
if (!in_array(UtmParameterMode::DROPDOWN, $allowedModes, true)) {
return;
}
$builder->add('values', CollectionType::class, [
'label' => false,
'entry_type' => UtmValueType::class,
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'prototype_name' => '__value__',
'by_reference' => false,
'error_bubbling' => false,
'required' => false,
'constraints' => [new Callback(callback: $this->validateValueList(...))],
]);
}
public function buildView(FormView $view, FormInterface $form, array $options): void
{
/** @var UtmParameterDefinition|null $definition */
$definition = $options['definition'];
$view->vars['utm_custom'] = null === $definition;
$view->vars['utm_key'] = $definition?->key;
$view->vars['utm_group'] = $definition->group ?? UtmParameterCatalog::GROUP_CUSTOM;
$view->vars['utm_description_key'] = $definition?->getDescriptionKey();
$view->vars['utm_auto_generated'] = $definition->autoGenerated ?? false;
$view->vars['utm_suggestions'] = array_map(
fn (string $value): array => [
'value' => $value,
'label' => $this->translator->trans(UtmParameterDefinition::getSuggestionLabelKey($value)),
],
$definition->suggestions ?? []
);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'definition' => null,
'label' => false,
]);
$resolver->setAllowedTypes('definition', ['null', UtmParameterDefinition::class]);
}
public function getBlockPrefix(): string
{
return 'utm_parameter';
}
private function validateCustomKey(mixed $key, ExecutionContextInterface $context): void
{
$key = (string) $key;
if ('' === $key) {
return;
}
$errors = $this->validator->validateCustomKey($key);
$keyForm = $context->getObject();
$collection = $keyForm instanceof FormInterface ? $keyForm->getParent()?->getParent() : null;
if ([] === $errors && null !== $collection) {
$keys = [];
foreach ($collection as $parameterForm) {
if ($parameterForm->has('key')) {
$keys[] = (string) $parameterForm->get('key')->getData();
}
}
$errors = $this->validator->validateKeyIsUnique($key, $keys);
}
$this->addViolations($context, $errors);
}
private function validateValueList(mixed $values, ExecutionContextInterface $context): void
{
$valuesForm = $context->getObject();
$parameter = $valuesForm instanceof FormInterface ? $valuesForm->getParent() : null;
if (null === $parameter) {
return;
}
$errors = $this->validator->validateValueList(
(string) $parameter->get('mode')->getData(),
(bool) $parameter->get('enabled')->getData(),
array_values(is_array($values) ? $values : [])
);
$this->addViolations($context, $errors);
}
/**
* @param list<array{0: string, 1: array<string, string>}> $errors
*/
private function addViolations(ExecutionContextInterface $context, array $errors): void
{
foreach ($errors as [$message, $parameters]) {
$context->buildViolation($message)
->setParameters($parameters)
->setTranslationDomain('validators')
->addViolation();
}
}
}
+365
View File
@@ -0,0 +1,365 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Type;
use Mautic\CoreBundle\Form\Type\FormButtonsType;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterMode;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\UtmTaxonomy;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Validator\UtmTaxonomyValidator;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationProvider;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* Create / edit a UTM Taxonomy.
*
* Every parameter enabled in Smart Links Settings appears, exactly as the admin defined it:
* a `dropdown` parameter offers its admin-configured values as a checkbox list (a subset
* selection -- nothing can be typed), and a `free` parameter gets its own editable value
* list here (one `value` or `value;Label` per line): a Smart Link using this taxonomy picks
* a value from it instead of typing freely.
*/
final class UtmTaxonomyType extends AbstractType
{
public function __construct(
private readonly UtmConfigurationProvider $utmConfiguration,
private readonly UtmTaxonomyValidator $validator,
) {
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('name', TextType::class, [
'label' => 'mt3s.smart_links.taxonomies.name',
'required' => true,
'attr' => [
'class' => 'form-control',
'maxlength' => UtmTaxonomy::NAME_MAX_LENGTH,
'tooltip' => 'mt3s.smart_links.taxonomies.name.tooltip',
],
'constraints' => [
new NotBlank(message: 'mt3s.smart_links.taxonomies.error.name_required'),
new Length(max: UtmTaxonomy::NAME_MAX_LENGTH, maxMessage: 'mt3s.smart_links.taxonomies.error.name_length'),
new Callback(callback: $this->validateName(...)),
],
]);
$builder->add('description', TextareaType::class, [
'label' => 'mt3s.smart_links.taxonomies.description',
'required' => false,
'attr' => [
'class' => 'form-control',
'tooltip' => 'mt3s.smart_links.taxonomies.description.tooltip',
'rows' => 3,
],
]);
$this->buildParameters($builder);
$builder->add('buttons', FormButtonsType::class);
if (!empty($options['action'])) {
$builder->setAction($options['action']);
}
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => UtmTaxonomy::class,
]);
}
public function getBlockPrefix(): string
{
return 'smartlinks_utm_taxonomy';
}
/**
* The values section: one field per enabled parameter. Dropdown parameters offer the
* admin's values as checkboxes; free ones get an editable textarea (one value per line).
* A transformer maps the children shapes to the stored rows, and the textarea lines are
* validated on POST_SUBMIT (pattern, duplicates).
*/
private function buildParameters(FormBuilderInterface $builder): void
{
$builder->add('parameters', FormType::class, [
'label' => false,
'error_bubbling' => false,
]);
$dropdowns = $this->getDropdownParameters();
$frees = $this->getFreeParameterKeys();
foreach ($this->utmConfiguration->getEnabledParameters() as $key => $parameter) {
if (isset($dropdowns[$key])) {
$attr = ['class' => 'utm-taxonomy-values'];
if ([] === $dropdowns[$key]) {
$attr['tooltip'] = 'mt3s.smart_links.taxonomies.no_values.tooltip';
}
$builder->get('parameters')->add($key, ChoiceType::class, [
'label' => (string) $parameter['label'],
'required' => false,
'multiple' => true,
'expanded' => true,
'choices' => array_flip($dropdowns[$key]),
'attr' => $attr,
]);
continue;
}
if (in_array($key, $frees, true)) {
$builder->get('parameters')->add($key, TextareaType::class, [
'label' => (string) $parameter['label'],
'required' => false,
'attr' => [
'class' => 'form-control utm-taxonomy-free-values',
'rows' => 2,
'tooltip' => 'mt3s.smart_links.taxonomies.free_values.tooltip',
'placeholder' => 'mt3s.smart_links.taxonomies.free_values.placeholder',
],
]);
}
}
$builder->get('parameters')->addModelTransformer(new CallbackTransformer(
fn (mixed $rows): array => $this->rowsToChildren($rows, $dropdowns, $frees),
fn (mixed $children): array => $this->childrenToRows($children, $dropdowns, $frees),
));
$builder->get('parameters')->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($frees): void {
$form = $event->getForm();
foreach ($frees as $key) {
if (!$form->has($key)) {
continue;
}
$rows = $this->parseTextarea((string) $form->get($key)->getData());
$this->addErrorsOn($form->get($key), $this->validator->validateValues($rows));
}
});
}
/**
* The admin's dropdown parameters: key => [value => label].
*
* @return array<string, array<string, string>>
*/
private function getDropdownParameters(): array
{
$dropdowns = [];
foreach ($this->utmConfiguration->getEnabledParameters() as $key => $parameter) {
if (UtmParameterMode::DROPDOWN !== $parameter['mode']) {
continue;
}
// Present even when the admin hasn't configured values yet: the parameter stays
// visible on the form (an empty checkbox list), mirroring the settings.
$dropdowns[$key] = [];
foreach ($this->utmConfiguration->getDropdownValues($key) as $row) {
$dropdowns[$key][$row['value']] = $row['label'];
}
}
return $dropdowns;
}
/**
* The parameters the admin left free text: they get an editable value list here.
*
* @return list<string>
*/
private function getFreeParameterKeys(): array
{
$free = [];
foreach ($this->utmConfiguration->getEnabledParameters() as $key => $parameter) {
if (UtmParameterMode::FREE === $parameter['mode']) {
$free[] = $key;
}
}
return $free;
}
/**
* The stored rows become the children data: checkbox arrays for dropdowns (only the
* values the admin still configures stay checked), one-value-per-line text for the
* free ones (a `value;Label` line when the label differs from the value).
*
* @param array<string, array<string, string>> $dropdowns
* @param list<string> $frees
*
* @return array<string, mixed>
*/
private function rowsToChildren(mixed $rows, array $dropdowns, array $frees): array
{
$children = [];
foreach (array_keys($dropdowns) as $key) {
$children[$key] = [];
}
foreach ($frees as $key) {
$children[$key] = '';
}
foreach (is_array($rows) ? $rows : [] as $key => $list) {
if (!\is_array($list) || !\array_key_exists((string) $key, $children)) {
continue;
}
if (\is_array($children[$key])) {
$children[$key] = [];
} else {
$children[$key] = '';
}
$lines = [];
foreach ($list as $row) {
$value = \is_array($row) ? (string) ($row['value'] ?? '') : '';
if ('' === $value) {
continue;
}
if (isset($dropdowns[$key])) {
if (isset($dropdowns[$key][$value])) {
$children[$key][] = $value;
}
continue;
}
$label = \is_array($row) ? trim((string) ($row['label'] ?? '')) : '';
$lines[] = ('' !== $label && $label !== $value) ? $value.';'.$label : $value;
}
if (\is_string($children[$key])) {
$children[$key] = implode("\n", $lines);
}
}
return $children;
}
/**
* Back to the stored shape: checkbox arrays become rows with the admin's labels,
* textarea lines become rows (labels default to the value); empty lists drop the key.
*
* @param array<string, array<string, string>> $dropdowns
* @param list<string> $frees
*
* @return array<string, list<array{value: string, label: string}>>
*/
private function childrenToRows(mixed $children, array $dropdowns, array $frees): array
{
$rows = [];
foreach (is_array($children) ? $children : [] as $key => $data) {
if (isset($dropdowns[$key])) {
$clean = [];
foreach (\is_array($data) ? $data : [] as $value) {
$value = (string) $value;
if (isset($dropdowns[$key][$value]) && !isset($clean[$value])) {
$clean[$value] = ['value' => $value, 'label' => $dropdowns[$key][$value]];
}
}
if ([] !== $clean) {
$rows[$key] = array_values($clean);
}
continue;
}
if (!in_array((string) $key, $frees, true)) {
continue;
}
$clean = [];
foreach ($this->parseTextarea((string) $data) as [$value, $label]) {
if (!isset($clean[$value])) {
$clean[$value] = ['value' => $value, 'label' => '' !== $label ? $label : $value];
}
}
if ([] !== $clean) {
$rows[$key] = array_values($clean);
}
}
ksort($rows);
return $rows;
}
/**
* One value (or `value;Label`) per line.
*
* @return list<array{0: string, 1: string}>
*/
private function parseTextarea(string $text): array
{
$parsed = [];
foreach (preg_split('/\r?\n/', $text) ?: [] as $line) {
$line = trim($line);
if ('' === $line) {
continue;
}
$parts = explode(';', $line, 2);
$parsed[] = [trim($parts[0]), isset($parts[1]) ? trim($parts[1]) : ''];
}
return $parsed;
}
/**
* Runs UtmTaxonomyValidator::validateName() on the typed name, skipping the entity's own.
*/
private function validateName(mixed $name, ExecutionContextInterface $context): void
{
$name = trim((string) $name);
if ('' === $name) {
return;
}
/** @var FormInterface $form */
$form = $context->getObject();
$ignored = $form instanceof FormInterface && $form->getParent()?->getData() instanceof UtmTaxonomy
? $form->getParent()->getData()->getId()
: null;
$this->addErrorsOn($form, $this->validator->validateName($name, $ignored));
}
/**
* @param FormInterface|FormBuilderInterface $form
* @param list<array{0: string, 1: array<string, string>}> $errors
*/
private function addErrorsOn(object $form, array $errors): void
{
foreach ($errors as [$message, $parameters]) {
$form->addError(new FormError($message, null, $parameters));
}
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Type;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Validator\UtmSettingsValidator;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Regex;
/**
* One allowed value of a `dropdown` parameter.
*/
final class UtmValueType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('value', TextType::class, [
'label' => 'mt3s.smart_links.config.values.value',
'attr' => [
'class' => 'form-control utm-value-input',
'placeholder' => 'mt3s.smart_links.config.values.value',
'maxlength' => UtmSettingsValidator::MAX_LENGTH,
],
'constraints' => [
new NotBlank(message: 'mt3s.smart_links.config.error.value_required'),
new Length(max: UtmSettingsValidator::MAX_LENGTH, maxMessage: 'mt3s.smart_links.config.error.value_length'),
new Regex(pattern: UtmSettingsValidator::VALUE_PATTERN, message: 'mt3s.smart_links.config.error.value_invalid'),
],
]);
$builder->add('label', TextType::class, [
'label' => 'mt3s.smart_links.config.values.label',
'attr' => [
'class' => 'form-control utm-label-input',
'placeholder' => 'mt3s.smart_links.config.values.label',
'maxlength' => UtmSettingsValidator::MAX_LENGTH,
],
'constraints' => UtmParameterType::labelConstraints(),
]);
$builder->add('is_default', CheckboxType::class, [
'label' => 'mt3s.smart_links.config.values.default',
'required' => false,
'attr' => ['class' => 'utm-value-default'],
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(['label' => false]);
}
public function getBlockPrefix(): string
{
return 'utm_value';
}
}
+253
View File
@@ -0,0 +1,253 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterCatalog;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterMode;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationProvider;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Makes the native "UTM tags" subform (Email, Focus Item) follow the UTM Manager configuration.
*
* Per native field: `dropdown` replaces the text input with a select restricted to the configured values
* (plus the value already stored, if it isn't in the taxonomy), `free` keeps the native field,
* `disabled` (or not enabled) removes the field and stores null.
*
* Only the form is enforced: API and import write the entity directly.
*/
final class UtmFieldsApplicator
{
/**
* Native subform fields => configuration keys. utm_term has no native field and is left alone.
*/
public const FIELDS = [
'utmSource' => 'utm_source',
'utmMedium' => 'utm_medium',
'utmCampaign' => 'utm_campaign',
'utmContent' => 'utm_content',
];
/** Native options carried over to the select. */
private const KEPT_OPTIONS = ['label_attr', 'constraints', 'help', 'help_attr', 'help_html', 'help_translation_parameters'];
public function __construct(
private readonly UtmConfigurationProvider $configurationProvider,
private readonly UtmParameterCatalog $catalog,
private readonly TranslatorInterface $translator,
) {
}
public function apply(FormBuilderInterface $builder): void
{
// Fields are rebuilt once the stored values are known, to offer legacy values as choices.
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event): void {
$this->buildFields($event->getForm(), $event->getData());
});
// A value posted for a removed field would raise an "extra fields" error: drop it.
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event): void {
$data = $event->getData();
if (!is_array($data)) {
return;
}
foreach ($this->getDisabledFields() as $field) {
unset($data[$field]);
}
$event->setData($data);
});
// A removed field leaves its key untouched in the stored array: clear it so no stale value survives.
$builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event): void {
$data = $event->getData();
if (null !== $data && !is_array($data)) {
return;
}
$data ??= [];
foreach ($this->getDisabledFields() as $field) {
// null, as the native empty field: an empty string would add "utm_x=" to every link.
$data[$field] = null;
}
$event->setData($data);
});
}
/**
* @param FormInterface<mixed> $form
*/
private function buildFields(FormInterface $form, mixed $storedTags): void
{
$storedTags = is_array($storedTags) ? $storedTags : [];
$nativeOrder = array_keys($form->all());
foreach (self::FIELDS as $field => $key) {
if (!$form->has($field)) {
continue;
}
$parameter = $this->configurationProvider->getParameter($key);
if (null === $parameter) {
continue;
}
$mode = $this->getMode($parameter);
if (UtmParameterMode::DISABLED === $mode) {
$form->remove($field);
continue;
}
$label = $this->getCustomLabel($key, $parameter);
if (UtmParameterMode::DROPDOWN === $mode) {
$this->addDropdown($form, $field, $key, $label, $storedTags[$field] ?? null);
} elseif (null !== $label) {
$this->replaceField($form, $field, null, ['label' => $label]);
}
}
// A replaced field is appended last: re-append every field in core's order.
foreach ($nativeOrder as $name) {
if ($form->has($name)) {
$child = $form->get($name);
$form->remove($name);
$form->add($child);
}
}
}
/**
* @param FormInterface<mixed> $form
*/
private function addDropdown(FormInterface $form, string $field, string $key, ?string $label, mixed $stored): void
{
// A non-scalar value can't be shown in a select: keep the native field rather than lose it.
if (null !== $stored && !is_scalar($stored)) {
return;
}
// value => label, in configured order. Numeric values become int keys: compare as strings.
$labels = [];
foreach ($this->configurationProvider->getDropdownValues($key) as $row) {
$labels[(string) $row['value']] = (string) $row['label'];
}
$options = [];
$storedValue = null === $stored ? '' : (string) $stored;
if ('' !== $storedValue && !array_key_exists($storedValue, $labels)) {
// Legacy value: kept as the last choice so it displays and re-saves without data loss.
$labels[$storedValue] = $this->translator->trans('mt3s.smart_links.form.legacy_choice', ['%value%' => $storedValue]);
$options['help'] = 'mt3s.smart_links.form.legacy_warning';
$options['help_attr'] = ['class' => 'text-warning'];
} elseif ([] === $labels) {
$options['help'] = 'mt3s.smart_links.form.no_values';
$options['help_attr'] = ['class' => 'text-warning'];
}
$options += [
'choices' => array_map('strval', array_keys($labels)),
'choice_label' => static fn (string $value): string => $labels[$value],
// Configured labels are shown as typed. The placeholder is translated here for the same reason.
'choice_translation_domain' => false,
'placeholder' => $this->translator->trans('mt3s.smart_links.form.choose'),
'required' => false,
'multiple' => false,
'expanded' => false,
'attr' => ['class' => 'form-control'],
'invalid_message' => 'mt3s.smart_links.form.error.not_in_taxonomy',
];
if (null !== $label) {
$options['label'] = $label;
}
$this->replaceField($form, $field, ChoiceType::class, $options);
}
/**
* Re-adds a field with its native options (label, constraints...) overridden by $options.
*
* @param FormInterface<mixed> $form
* @param class-string|null $type null keeps the native type and all native options
* @param array<string, mixed> $options
*/
private function replaceField(FormInterface $form, string $field, ?string $type, array $options): void
{
$config = $form->get($field)->getConfig();
$native = $config->getOptions();
if (null === $type) {
$type = $config->getType()->getInnerType()::class;
$options = array_replace($this->getOverridableOptions($native), $options);
} else {
$kept = array_intersect_key($native, array_flip(self::KEPT_OPTIONS));
$kept += ['label' => $native['label'] ?? null];
// Our help (legacy warning, empty list) wins over the native one; otherwise keep the native help.
$options = array_replace($kept, $options);
}
$form->remove($field);
$form->add($field, $type, $options);
}
/**
* Native options a type accepts again when re-added (resolved-only options are excluded).
*
* @param array<string, mixed> $native
*
* @return array<string, mixed>
*/
private function getOverridableOptions(array $native): array
{
return array_intersect_key($native, array_flip(['label', 'label_attr', 'attr', 'required', 'constraints', 'help', 'help_attr', 'help_html']));
}
/**
* @param array<string, mixed> $parameter
*/
private function getMode(array $parameter): string
{
return $parameter['enabled'] ? (string) $parameter['mode'] : UtmParameterMode::DISABLED;
}
/**
* The configured label, or null when it is the catalog default (the native label is kept then).
*
* @param array<string, mixed> $parameter
*/
private function getCustomLabel(string $key, array $parameter): ?string
{
$label = (string) ($parameter['label'] ?? '');
$definition = $this->catalog->get($key);
if ('' === $label || (null !== $definition && $label === $this->translator->trans($definition->getLabelKey()))) {
return null;
}
return $label;
}
/**
* @return list<string>
*/
private function getDisabledFields(): array
{
$disabled = [];
foreach (self::FIELDS as $field => $key) {
$parameter = $this->configurationProvider->getParameter($key);
if (null !== $parameter && UtmParameterMode::DISABLED === $this->getMode($parameter)) {
$disabled[] = $field;
}
}
return $disabled;
}
}
+177
View File
@@ -0,0 +1,177 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Validator;
use Mautic\FormBundle\Entity\Form;
use Mautic\PageBundle\Entity\Page;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\SmartLinkRedirectType;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterMode;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\UtmTaxonomy;
use MauticPlugin\MT3SMarketingProgramBundle\Model\SmartLinkModel;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationProvider;
/**
* Business rules of the Smart Link form. The form type calls these methods from Callback
* constraints; each method returns translation keys (validators domain) and parameters.
*/
final class SmartLinkValidator
{
public const ERROR_SLUG_TAKEN = 'mt3s.smart_links.smart_links.error.slug_taken';
public const ERROR_SLUG_REQUIRED = 'mt3s.smart_links.smart_links.error.slug_required';
public const ERROR_SLUG_LENGTH = 'mt3s.smart_links.smart_links.error.slug_length';
public const ERROR_DESTINATION_REQUIRED = 'mt3s.smart_links.smart_links.error.destination_required';
public const ERROR_DESTINATION_REQUIRED_MAUTIC = 'mt3s.smart_links.smart_links.error.destination_required_mautic';
public const ERROR_DESTINATION_INVALID = 'mt3s.smart_links.smart_links.error.destination_invalid';
public const ERROR_UTM_VALUE_INVALID = 'mt3s.smart_links.smart_links.error.utm_value_invalid';
public const ERROR_UTM_VALUE_NOT_ALLOWED = 'mt3s.smart_links.smart_links.error.utm_value_not_allowed';
public const ERROR_TAXONOMY_PARAMETER_UNKNOWN = 'mt3s.smart_links.smart_links.error.taxonomy_parameter_unknown';
public function __construct(
private readonly SmartLinkModel $smartLinkModel,
private readonly UtmConfigurationProvider $utmConfiguration,
) {
}
/**
* Unique slug. The rules (lowercase, separator replacement) are applied by the model
* before this check, so the comparison uses the final slug.
*
* @return list<array{0: string, 1: array<string, string>}>
*/
public function validateSlug(string $slug, ?int $ignoreId = null): array
{
if ('' === $slug) {
return [[self::ERROR_SLUG_REQUIRED, []]];
}
if ($this->smartLinkModel->isSlugTaken($slug, $ignoreId)) {
return [[self::ERROR_SLUG_TAKEN, ['%slug%' => $slug]]];
}
return [];
}
/**
* A destination is required for every redirect type: an URL for external ones, a landing
* page or a standalone form for Mautic ones. Only http(s) URLs are accepted.
*
* @return list<array{0: string, 1: array<string, string>}>
*/
public function validateDestination(SmartLinkRedirectType $redirectType, ?string $url, ?Page $page = null, ?Form $form = null): array
{
if ($redirectType->isMautic()) {
if (null === $page && null === $form) {
return [[self::ERROR_DESTINATION_REQUIRED_MAUTIC, []]];
}
return [];
}
$url = trim((string) $url);
if ('' === $url) {
return [[self::ERROR_DESTINATION_REQUIRED, []]];
}
if (!filter_var($url, FILTER_VALIDATE_URL)
|| !in_array(parse_url($url, PHP_URL_SCHEME), ['http', 'https'], true)) {
return [[self::ERROR_DESTINATION_INVALID, ['%url%' => $url]]];
}
return [];
}
/**
* UTM values follow the Smart Links Settings the admin defines. With a taxonomy chosen:
* every parameter the taxonomy defines limits the value -- the checkbox subset of the
* admin's values for a dropdown, the taxonomy's own list for a free parameter. The
* values the link carried before the edit stay acceptable (they were chosen when the
* taxonomy — or, before the feature, the global configuration — allowed them), so a plain
* re-save never errors. Without a taxonomy (links that predate the feature, before their
* next edit), the values follow the rules of Smart Links Settings.
*
* @param array<string, string> $utmParameters
* @param array<string, string> $stored the values the link carried before the edit
*
* @return list<array{0: string, 1: array<string, string>}>
*/
public function validateUtmParameters(array $utmParameters, ?UtmTaxonomy $taxonomy = null, array $stored = []): array
{
if (null === $taxonomy) {
return $this->validateAgainstGlobalConfiguration($utmParameters, $stored);
}
$errors = [];
foreach ($utmParameters as $key => $value) {
$parameter = $this->utmConfiguration->getParameter($key);
if (null === $parameter || (!$parameter['enabled']) || UtmParameterMode::DISABLED === $parameter['mode']) {
$errors[] = [self::ERROR_UTM_VALUE_INVALID, ['%key%' => $key]];
continue;
}
// Every parameter of the taxonomy limits the value: a dropdown subset selected
// among the admin's values, or the taxonomy's own list for a free parameter.
$allowed = $taxonomy->getParameterValues($key);
if ([] === $allowed) {
$errors[] = [self::ERROR_TAXONOMY_PARAMETER_UNKNOWN, ['%key%' => $key, '%name%' => (string) $taxonomy->getName()]];
continue;
}
if (in_array($value, array_column($allowed, 'value'), true) || ($stored[$key] ?? null) === $value) {
continue;
}
$errors[] = [self::ERROR_UTM_VALUE_NOT_ALLOWED, ['%key%' => $key, '%value%' => $value]];
}
return $errors;
}
/**
* The rules of Smart Links Settings: the values belong to enabled parameters, respect the
* technical pattern, and dropdown values stay within the configured list — unless the link
* already carried them.
*
* @param array<string, string> $utmParameters
* @param array<string, string> $stored
*
* @return list<array{0: string, 1: array<string, string>}>
*/
private function validateAgainstGlobalConfiguration(array $utmParameters, array $stored): array
{
$valuePattern = UtmSettingsValidator::VALUE_PATTERN;
$errors = [];
foreach ($utmParameters as $key => $value) {
$parameter = $this->utmConfiguration->getParameter($key);
if (null === $parameter || (!$parameter['enabled']) || UtmParameterMode::DISABLED === $parameter['mode']) {
$errors[] = [self::ERROR_UTM_VALUE_INVALID, ['%key%' => $key]];
continue;
}
if (1 !== preg_match($valuePattern, $value)) {
$errors[] = [self::ERROR_UTM_VALUE_INVALID, ['%key%' => $key]];
continue;
}
$inList = UtmParameterMode::DROPDOWN !== $parameter['mode']
|| in_array($value, array_column($this->utmConfiguration->getDropdownValues($key), 'value'), true);
if (!$inList && ($stored[$key] ?? null) !== $value) {
$errors[] = [self::ERROR_UTM_VALUE_NOT_ALLOWED, ['%key%' => $key, '%value%' => $value]];
}
}
return $errors;
}
}
+100
View File
@@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Validator;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterCatalog;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterMode;
/**
* Business rules of the UTM Manager configuration form. The form types call these methods
* from Callback constraints; each method returns translation keys (validators domain) and parameters.
*/
final class UtmSettingsValidator
{
/** Technical value written in the URL: lowercase letters, digits, "-", "_" and ".". */
public const VALUE_PATTERN = '/^[a-z0-9._-]+$/';
public const MAX_LENGTH = 100;
public const ERROR_KEY_INVALID = 'mt3s.smart_links.config.error.key_invalid';
public const ERROR_KEY_RESERVED = 'mt3s.smart_links.config.error.key_reserved';
public const ERROR_KEY_DUPLICATE = 'mt3s.smart_links.config.error.key_duplicate';
public const ERROR_VALUES_REQUIRED = 'mt3s.smart_links.config.error.values_required';
public const ERROR_VALUE_DUPLICATE = 'mt3s.smart_links.config.error.value_duplicate';
public const ERROR_DEFAULT_MULTIPLE = 'mt3s.smart_links.config.error.default_multiple';
public function __construct(
private readonly UtmParameterCatalog $catalog,
) {
}
/**
* @return list<array{0: string, 1: array<string, string>}>
*/
public function validateCustomKey(string $key): array
{
if (1 !== preg_match(UtmParameterCatalog::CUSTOM_KEY_PATTERN, $key)) {
return [[self::ERROR_KEY_INVALID, ['%key%' => $key]]];
}
if ($this->catalog->isReservedKey($key)) {
return [[self::ERROR_KEY_RESERVED, ['%key%' => $key]]];
}
return [];
}
/**
* @param string[] $existingKeys All custom keys of the form, including $key itself
*
* @return list<array{0: string, 1: array<string, string>}>
*/
public function validateKeyIsUnique(string $key, array $existingKeys): array
{
$occurrences = count(array_filter($existingKeys, fn (string $other): bool => $other === $key));
return $occurrences > 1 ? [[self::ERROR_KEY_DUPLICATE, ['%key%' => $key]]] : [];
}
/**
* Rules that apply to the whole value list of a `dropdown` parameter. Nothing is checked
* for other modes: their values are never processed.
*
* @param array<array{value?: mixed, label?: mixed, is_default?: mixed}> $rows
*
* @return list<array{0: string, 1: array<string, string>}>
*/
public function validateValueList(string $mode, bool $enabled, array $rows): array
{
if (UtmParameterMode::DROPDOWN !== $mode) {
return [];
}
$errors = [];
if ($enabled && [] === $rows) {
$errors[] = [self::ERROR_VALUES_REQUIRED, []];
}
$seen = [];
foreach ($rows as $row) {
$value = (string) ($row['value'] ?? '');
if ('' === $value) {
continue;
}
if (isset($seen[$value]) && 1 === $seen[$value]) {
$errors[] = [self::ERROR_VALUE_DUPLICATE, ['%value%' => $value]];
}
$seen[$value] = ($seen[$value] ?? 0) + 1;
}
$defaults = array_filter($rows, fn (array $row): bool => !empty($row['is_default']));
if (count($defaults) > 1) {
$errors[] = [self::ERROR_DEFAULT_MULTIPLE, []];
}
return $errors;
}
}
+73
View File
@@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Validator;
use MauticPlugin\MT3SMarketingProgramBundle\Model\UtmTaxonomyModel;
/**
* Business rules of the UTM Taxonomy form. The form types call these methods from Callback
* constraints; each method returns translation keys (validators domain) and parameters.
*/
final class UtmTaxonomyValidator
{
public const ERROR_NAME_TAKEN = 'mt3s.smart_links.taxonomies.error.name_taken';
public const ERROR_NAME_CHARACTERS = 'mt3s.smart_links.taxonomies.error.name_characters';
public const ERROR_VALUE_INVALID = 'mt3s.smart_links.taxonomies.error.value_invalid';
public const ERROR_VALUE_DUPLICATE = 'mt3s.smart_links.config.error.value_duplicate';
public function __construct(
private readonly UtmTaxonomyModel $taxonomyModel,
) {
}
/**
* Unique, non-empty name. Free of the characters local.php can't carry ("%", "{", "}").
*
* @return list<array{0: string, 1: array<string, string>}>
*/
public function validateName(string $name, ?int $ignoreId = null): array
{
if (1 !== preg_match('/^[^%{}]+$/', $name)) {
return [[self::ERROR_NAME_CHARACTERS, []]];
}
if ($this->taxonomyModel->isNameTaken($name, $ignoreId)) {
return [[self::ERROR_NAME_TAKEN, ['%name%' => $name]]];
}
return [];
}
/**
* The value list of a `free` parameter (its editable textarea): every line must respect
* the technical pattern of the URL values, and duplicates are rejected.
*
* @param list<array{0: string, 1: string}> $parsed
*
* @return list<array{0: string, 1: array<string, string>}>
*/
public function validateValues(array $parsed): array
{
$errors = [];
$seen = [];
foreach ($parsed as [$value]) {
if ('' === $value) {
continue;
}
if (isset($seen[$value]) && 1 === $seen[$value]) {
$errors[] = [self::ERROR_VALUE_DUPLICATE, ['%value%' => $value]];
}
$seen[$value] = ($seen[$value] ?? 0) + 1;
if (1 !== preg_match(UtmSettingsValidator::VALUE_PATTERN, $value)) {
$errors[] = [self::ERROR_VALUE_INVALID, ['%value%' => $value]];
}
}
return $errors;
}
}
@@ -13,7 +13,7 @@ class MT3SMarketingProgramIntegration extends BasicIntegration implements BasicI
use ConfigurationTrait; use ConfigurationTrait;
public const NAME = 'MT3SMarketingProgram'; public const NAME = 'MT3SMarketingProgram';
public const DISPLAY_NAME = 'Marketing Programs'; public const DISPLAY_NAME = 'MT3S Marketing Program';
public function getName(): string public function getName(): string
{ {
+32
View File
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Integration;
use Mautic\IntegrationsBundle\Integration\BasicIntegration;
use Mautic\IntegrationsBundle\Integration\ConfigurationTrait;
use Mautic\IntegrationsBundle\Integration\Interfaces\BasicInterface;
class SmartlinksIntegration extends BasicIntegration implements BasicInterface
{
use ConfigurationTrait;
public const NAME = 'Smartlinks';
public const DISPLAY_NAME = 'Smart Links';
public function getName(): string
{
return self::NAME;
}
public function getDisplayName(): string
{
return self::DISPLAY_NAME;
}
public function getIcon(): string
{
return 'plugins/MT3SMarketingProgramBundle/Assets/img/smartlinks-icon.svg';
}
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Integration\Support;
use Mautic\IntegrationsBundle\Integration\DefaultConfigFormTrait;
use Mautic\IntegrationsBundle\Integration\Interfaces\ConfigFormInterface;
use MauticPlugin\MT3SMarketingProgramBundle\Integration\SmartlinksIntegration;
class SmartlinksConfigSupport extends SmartlinksIntegration implements ConfigFormInterface
{
use DefaultConfigFormTrait;
}
+200
View File
@@ -0,0 +1,200 @@
# Merge Smartlinks into MT3S Marketing Program
Instructions for merging the `SmartlinksBundle` plugin (`mautic-plugin-smartlinks`) into
`MT3SMarketingProgramBundle` (this repo) as one unique bundle.
- **Reversibility**: both repos are tagged `pre-merge-v1` (pushed to origin).
Roll back with `git reset --hard pre-merge-v1`.
- **Principles**:
1. One unique bundle: `MT3SMarketingProgramBundle` hosts everything.
2. Domains stay separate: the *Marketing Program* domain and the *Smart Links* domain keep
their own menu groups, routes, permission categories, configuration sections and
translation prefixes. They only share the bundle, the plugin row and the codebase.
3. Every entity is left intact: no table, column or JSON shape changes. Only the PHP
namespace of the Smart Links classes changes.
4. Mautic naming best practices, vendor **MT3 Solutions** (acronym **MT3S**): the host
bundle already follows them (`MauticPlugin\MT3SMarketingProgramBundle`,
`mt3s/mautic-marketing-program-bundle`, service ids `mt3s.*`, params
`mt3s_marketing_program_*`, tables `mt3s_mp_program_*`, permission base
`mt3smarketingprogram`).
## Inventory
### Coming in from `mautic-plugin-smartlinks` (Smart Links domain, version 0.6.0)
| Layer | Contents |
|---|---|
| Entities | `SmartLink` (`smart_links`), `SmartLinkHit` (`smart_link_hits`), `UtmTaxonomy` (`utm_taxonomies`) + repositories |
| Models | `SmartLinkModel` (`smartlinks.smart_link`), `UtmTaxonomyModel` (`smartlinks.utm_taxonomy`) |
| Controllers | `SmartLinkController`, `UtmTaxonomyController`, `PublicController` (public `/l/{slug}`) |
| Forms / validators | `SmartLinkType`, `UtmTaxonomyType`, `SmartLinkValidator`, `UtmTaxonomyValidator`, `UtmSettingsValidator`, `SmartlinksSettingsType`, `SmartLinksConfigType`, `ConfigType`-era classes, `UtmTagsTypeExtension`, `UtmFieldsApplicator`, `UtmSettingsTransformer`, catalog (`UtmParameterCatalog` …) |
| Services | `UtmConfigurationProvider`, `UtmConfigurationNormalizer`, `SmartLinkShortUrlBuilder` |
| Views | `Resources/views/SmartLink/*`, `Resources/views/UtmTaxonomy/*`, `Resources/views/FormTheme/Config/*` |
| Config tab | "Smart Links Settings" (`SmartlinksConfigSubscriber` + theme): section "UTM Settings" (enforce lowercase, separator, short link domain) + section "Parameters" |
| Menu | Group "Smart Links": children "UTM Taxonomies" (above) and "Smart Links" |
| Permissions | categories `smart_links`, `taxonomies` (base `smartlinks:`) |
| Params | `smartlinks_utm_config`, `smartlinks_config` (+ legacy keys `utm_manager_config`, `utm_manager_smart_links`) |
| Translations | `mautic.smartlinks.*` keys (en_US + fr_FR) |
| Migrations | `Version_0_2_0` … `Version_0_6_0` (all idempotent by schema checks) |
| Other | `Assets/js/smartlinks.js`, `Tests/Unit/*` (90 tests), `phpunit.xml.dist`, icon |
| Public | route `/l/{slug}` — short links keep working, no URL change |
### Already in the host (Marketing Program domain, version 0.17.0)
`mt3s_mp_program*` tables (programs, tasks, stakeholders, audiences, item types), menu group
"Programs" with 5 children, permission base `mt3smarketingprogram:` (categories `programs`,
`tasks`, `stakeholders`, `audiences`, `itemtypes`), config tab "Program Settings",
params `mt3s_marketing_program_*`, translations `mt3s.marketing_program.*`,
`Assets/js/mt3s-mp-program.js`, migrations `Version_0_2_0` … `Version_0_17_0`.
## Impact analysis
1. **Namespace** — every `MauticPlugin\SmartlinksBundle\` reference becomes
`MauticPlugin\MT3SMarketingProgramBundle\`. Pure textual remap; classes keep their names
(domains stay identifiable by their class-name prefixes: `SmartLink*`, `UtmTaxonomy*` vs
`Program*`, `Task*`, `Stakeholder*`, `Audience*` — flat Mautic directory convention).
2. **Database — zero schema/data impact**: `smart_links`, `smart_link_hits`, `utm_taxonomies`
keep their names and columns. No migration of data is required; existing rows keep working
(proven idempotent migrations).
3. **Migration class-name collision (critical)**: both repos define `Version_0_2_0.php` …
overlapping names. One `Migrations/` directory cannot contain both sets (the engine builds
`MauticPlugin\<Bundle>\Migrations\<Class>` per file; duplicate class names are fatal).
→ The incoming Smart Links migrations are renamed with a suffix, e.g.
`Version_0_2_0.php` → `Version_0_2_0_SmartLinks.php` (class renamed accordingly).
Their `shouldExecute()` schema checks are unchanged, so nothing re-runs.
4. **Plugin row**: the two rows (`SmartlinksBundle` 0.6.0, `MT3SMarketingProgramBundle` 0.17.0)
become ONE: keep this repo's row (version bumped to `0.18.0`), delete the `SmartlinksBundle`
row. The engine replays every migration through its schema checks on reload — all no-op.
5. **Permissions (role re-grant)**: the categories `smart_links` and `taxonomies` move under
the host permission class, so their base becomes `mt3smarketingprogram:smart_links:*` /
`mt3smarketingprogram:taxonomies:*`. Stored role grants referencing the old
`smartlinks:*` base must be re-granted once (dev DB: admin only, zero impact; production:
one-time re-grant, same as the 0.5.0 rename).
6. **Routes keep their names** (`mautic_smartlinks_*`) and paths (`/smart-links`, `/utm-taxonomies`,
`/l/{slug}`): no session, bookmark or saved-list breakage. (Optional later cosmetic pass to
`mt3s_smart_links_*` is noted but not required.)
7. **Menu**: the "Smart Links" group is added as a second top-level entry next to "Programs" —
domains remain separately visible, no icon/id collisions.
8. **Config**: the "Smart Links Settings" tab (`smartlinksconfig` alias) is added alongside
"Program Settings"; its params (`smartlinks_utm_config`, `smartlinks_config` + legacy keys)
move into `Config/config.php` verbatim — saved local.php values keep working, including the
legacy-key fallbacks.
9. **Translations**: the `mautic.smartlinks.*` keys are appended to this repo's
`Translations/{en_US,fr_FR}/messages.ini|validators.ini` (key prefixes are globally unique —
parse-check every file after each edit; a stray quote kills the whole catalog).
10. **Assets**: `smartlinks.js` becomes `Assets/js/mt3s-mp-smartlinks.js` (host file-naming
convention; the mauticContent/OnLoad prefixes it registers are unchanged).
11. **Integrations**: the host keeps `MT3SMarketingProgramIntegration`; the Smart Links
`SmartlinksIntegration` (+ its `ConfigSupport`) move in as additional
`mautic.integration` services — one plugin may register several.
12. **Dev environment**: `docker-compose.yml` drops the `PLUGIN_SMARTLINKS_PATH` mount; this
repo remains the single `MT3SMarketingProgramBundle` mount. `.env` updated accordingly.
13. **The `mautic-plugin-smartlinks` repo** becomes obsolete after the merge: archive it, don't
delete (it carries `pre-merge-v1` and the full history).
## Procedure (step by step)
All work happens on a branch `merge-smartlinks` of THIS repo. The `mautic-plugin-smartlinks`
repo is read-only source material (already tagged).
### Phase 1 — import the Smart Links code
1. From `mautic-plugin-smartlinks`, copy into this repo (paths unchanged):
`Catalog/`, `Controller/` (the 3 Smart Links controllers), `Entity/` (3 entities + 3
repositories), `EventListener/` (`SmartLinksConfigSubscriber`, `PluginInstallSubscriber`),
`Form/` (types, validators, transformer, applicator, extension), `Integration/`
(Smartlinks integration + ConfigSupport), `Model/` (2 models), `Resources/views/SmartLink/`,
`Resources/views/UtmTaxonomy/`, `Resources/views/FormTheme/Config/`, `Service/` (3 services),
`Assets/img/` (icon), `Tests/Unit/…` (the smartlinks tests).
2. Textual namespace remap in every copied file:
`MauticPlugin\SmartlinksBundle\` → `MauticPlugin\MT3SMarketingProgramBundle\`.
3. `Assets/js/smartlinks.js` → `Assets/js/mt3s-mp-smartlinks.js` (contents unchanged).
4. Migrations: copy `Version_0_2_0.php` … `Version_0_6_0.php` renamed to
`Version_0_2_0_SmartLinks.php` … `Version_0_6_0_SmartLinks.php` (class names likewise);
namespace remap; the `TABLE_NAME` constants they reference are unchanged.
5. Gate: `grep -rn "SmartlinksBundle" .` must return zero hits afterwards.
### Phase 2 — merge Config/config.php
Add to this repo's `Config/config.php` (keep every existing entry untouched):
- `routes.main`: the 4 Smart Links routes (`mautic_smartlinks_index`, `mautic_smartlinks_action`,
`mautic_smartlinks_taxonomies`, `mautic_smartlinks_taxonomy_action`), controllers re-pointed
at the new namespace; keep `routes.public` `mautic_smartlinks_go` (`/l/{slug}`).
- `menu.main`: the whole `mautic.smartlinks.menu.root` group (UTM Taxonomies above Smart Links),
access arrays re-based to `mt3smarketingprogram:smart_links:*` / `mt3smarketingprogram:taxonomies:*`.
- `services.integrations`: `mt3s.smart_links.integration` + `…integration.configuration`
(host `mt3s.*` id convention; class namespaces remapped).
- `parameters`: `smartlinks_utm_config`, `smartlinks_config`, legacy `utm_manager_config`,
`utm_manager_smart_links` — verbatim.
- Bump `'version'` to `'0.18.0'`; extend `'description'` to mention smart links.
### Phase 3 — fold permissions, services, config tab
- `Security/Permissions/MT3SMarketingProgramPermissions.php`: add
`$this->addExtendedPermissions('smart_links'); $this->addExtendedPermissions('taxonomies');`
and the matching `addExtendedFormFields('mt3smarketingprogram', 'smart_links'|'taxonomies', …)`
lines; do NOT copy `SmartlinksPermissions.php` into the bundle.
- `Config/services.php`: add the model aliases
`mautic.smartlinks.model.smart_link` / `mautic.smartlinks.model.utm_taxonomy`
(plus `mt3s.smart_links.model.*` aliases if wanted); nothing else — autoconfiguration
picks up the new classes.
- `SmartLinksConfigSubscriber`: verify the `'bundle' => 'MT3SMarketingProgramBundle'` entry and
the `@Smartlinks/FormTheme/Config/…` twig paths (the twig namespace follows the bundle name).
### Phase 4 — translations
Append the `mautic.smartlinks.*` keys from the source repo's 4 ini files into this repo's
4 ini files (same keys, no renames; the `SmartlinksConfigSubscriber` tab key
`mautic.config.tab.smartlinksconfig` comes along). **Parse-check all 4 files after every
edit** — `parse_ini_file()` must not return `false` (a single stray quote kills the whole
catalog, as happened in 0.6.0).
### Phase 5 — dev environment + database registration
1. `mautic-dev-env/docker-compose.yml`: remove the `PLUGIN_SMARTLINKS_PATH` mount line;
`.env` + `.env.example`: remove the variable.
2. `docker compose up -d` (recreates the containers with the single mount).
3. Database: `DELETE FROM plugins WHERE bundle='SmartlinksBundle';` and
`UPDATE plugins SET version='0.18.0' WHERE bundle='MT3SMarketingProgramBundle';`
4. Stop the background containers, then:
`./dev.sh cc && ./dev.sh console mautic:plugins:reload`
then restart them (they race the cache clear; the web container also needs a restart
afterwards when opcache validates timestamps off).
5. `./dev.sh console mautic:assets:generate`.
### Phase 6 — verification checklist
- [ ] `php -l` over every file; full ini parse-check (4 files)
- [ ] Plugin row: ONE `MT3SMarketingProgramBundle` 0.18.0; Plugins page shows "MT3S Marketing Program"
- [ ] Menu: "Programs" group (5 children) AND "Smart Links" group (UTM Taxonomies, Smart Links)
- [ ] Config: "Program Settings" tab AND "Smart Links Settings" tab (UTM Settings + Parameters)
- [ ] Smart Links: list/create/edit; taxonomy select + fieldsets; out-of-list value rejected
- [ ] UTM Taxonomies: list/create/edit (checkbox subsets + free-value lists)
- [ ] Public redirect: `curl -sI -H 'Host: <short_link_domain>' http://localhost:8080/l/<slug>`
→ 302 with UTM parameters on the Location; hits recorded in `smart_link_hits`
- [ ] Marketing Program pages: programs, tasks, stakeholders, audiences, item types all load
- [ ] Translations: no raw `mautic.*` keys anywhere (en + fr)
- [ ] Roles: re-grant `mt3smarketingprogram:smart_links:*` / `…:taxonomies:*` where needed
- [ ] Tests: `php /tmp/phpunit.phar --do-not-cache-result -c
docroot/plugins/MT3SMarketingProgramBundle/phpunit.xml.dist` (merged suites, both domains)
- [ ] Legacy data: `smart_links` / `utm_taxonomies` rows intact; `mt3s_mp_*` tables untouched
### Phase 7 — finalize
1. `readme.md`: add the Smart Links domain section (structure, short links, taxonomies,
public redirect, tests).
2. Commit `feat: merge Smartlinks into MT3S Marketing Program (smart links + UTM taxonomies)`;
push; tag `post-merge-v1`; archive `mautic-plugin-smartlinks`.
3. Rollback at any point: `git reset --hard pre-merge-v1` in this repo — the source repo is
untouched throughout the merge.
## Risk register
| Risk | Mitigation |
|---|---|
| Migration class-name collision → fatal reload | Phase 1.4 renames the incoming set; verify no duplicate class names in `Migrations/` |
| Broken translation catalog (stray quote) | Phase 4 parse-check after every edit |
| `cache:clear` races / opcache staleness | stop cron+worker, `dev.sh cc`, restart the web container |
| Permission base change breaks saved roles | Phase 6 re-grant checklist (documented, one-time) |
| Missed namespace reference | Phase 1.5 grep gate: zero `SmartlinksBundle` hits |
| Data loss | none by design: no schema/data migration; `pre-merge-v1` tags on both repos |
+1
View File
@@ -6,6 +6,7 @@ namespace MauticPlugin\MT3SMarketingProgramBundle\Migrations;
use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Schema;
use Mautic\IntegrationsBundle\Migration\AbstractMigration; use Mautic\IntegrationsBundle\Migration\AbstractMigration;
/** /**
* Since 0.10.0 objectives have a type, the key of an objective type set up in Settings > * Since 0.10.0 objectives have a type, the key of an objective type set up in Settings >
* Configuration > Plan Settings (parameter plan_objective_types). Adds initiative_objectives.type for * Configuration > Plan Settings (parameter plan_objective_types). Adds initiative_objectives.type for
+2 -1
View File
@@ -6,6 +6,7 @@ namespace MauticPlugin\MT3SMarketingProgramBundle\Migrations;
use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Schema;
use Mautic\IntegrationsBundle\Migration\AbstractMigration; use Mautic\IntegrationsBundle\Migration\AbstractMigration;
/** /**
* Since 0.10.1 objectives have a priority, a whole number from 1 (highest) to 99 (lowest). Adds * Since 0.10.1 objectives have a priority, a whole number from 1 (highest) to 99 (lowest). Adds
* initiative_objectives.priority for installs created before 0.10.1: NOT NULL with the default 1, and the * initiative_objectives.priority for installs created before 0.10.1: NOT NULL with the default 1, and the
@@ -29,7 +30,7 @@ class Version_0_10_1 extends AbstractMigration
if (!$table->hasColumn('priority')) { if (!$table->hasColumn('priority')) {
$this->addSql(sprintf( $this->addSql(sprintf(
"ALTER TABLE %s ADD priority INT NOT NULL DEFAULT %d", 'ALTER TABLE %s ADD priority INT NOT NULL DEFAULT %d',
$objectives, $objectives,
1 1
)); ));
+1
View File
@@ -9,6 +9,7 @@ use Doctrine\ORM\Tools\SchemaTool;
use Mautic\IntegrationsBundle\Migration\AbstractMigration; use Mautic\IntegrationsBundle\Migration\AbstractMigration;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\Audience; use MauticPlugin\MT3SMarketingProgramBundle\Entity\Audience;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\AudienceType as AudienceTypeEnum; use MauticPlugin\MT3SMarketingProgramBundle\Entity\AudienceType as AudienceTypeEnum;
/** /**
* Since 0.11.0 a plan has audiences (table initiative_audiences, initiative_audiences_stages before 0.15.0) with any * Since 0.11.0 a plan has audiences (table initiative_audiences, initiative_audiences_stages before 0.15.0) with any
* number of Mautic stages (join table initiative_audiences_stages). Creates both tables for installs created * number of Mautic stages (join table initiative_audiences_stages). Creates both tables for installs created
+2 -1
View File
@@ -7,6 +7,7 @@ namespace MauticPlugin\MT3SMarketingProgramBundle\Migrations;
use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Schema;
use Mautic\IntegrationsBundle\Migration\AbstractMigration; use Mautic\IntegrationsBundle\Migration\AbstractMigration;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\Audience; use MauticPlugin\MT3SMarketingProgramBundle\Entity\Audience;
/** /**
* Since 0.14.0 audiences are a global directory (Planning > Audiences, called Targets before 0.15.0), * Since 0.14.0 audiences are a global directory (Planning > Audiences, called Targets before 0.15.0),
* like stakeholders: * like stakeholders:
@@ -46,7 +47,7 @@ class Version_0_14_0 extends AbstractMigration
} }
[$directory, $links] = $names; [$directory, $links] = $names;
$oldNaming = 'initiative_audiences' === $directory; $oldNaming = 'initiative_audiences' === $directory;
$table = $schema->getTable($directory); $table = $schema->getTable($directory);
$shared = fn (string $column): bool => $table->hasColumn($this->concatPrefix($column)); $shared = fn (string $column): bool => $table->hasColumn($this->concatPrefix($column));
+1
View File
@@ -7,6 +7,7 @@ namespace MauticPlugin\MT3SMarketingProgramBundle\Migrations;
use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Schema;
use Mautic\IntegrationsBundle\Migration\AbstractMigration; use Mautic\IntegrationsBundle\Migration\AbstractMigration;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\Audience; use MauticPlugin\MT3SMarketingProgramBundle\Entity\Audience;
/** /**
* Historical migration (from 0.15.0, when the bundle was still PlanBundle): it renamed "targets" * Historical migration (from 0.15.0, when the bundle was still PlanBundle): it renamed "targets"
* to "audiences" — plan_targets became plan_audiences (its target_type column audience_type), * to "audiences" — plan_targets became plan_audiences (its target_type column audience_type),
+13 -13
View File
@@ -34,20 +34,20 @@ class Version_0_16_0 extends AbstractMigration
* needed, but one rename per line keeps half-applied states recoverable). * needed, but one rename per line keeps half-applied states recoverable).
*/ */
private const TABLES = [ private const TABLES = [
'plans' => 'initiatives', 'plans' => 'initiatives',
'plan_objectives' => 'initiative_objectives', 'plan_objectives' => 'initiative_objectives',
'plan_description_items' => 'initiative_description_items', 'plan_description_items' => 'initiative_description_items',
'plan_allocation_items' => 'initiative_allocation_items', 'plan_allocation_items' => 'initiative_allocation_items',
'plan_tasks' => 'initiative_tasks', 'plan_tasks' => 'initiative_tasks',
'plan_task_dependencies' => 'initiative_task_dependencies', 'plan_task_dependencies' => 'initiative_task_dependencies',
'plan_task_raci' => 'initiative_task_raci', 'plan_task_raci' => 'initiative_task_raci',
'plan_task_raci_stakeholders' => 'initiative_task_raci_stakeholders', 'plan_task_raci_stakeholders' => 'initiative_task_raci_stakeholders',
'plan_stakeholders' => 'initiative_stakeholders', 'plan_stakeholders' => 'initiative_stakeholders',
'plan_stakeholders_plan' => 'initiative_stakeholders_initiative', 'plan_stakeholders_plan' => 'initiative_stakeholders_initiative',
'plan_audiences' => 'initiative_audiences', 'plan_audiences' => 'initiative_audiences',
'plan_audiences_plan' => 'initiative_audiences_initiative', 'plan_audiences_plan' => 'initiative_audiences_initiative',
'plan_audiences_segments' => 'initiative_audiences_segments', 'plan_audiences_segments' => 'initiative_audiences_segments',
'plan_audiences_stages' => 'initiative_audiences_stages', 'plan_audiences_stages' => 'initiative_audiences_stages',
]; ];
/** /**
+2 -2
View File
@@ -43,12 +43,12 @@ class Version_0_17_0 extends AbstractMigration
'initiative_description_items' => 'mt3s_mp_program_description_items', 'initiative_description_items' => 'mt3s_mp_program_description_items',
'initiative_allocation_items' => 'mt3s_mp_program_allocation_items', 'initiative_allocation_items' => 'mt3s_mp_program_allocation_items',
'initiative_tasks' => 'mt3s_mp_program_tasks', 'initiative_tasks' => 'mt3s_mp_program_tasks',
'initiative_task_dependencies' => 'mt3s_mp_program_task_dependencies', 'initiative_task_dependencies' => 'mt3s_mp_program_task_dependencies',
'initiative_task_raci' => 'mt3s_mp_program_task_raci', 'initiative_task_raci' => 'mt3s_mp_program_task_raci',
'initiative_task_raci_stakeholders' => 'mt3s_mp_program_task_raci_stakeholders', 'initiative_task_raci_stakeholders' => 'mt3s_mp_program_task_raci_stakeholders',
'initiative_stakeholders' => 'mt3s_mp_program_stakeholders', 'initiative_stakeholders' => 'mt3s_mp_program_stakeholders',
'initiative_stakeholders_initiative' => 'mt3s_mp_program_stakeholders_program', 'initiative_stakeholders_initiative' => 'mt3s_mp_program_stakeholders_program',
'initiative_audiences' => 'mt3s_mp_program_audiences', 'initiative_audiences' => 'mt3s_mp_program_audiences',
'initiative_audiences_initiative' => 'mt3s_mp_program_audiences_program', 'initiative_audiences_initiative' => 'mt3s_mp_program_audiences_program',
'initiative_audiences_segments' => 'mt3s_mp_program_audiences_segments', 'initiative_audiences_segments' => 'mt3s_mp_program_audiences_segments',
'initiative_audiences_stages' => 'mt3s_mp_program_audiences_stages', 'initiative_audiences_stages' => 'mt3s_mp_program_audiences_stages',
+1
View File
@@ -7,6 +7,7 @@ namespace MauticPlugin\MT3SMarketingProgramBundle\Migrations;
use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Table; use Doctrine\DBAL\Schema\Table;
use Mautic\IntegrationsBundle\Migration\AbstractMigration; use Mautic\IntegrationsBundle\Migration\AbstractMigration;
/** /**
* Brings the plans table in line with the entity mapping. * Brings the plans table in line with the entity mapping.
* *
+54
View File
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Migrations;
use Doctrine\DBAL\Schema\Schema;
use Mautic\IntegrationsBundle\Migration\AbstractMigration;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink;
/**
* Creates the Smart Links table for installs of version 0.1.0, which predate the feature.
*
* The plugin installer creates the tables of fresh installs (installPluginSchema runs
* SchemaTool on the plugin's own entities); on update core only runs these migrations.
* Idempotent: runs on plugin update (core's migration engine) and right after a fresh
* install (PluginInstallSubscriber), and stops when the table already exists.
*/
class Version_0_2_0_SmartLinks extends AbstractMigration
{
protected function isApplicable(Schema $schema): bool
{
return !$schema->hasTable($this->concatPrefix(SmartLink::TABLE_NAME));
}
protected function up(): void
{
$table = $this->concatPrefix(SmartLink::TABLE_NAME);
$this->addSql(<<<SQL
CREATE TABLE {$table} (
id INT UNSIGNED AUTO_INCREMENT NOT NULL,
is_published TINYINT(1) NOT NULL,
date_added DATETIME DEFAULT NULL,
created_by INT DEFAULT NULL,
created_by_user VARCHAR(191) DEFAULT NULL,
date_modified DATETIME DEFAULT NULL,
modified_by INT DEFAULT NULL,
modified_by_user VARCHAR(191) DEFAULT NULL,
checked_out DATETIME DEFAULT NULL,
checked_out_by INT DEFAULT NULL,
checked_out_by_user VARCHAR(191) DEFAULT NULL,
slug VARCHAR(9) NOT NULL,
redirect_type VARCHAR(20) DEFAULT 'external' NOT NULL,
redirect_code INT DEFAULT 302 NOT NULL,
destination_url LONGTEXT DEFAULT NULL,
utm_parameters JSON NOT NULL,
UNIQUE INDEX UNIQ_SLUG (slug),
INDEX smart_link_slug (slug),
PRIMARY KEY(id)
) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB
SQL);
}
}
+1
View File
@@ -6,6 +6,7 @@ namespace MauticPlugin\MT3SMarketingProgramBundle\Migrations;
use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Schema;
use Mautic\IntegrationsBundle\Migration\AbstractMigration; use Mautic\IntegrationsBundle\Migration\AbstractMigration;
/** /**
* Adds plans.version and the initiative_objectives table to installs created before 0.3.0. * Adds plans.version and the initiative_objectives table to installs created before 0.3.0.
* *
+72
View File
@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Migrations;
use Doctrine\DBAL\Schema\Schema;
use Mautic\IntegrationsBundle\Migration\AbstractMigration;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLinkHit;
/**
* Creates the Smart Link hits table (one row per call of a short link) for installs of
* version 0.2.0, which predate the redirect feature.
*
* The plugin installer creates the tables of fresh installs (installPluginSchema runs
* SchemaTool on the plugin's own entities); on update core only runs these migrations.
* Idempotent: runs on plugin update (core's migration engine) and right after a fresh
* install (PluginInstallSubscriber), and stops when the table already exists.
*/
class Version_0_3_0_SmartLinks extends AbstractMigration
{
protected function isApplicable(Schema $schema): bool
{
return !$schema->hasTable($this->concatPrefix(SmartLinkHit::TABLE_NAME));
}
protected function up(): void
{
$schema = $this->entityManager->getConnection()->createSchemaManager()->introspectSchema();
$table = $this->concatPrefix(SmartLinkHit::TABLE_NAME);
$this->addSql(<<<SQL
CREATE TABLE {$table} (
id INT UNSIGNED AUTO_INCREMENT NOT NULL,
is_published TINYINT(1) NOT NULL,
smart_link_id INT UNSIGNED NOT NULL,
date_added DATETIME DEFAULT NULL,
created_by INT DEFAULT NULL,
created_by_user VARCHAR(191) DEFAULT NULL,
date_modified DATETIME DEFAULT NULL,
modified_by INT DEFAULT NULL,
modified_by_user VARCHAR(191) DEFAULT NULL,
checked_out DATETIME DEFAULT NULL,
checked_out_by INT DEFAULT NULL,
checked_out_by_user VARCHAR(191) DEFAULT NULL,
ip_address VARCHAR(45) DEFAULT NULL,
referer LONGTEXT DEFAULT NULL,
user_agent LONGTEXT DEFAULT NULL,
INDEX smart_link_hit_link (smart_link_id),
PRIMARY KEY(id)
) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB
SQL);
$this->addSql($this->generateAlterTableForeignKeyStatement(
SmartLinkHit::TABLE_NAME,
['smart_link_id'],
$this->resolveLinksTableName($schema),
['id'],
'ON DELETE CASCADE'
));
}
/**
* The links table under the name it has right now: Version_0_5_0 renames utm_smart_links to
* smart_links, and an update from 0.2.0 runs this migration before the rename.
*/
private function resolveLinksTableName(Schema $schema): string
{
return $schema->hasTable($this->concatPrefix('smart_links')) ? 'smart_links' : 'utm_smart_links';
}
}
+1 -1
View File
@@ -76,7 +76,7 @@ class Version_0_4_0 extends AbstractMigration
} }
} }
throw new \RuntimeException('SchemaTool returned no CREATE TABLE statement for '.'initiative_tasks'.'.'); throw new \RuntimeException('SchemaTool returned no CREATE TABLE statement for initiative_tasks.');
} }
/** /**
+97
View File
@@ -0,0 +1,97 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Migrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Table;
use Mautic\IntegrationsBundle\Migration\AbstractMigration;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink;
/**
* Adds the Mautic destinations to the Smart Links: a landing page or a standalone form.
*
* Idempotent: runs on plugin update (core's migration engine) and right after a fresh
* install (PluginInstallSubscriber), and stops when the columns already exist.
*/
class Version_0_4_0_SmartLinks extends AbstractMigration
{
/**
* Local column => referenced core table.
*/
private const FOREIGN_KEYS = [
'page_id' => 'pages',
'form_id' => 'forms',
];
protected function isApplicable(Schema $schema): bool
{
$table = $this->getTable($schema);
if (null === $table) {
return false;
}
foreach (array_keys(self::FOREIGN_KEYS) as $column) {
if (!$table->hasColumn($column)) {
return true;
}
}
return [] !== $this->getMissingForeignKeys($table);
}
protected function up(): void
{
$schema = $this->entityManager->getConnection()->createSchemaManager()->introspectSchema();
$table = $this->getTable($schema);
if (null === $table) {
return;
}
foreach (array_keys(self::FOREIGN_KEYS) as $column) {
if (!$table->hasColumn($column)) {
$this->addSql(sprintf(
'ALTER TABLE %s ADD %s INT UNSIGNED DEFAULT NULL',
$this->concatPrefix(SmartLink::TABLE_NAME),
$column
));
}
}
foreach ($this->getMissingForeignKeys($table) as $column => $referenceTable) {
$this->addSql($this->generateAlterTableForeignKeyStatement(
SmartLink::TABLE_NAME,
[$column],
$referenceTable,
['id'],
'ON DELETE SET NULL'
));
}
}
private function getTable(Schema $schema): ?Table
{
$name = $this->concatPrefix(SmartLink::TABLE_NAME);
return $schema->hasTable($name) ? $schema->getTable($name) : null;
}
/**
* @return array<string, string>
*/
private function getMissingForeignKeys(Table $table): array
{
$missing = self::FOREIGN_KEYS;
foreach ($table->getForeignKeys() as $foreignKey) {
foreach ($foreignKey->getLocalColumns() as $column) {
unset($missing[$column]);
}
}
return $missing;
}
}
+208
View File
@@ -0,0 +1,208 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Migrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Table;
use Mautic\IntegrationsBundle\Migration\AbstractMigration;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLinkHit;
/**
* The 0.5.0 rename of the plugin (UTM Manager -> Smartlinks) also renames its tables and their
* indexes: utm_smart_links -> smart_links and utm_smart_link_hits -> smart_link_hits.
*
* Mautic syncs the plugin schema before running the migrations, so the new tables usually
* already exist (empty, straight from the entity metadata) when this runs: the rows are copied
* from the old tables, which are then dropped (hits first: they still reference the old links
* table). When the new tables don't exist yet (a plugin update without the schema sync) the old
* tables are renamed instead, which keeps the rows, the foreign keys and the indexes.
*
* Installs updated from 0.3.0 skipped the Mautic destinations of Version_0_4_0, which looks for
* the table under its new name: the page_id / form_id columns and their foreign keys are
* re-checked here so every install converges to the same schema.
*
* Idempotent: runs on plugin update (core's migration engine) and right after a fresh install
* (PluginInstallSubscriber), and stops when nothing is left to rename, copy or add.
*/
class Version_0_5_0_SmartLinks extends AbstractMigration
{
private const RENAMED_TABLES = [
'utm_smart_links' => 'smart_links',
'utm_smart_link_hits' => 'smart_link_hits',
];
private const RENAMED_INDEXES = [
'utm_smart_link_slug' => 'smart_link_slug',
'utm_smart_link_hit_link' => 'smart_link_hit_link',
];
/** Local column => referenced core table (the Mautic destinations of Version_0_4_0). */
private const MAUTIC_DESTINATIONS = [
'page_id' => 'pages',
'form_id' => 'forms',
];
protected function isApplicable(Schema $schema): bool
{
foreach (array_keys(self::RENAMED_TABLES) as $old) {
if ($schema->hasTable($this->concatPrefix($old))) {
return true;
}
}
$links = $this->findLinksTable($schema);
if (null !== $links) {
foreach (array_keys(self::MAUTIC_DESTINATIONS) as $column) {
if (!$links->hasColumn($column)) {
return true;
}
}
if ([] !== $this->getOldIndexes($links) || [] !== $this->getMissingForeignKeys($links)) {
return true;
}
}
$hits = $this->findHitsTable($schema);
return null !== $hits && [] !== $this->getOldIndexes($hits);
}
protected function up(): void
{
$schema = $this->entityManager->getConnection()->createSchemaManager()->introspectSchema();
$emptied = [];
foreach (self::RENAMED_TABLES as $old => $new) {
$oldTable = $this->findTable($schema, $old);
$newTable = $this->findTable($schema, $new);
if (null === $oldTable) {
continue; // nothing left under the old name
}
if (null === $newTable) {
// No schema sync ran: rename keeps the rows, the foreign keys and the indexes.
$this->addSql(sprintf('RENAME TABLE %s TO %s', $this->concatPrefix($old), $this->concatPrefix($new)));
continue;
}
// The schema sync already created the new table (empty): copy the rows over, then
// drop the old table. Hits reference links, so everything is copied before the
// first DROP (see below).
$columns = implode(', ', array_intersect(
array_keys($newTable->getColumns()),
array_keys($oldTable->getColumns())
));
$this->addSql(sprintf(
'INSERT INTO %s (%s) SELECT %s FROM %s',
$this->concatPrefix($new),
$columns,
$columns,
$this->concatPrefix($old)
));
$emptied[] = $old;
}
// Drop the copied-from tables, hits first: their foreign key still references the old links table.
foreach (array_reverse($emptied) as $old) {
$this->addSql(sprintf('DROP TABLE %s', $this->concatPrefix($old)));
}
$links = $this->findLinksTable($schema);
$hits = $this->findHitsTable($schema);
if (null === $links) {
return;
}
// The statements below run after the RENAME TABLE ones, so they target the new names.
foreach ([[SmartLink::TABLE_NAME, $links], [SmartLinkHit::TABLE_NAME, $hits]] as [$name, $table]) {
if (null === $table) {
continue;
}
foreach ($this->getOldIndexes($table) as $old) {
$this->addSql(sprintf(
'ALTER TABLE %s DROP INDEX %s, ADD INDEX %s (%s)',
$this->concatPrefix($name),
$old,
self::RENAMED_INDEXES[$old],
implode(', ', $table->getIndex($old)->getColumns())
));
}
}
foreach (array_keys(self::MAUTIC_DESTINATIONS) as $column) {
if (!$links->hasColumn($column)) {
$this->addSql(sprintf(
'ALTER TABLE %s ADD %s INT UNSIGNED DEFAULT NULL',
$this->concatPrefix(SmartLink::TABLE_NAME),
$column
));
}
}
foreach ($this->getMissingForeignKeys($links) as $column => $referenceTable) {
$this->addSql($this->generateAlterTableForeignKeyStatement(
SmartLink::TABLE_NAME,
[$column],
$referenceTable,
['id'],
'ON DELETE SET NULL'
));
}
}
/**
* The links table under the name it has right now: new on fresh installs, old on installs
* that wait for the RENAME TABLE statements queued above.
*/
private function findLinksTable(Schema $schema): ?Table
{
return $this->findTable($schema, SmartLink::TABLE_NAME) ?? $this->findTable($schema, 'utm_smart_links');
}
private function findHitsTable(Schema $schema): ?Table
{
return $this->findTable($schema, SmartLinkHit::TABLE_NAME) ?? $this->findTable($schema, 'utm_smart_link_hits');
}
private function findTable(Schema $schema, string $name): ?Table
{
$name = $this->concatPrefix($name);
return $schema->hasTable($name) ? $schema->getTable($name) : null;
}
/**
* @return list<string> Indexes still carrying their pre-rename name
*/
private function getOldIndexes(Table $table): array
{
return array_values(array_filter(
array_keys(self::RENAMED_INDEXES),
fn (string $index): bool => $table->hasIndex($index)
));
}
/**
* @return array<string, string>
*/
private function getMissingForeignKeys(Table $table): array
{
$missing = self::MAUTIC_DESTINATIONS;
foreach ($table->getForeignKeys() as $foreignKey) {
foreach ($foreignKey->getLocalColumns() as $column) {
unset($missing[$column]);
}
}
return $missing;
}
}
+2 -1
View File
@@ -7,6 +7,7 @@ namespace MauticPlugin\MT3SMarketingProgramBundle\Migrations;
use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Schema;
use Doctrine\ORM\Tools\SchemaTool; use Doctrine\ORM\Tools\SchemaTool;
use Mautic\IntegrationsBundle\Migration\AbstractMigration; use Mautic\IntegrationsBundle\Migration\AbstractMigration;
/** /**
* For installs created before 0.6.0: * For installs created before 0.6.0:
* - creates initiative_description_items (and its foreign key to plans, ON DELETE CASCADE); * - creates initiative_description_items (and its foreign key to plans, ON DELETE CASCADE);
@@ -80,6 +81,6 @@ class Version_0_6_0 extends AbstractMigration
} }
} }
throw new \RuntimeException('SchemaTool returned no CREATE TABLE statement for '.'initiative_description_items'.'.'); throw new \RuntimeException('SchemaTool returned no CREATE TABLE statement for initiative_description_items.');
} }
} }
+100
View File
@@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Migrations;
use Doctrine\DBAL\Schema\Schema;
use Mautic\IntegrationsBundle\Migration\AbstractMigration;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\UtmTaxonomy;
/**
* The 0.6.0 UTM Taxonomies feature: the `utm_taxonomies` table, and the taxonomy of each
* Smart Link (`utm_taxonomy_id`, ON DELETE SET NULL: deleting a taxonomy keeps its links,
* they redirect with the values they already carry).
*
* Idempotent: runs on plugin update (core's migration engine) and right after a fresh install
* (PluginInstallSubscriber), and stops when everything is already in place.
*/
class Version_0_6_0_SmartLinks extends AbstractMigration
{
protected function isApplicable(Schema $schema): bool
{
return !$schema->hasTable($this->concatPrefix(UtmTaxonomy::TABLE_NAME))
|| !$this->hasTaxonomyColumn($schema)
|| [] !== $this->getMissingForeignKeys($schema);
}
protected function up(): void
{
$schema = $this->entityManager->getConnection()->createSchemaManager()->introspectSchema();
if (!$schema->hasTable($this->concatPrefix(UtmTaxonomy::TABLE_NAME))) {
$table = $this->concatPrefix(UtmTaxonomy::TABLE_NAME);
$this->addSql(<<<SQL
CREATE TABLE {$table} (
id INT UNSIGNED AUTO_INCREMENT NOT NULL,
is_published TINYINT(1) NOT NULL,
date_added DATETIME DEFAULT NULL,
created_by INT DEFAULT NULL,
created_by_user VARCHAR(191) DEFAULT NULL,
date_modified DATETIME DEFAULT NULL,
modified_by INT DEFAULT NULL,
modified_by_user VARCHAR(191) DEFAULT NULL,
checked_out DATETIME DEFAULT NULL,
checked_out_by INT DEFAULT NULL,
checked_out_by_user VARCHAR(191) DEFAULT NULL,
name VARCHAR(50) NOT NULL,
description LONGTEXT DEFAULT NULL,
parameters JSON NOT NULL,
UNIQUE INDEX UNIQ_TAXONOMY_NAME (name),
INDEX utm_taxonomy_name (name),
PRIMARY KEY(id)
) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB
SQL);
}
if (!$this->hasTaxonomyColumn($schema)) {
$this->addSql(sprintf(
'ALTER TABLE %s ADD utm_taxonomy_id INT UNSIGNED DEFAULT NULL',
$this->concatPrefix(SmartLink::TABLE_NAME)
));
}
foreach ($this->getMissingForeignKeys($schema) as $foreignKey) {
$this->addSql($this->generateAlterTableForeignKeyStatement(
SmartLink::TABLE_NAME,
['utm_taxonomy_id'],
UtmTaxonomy::TABLE_NAME,
['id'],
'ON DELETE SET NULL'
));
}
}
private function hasTaxonomyColumn(Schema $schema): bool
{
$links = $this->concatPrefix(SmartLink::TABLE_NAME);
return $schema->hasTable($links) && $schema->getTable($links)->hasColumn('utm_taxonomy_id');
}
/**
* @return list<string>
*/
private function getMissingForeignKeys(Schema $schema): array
{
$links = $this->concatPrefix(SmartLink::TABLE_NAME);
$missing = ['utm_taxonomy_id'];
if ($schema->hasTable($links)) {
foreach ($schema->getTable($links)->getForeignKeys() as $foreignKey) {
$missing = array_diff($missing, $foreignKey->getLocalColumns());
}
}
return array_values($missing);
}
}
+2 -1
View File
@@ -7,6 +7,7 @@ namespace MauticPlugin\MT3SMarketingProgramBundle\Migrations;
use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Schema;
use Doctrine\ORM\Tools\SchemaTool; use Doctrine\ORM\Tools\SchemaTool;
use Mautic\IntegrationsBundle\Migration\AbstractMigration; use Mautic\IntegrationsBundle\Migration\AbstractMigration;
/** /**
* Creates initiative_allocation_items (and its foreign key to plans, ON DELETE CASCADE) for installs created * Creates initiative_allocation_items (and its foreign key to plans, ON DELETE CASCADE) for installs created
* before 0.7.0. Each step runs only if needed. As in Version_0_4_0, only the CREATE TABLE statement for * before 0.7.0. Each step runs only if needed. As in Version_0_4_0, only the CREATE TABLE statement for
@@ -71,6 +72,6 @@ class Version_0_7_0 extends AbstractMigration
} }
} }
throw new \RuntimeException('SchemaTool returned no CREATE TABLE statement for '.'initiative_allocation_items'.'.'); throw new \RuntimeException('SchemaTool returned no CREATE TABLE statement for initiative_allocation_items.');
} }
} }
+2 -1
View File
@@ -6,6 +6,7 @@ namespace MauticPlugin\MT3SMarketingProgramBundle\Migrations;
use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Schema;
use Mautic\IntegrationsBundle\Migration\AbstractMigration; use Mautic\IntegrationsBundle\Migration\AbstractMigration;
/** /**
* Since 0.8.0 every amount is in one general currency (Settings > Configuration > Plan Settings, parameter * Since 0.8.0 every amount is in one general currency (Settings > Configuration > Plan Settings, parameter
* program_currency), so the per-record currency columns are dropped: plans.currency, * program_currency), so the per-record currency columns are dropped: plans.currency,
@@ -18,7 +19,7 @@ class Version_0_8_0 extends AbstractMigration
* Table => columns to drop. * Table => columns to drop.
*/ */
private const COLUMNS = [ private const COLUMNS = [
'initiatives' => ['currency'], 'initiatives' => ['currency'],
'initiative_allocation_items' => ['planned_currency', 'real_currency'], 'initiative_allocation_items' => ['planned_currency', 'real_currency'],
]; ];
+1 -1
View File
@@ -13,7 +13,7 @@ use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
/** /**
* Available as mt3s.marketing_program.model.audience, or getModel('mt3smp.audience'). * Available as mautic.mt3smarketingprogram.model.audience, or getModel('mt3smarketingprogram.audience').
* *
* Audiences are a global directory (Programs > Audiences), independent of plans; plans link to * Audiences are a global directory (Programs > Audiences), independent of plans; plans link to
* them from their Audiences tab through ProgramAudience (which carries the audience's priority in * them from their Audiences tab through ProgramAudience (which carries the audience's priority in
+2
View File
@@ -15,6 +15,8 @@ use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
/** /**
* Available as mautic.mt3smarketingprogram.model.program, or getModel('mt3smarketingprogram.program').
*
* @extends FormModel<Program> * @extends FormModel<Program>
*/ */
class ProgramModel extends FormModel class ProgramModel extends FormModel
+354
View File
@@ -0,0 +1,354 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Model;
use Doctrine\ORM\EntityManagerInterface;
use Mautic\CoreBundle\Helper\CoreParametersHelper;
use Mautic\CoreBundle\Helper\UserHelper;
use Mautic\CoreBundle\Model\FormModel;
use Mautic\CoreBundle\Security\Permissions\CorePermissions;
use Mautic\PageBundle\Model\PageModel;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLinkHit;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLinkHitRepository;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLinkRepository;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Type\SmartLinkType;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationProvider;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Available as mautic.mt3smarketingprogram.model.smart_link, or getModel('mt3smarketingprogram.smart_link').
*
* @extends FormModel<SmartLink>
*/
class SmartLinkModel extends FormModel
{
public const MODEL_NAME = 'mt3smarketingprogram.smart_link';
/** Random slugs offered by the "Generate" button: 4 characters, letters and digits. */
public const GENERATED_SLUG_LENGTH = 4;
public function __construct(
EntityManagerInterface $em,
CorePermissions $security,
EventDispatcherInterface $dispatcher,
UrlGeneratorInterface $router,
TranslatorInterface $translator,
UserHelper $userHelper,
LoggerInterface $logger,
CoreParametersHelper $coreParametersHelper,
private readonly UtmConfigurationProvider $utmConfiguration,
private readonly PageModel $pageModel,
) {
parent::__construct($em, $security, $dispatcher, $router, $translator, $userHelper, $logger, $coreParametersHelper);
}
public function getRepository(): SmartLinkRepository
{
$repository = $this->em->getRepository(SmartLink::class);
\assert($repository instanceof SmartLinkRepository);
return $repository;
}
public function getPermissionBase(): string
{
return 'mt3smarketingprogram:smart_links';
}
public function getEntity($id = null): ?SmartLink
{
if (null === $id) {
return new SmartLink();
}
$entity = parent::getEntity($id);
return $entity instanceof SmartLink ? $entity : null;
}
/**
* @param array<string, mixed> $options
*/
public function createForm($entity, FormFactoryInterface $formFactory, $action = null, $options = []): FormInterface
{
if (!$entity instanceof SmartLink) {
throw new MethodNotAllowedHttpException(['SmartLink']);
}
if (!empty($action)) {
$options['action'] = $action;
}
return $formFactory->create(SmartLinkType::class, $entity, $options);
}
/**
* Applies the UTM Manager settings to everything the user typed (slug and values), then saves.
*/
public function saveEntity($entity, $unlock = true): void
{
if ($entity instanceof SmartLink) {
$this->applySlugRules($entity);
$entity->setUtmParameters($this->normalizeUtmValues($entity->getUtmParameters()));
}
parent::saveEntity($entity, $unlock);
}
/**
* Slug rules from Settings > Configuration > UTM Settings: spaces become the configured
* separator (or hyphen), lowercase is enforced when configured. Kept here (not in the form)
* so a manually typed slug, an imported one and a generated one all follow the same rules.
*/
public function applySlugRules(SmartLink $entity, ?string $rawSlug = null): void
{
$raw = $rawSlug ?? (string) ($entity->getSlug() ?? '');
$slug = str_replace(' ', $this->utmConfiguration->getSeparatorReplacement(), trim($raw));
if ($this->utmConfiguration->isLowercaseEnforced()) {
$slug = mb_strtolower($slug);
}
// The user never edits the slug of a saved link (the form field is disabled): the entity
// keeps the stored one. onPersistentEntityChange checks it in the background.
if (null === $entity->getId()) {
$entity->setSlug('' !== $slug ? $slug : null);
} elseif (null !== $rawSlug) {
$entity->setSlug($slug); // throws when it differs from the stored slug
}
}
/**
* @param array<string, string|null> $utmParameters values may be null (an empty form field); they are dropped
*
* @return array<string, string>
*/
public function normalizeUtmValues(array $utmParameters): array
{
$clean = [];
foreach ($utmParameters as $key => $value) {
$key = trim((string) $key);
$value = trim((string) $value);
if ('' === $key || '' === $value) {
continue;
}
if ($this->utmConfiguration->isLowercaseEnforced()) {
$value = mb_strtolower($value);
}
$clean[$key] = $value;
}
ksort($clean);
return $clean;
}
/**
* The slug of a saved link never changes; saveEntity() only re-applies the rules to a slug
* the user could have typed on the "new" form. Drops the form value on edit so the immutable
* one is kept.
*/
public function onPersistentEntityChange(SmartLink $entity, ?string $submittedSlug): void
{
$this->applySlugRules($entity, $submittedSlug);
}
/**
* True when another saved link already uses this slug. $ignoreId keeps a link being
* edited from colliding with itself.
*/
public function isSlugTaken(string $slug, ?int $ignoreId = null): bool
{
return $this->getRepository()->slugExists($slug, $ignoreId);
}
/**
* The short links domain configured in Settings > Configuration > Smart Links Settings,
* without scheme or trailing slash, for example lnk.example.com. Empty when not configured.
*/
public function getShortLinkDomain(): string
{
$stored = $this->coreParametersHelper->get(\MauticPlugin\MT3SMarketingProgramBundle\Form\Type\SmartLinksConfigType::CONFIG_PARAMETER, []);
// Upgrades keep the domain in local.php under a legacy key (the standalone
// SmartlinksBundle wrote `smartlinks_config`, the UtmManagerBundle before it
// `utm_manager_smart_links`); serve it until the Configuration page is saved again.
$legacyKeys = [
\MauticPlugin\MT3SMarketingProgramBundle\Form\Type\SmartLinksConfigType::LEGACY_SMARTLINKS_PARAMETER,
\MauticPlugin\MT3SMarketingProgramBundle\Form\Type\SmartLinksConfigType::LEGACY_CONFIG_PARAMETER,
];
foreach ($legacyKeys as $legacyKey) {
if (!is_array($stored) || '' === trim((string) ($stored['short_link_domain'] ?? ''))) {
$legacy = $this->coreParametersHelper->get($legacyKey, []);
if (is_array($legacy) && '' !== trim((string) ($legacy['short_link_domain'] ?? ''))) {
$stored = $legacy;
}
}
}
$domain = trim(is_array($stored) ? (string) ($stored['short_link_domain'] ?? '') : '');
return '' === $domain ? '' : rtrim($domain, '/');
}
/**
* A random slug of 4 lowercase letters and digits, for example a7f3, that no saved link
* uses yet. Used by the "Generate" button of the form and to prefill a new link.
*/
public function generateSlug(): string
{
$alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789';
do {
$slug = '';
for ($i = 0; $i < self::GENERATED_SLUG_LENGTH; ++$i) {
$slug .= $alphabet[random_int(0, strlen($alphabet) - 1)];
}
} while ($this->isSlugTaken($slug));
return $slug;
}
/**
* The final URL of the redirect, whatever the link's type: the destination with the link's
* UTM parameters appended to its query string. The link's values override same-named
* parameters of the destination; the query of the short link call itself is ignored (the
* stored parameters are the canonical ones).
*
* External redirects go to the configured URL; Mautic redirects go to the public URL of
* the linked landing page (/{slug}) or standalone form (/form/{id}).
*/
public function buildRedirectUrl(SmartLink $link): string
{
$destination = $link->getRedirectType()->isMautic()
? $this->buildMauticDestinationUrl($link)
: trim((string) $link->getDestinationUrl());
return self::appendUtmParameters($destination, $link->getUtmParameters());
}
/**
* The public URL of the Mautic destination: the landing page or the standalone form.
* Empty when the link has no (or no longer a) destination.
*/
public function buildMauticDestinationUrl(SmartLink $link): string
{
if (null !== $link->getPage()) {
// PageModel::generateUrl() handles variants, category and language slugs.
return $this->pageModel->generateUrl($link->getPage());
}
if (null !== $link->getForm()) {
// Standalone forms have no alias URL: their landing page is the form preview.
return $this->router->generate(
'mautic_form_preview',
['id' => $link->getForm()->getId()],
UrlGeneratorInterface::ABSOLUTE_URL
);
}
return '';
}
/**
* Appends the UTM parameters to a destination URL. Pure static method, unit-testable.
*
* @param array<string, string> $utms
*/
public static function appendUtmParameters(string $destination, array $utms): string
{
if ([] === $utms || '' === $destination) {
return $destination;
}
$parts = parse_url($destination);
$query = [];
if (isset($parts['query']) && '' !== $parts['query']) {
parse_str($parts['query'], $query);
}
// The link's parameters win over the destination's own ones.
$parts['query'] = http_build_query(array_merge($query, $utms));
return self::unparseUrl($parts);
}
/**
* Records one call of the short link (date, IP, referer, user agent). Statistics never
* block the redirect: the controller wraps the call in a try/catch.
*/
public function recordHit(SmartLink $link, Request $request): SmartLinkHit
{
$hit = new SmartLinkHit();
$hit->setSmartLink($link);
$hit->setIpAddress($request->getClientIp());
$hit->setReferer($request->headers->get('referer'));
$hit->setUserAgent($request->headers->get('user-agent'));
$this->em->persist($hit);
$this->em->flush();
return $hit;
}
/**
* Hit counts of every link, in one query: link id => number of hits.
*
* @return array<int, int>
*/
public function getHitCounts(): array
{
return $this->getHitRepository()->getHitCounts();
}
private function getHitRepository(): SmartLinkHitRepository
{
$repository = $this->em->getRepository(SmartLinkHit::class);
\assert($repository instanceof SmartLinkHitRepository);
return $repository;
}
/**
* Rebuilds a URL from parse_url() parts (the scheme/host/path/query the destination had).
*
* @param array<string, mixed> $parts
*/
private static function unparseUrl(array $parts): string
{
$url = '';
if (isset($parts['scheme'])) {
$url .= $parts['scheme'].'://';
} elseif (isset($parts['host'])) {
$url .= '//';
}
$url .= $parts['host'] ?? '';
if (isset($parts['port'])) {
$url .= ':'.$parts['port'];
}
$url .= $parts['path'] ?? '';
if (isset($parts['query'])) {
$url .= '?'.$parts['query'];
}
if (isset($parts['fragment'])) {
$url .= '#'.$parts['fragment'];
}
return $url;
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
/** /**
* Available as mt3s.marketing_program.model.stakeholder, or getModel('mt3smp.stakeholder'). * Available as mautic.mt3smarketingprogram.model.stakeholder, or getModel('mt3smarketingprogram.stakeholder').
* *
* On save, the phone number is normalized to E.164 using the default region from Settings > * On save, the phone number is normalized to E.164 using the default region from Settings >
* Configuration > Program Settings (parameter mt3s_marketing_program_stakeholder_phone_region, FR by default). A number that * Configuration > Program Settings (parameter mt3s_marketing_program_stakeholder_phone_region, FR by default). A number that
+1 -1
View File
@@ -14,7 +14,7 @@ use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
/** /**
* Available as mt3s.marketing_program.model.task, or getModel('mt3smp.task'). * Available as mautic.mt3smarketingprogram.model.task, or getModel('mt3smarketingprogram.task').
* *
* @extends FormModel<Task> * @extends FormModel<Task>
*/ */
+149
View File
@@ -0,0 +1,149 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Model;
use Doctrine\ORM\EntityManagerInterface;
use Mautic\CoreBundle\Helper\CoreParametersHelper;
use Mautic\CoreBundle\Helper\UserHelper;
use Mautic\CoreBundle\Model\FormModel;
use Mautic\CoreBundle\Security\Permissions\CorePermissions;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\UtmTaxonomy;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\UtmTaxonomyRepository;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Type\UtmTaxonomyType;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Available as mautic.mt3smarketingprogram.model.utm_taxonomy, or getModel('mt3smarketingprogram.utm_taxonomy').
*
* @extends FormModel<UtmTaxonomy>
*/
class UtmTaxonomyModel extends FormModel
{
public const MODEL_NAME = 'mt3smarketingprogram.utm_taxonomy';
public function __construct(
EntityManagerInterface $em,
CorePermissions $security,
EventDispatcherInterface $dispatcher,
UrlGeneratorInterface $router,
TranslatorInterface $translator,
UserHelper $userHelper,
LoggerInterface $logger,
CoreParametersHelper $coreParametersHelper,
) {
parent::__construct($em, $security, $dispatcher, $router, $translator, $userHelper, $logger, $coreParametersHelper);
}
public function getRepository(): UtmTaxonomyRepository
{
$repository = $this->em->getRepository(UtmTaxonomy::class);
\assert($repository instanceof UtmTaxonomyRepository);
return $repository;
}
public function getPermissionBase(): string
{
return 'mt3smarketingprogram:taxonomies';
}
public function getEntity($id = null): ?UtmTaxonomy
{
if (null === $id) {
return new UtmTaxonomy();
}
$entity = parent::getEntity($id);
return $entity instanceof UtmTaxonomy ? $entity : null;
}
/**
* @param array<string, mixed> $options
*/
public function createForm($entity, FormFactoryInterface $formFactory, $action = null, $options = []): FormInterface
{
if (!$entity instanceof UtmTaxonomy) {
throw new MethodNotAllowedHttpException(['UtmTaxonomy']);
}
if (!empty($action)) {
$options['action'] = $action;
}
return $formFactory->create(UtmTaxonomyType::class, $entity, $options);
}
/**
* Applies the canonical shape to the value lists (trimmed, de-duplicated, sorted), then saves.
*/
public function saveEntity($entity, $unlock = true): void
{
if ($entity instanceof UtmTaxonomy) {
$entity->setParameters($this->normalizeParameters($entity->getParameters()));
}
parent::saveEntity($entity, $unlock);
}
/**
* The canonical shape of the `parameters` array: parameter key => list of {value, label} rows.
* Empty keys and values are dropped, duplicates keep their first label, labels fall back to
* the value, keys and rows keep a stable order. The UtmTaxonomyValidator guarantees the
* technical pattern of the values; this is the safety net behind it.
*
* @param array<string, mixed> $parameters
*
* @return array<string, list<array{value: string, label: string}>>
*/
public function normalizeParameters(array $parameters): array
{
$clean = [];
foreach ($parameters as $key => $rows) {
$key = trim((string) $key);
if ('' === $key || !is_array($rows)) {
continue;
}
$values = [];
foreach ($rows as $row) {
if (!is_array($row)) {
continue;
}
$value = trim((string) ($row['value'] ?? ''));
if ('' === $value || isset($values[$value])) {
continue;
}
$label = trim((string) ($row['label'] ?? ''));
$values[$value] = ['value' => $value, 'label' => '' !== $label ? $label : $value];
}
if ([] !== $values) {
$clean[$key] = array_values($values);
}
}
ksort($clean);
return $clean;
}
/**
* True when another saved taxonomy already uses this name. $ignoreId keeps a taxonomy being
* edited from colliding with itself.
*/
public function isNameTaken(string $name, ?int $ignoreId = null): bool
{
return $this->getRepository()->nameExists($name, $ignoreId);
}
}
@@ -0,0 +1,169 @@
{# Settings > Configuration > Smart Links Settings: the single tab of the plugin. Section "UTM
Settings": the general rules and the short link domain. Section "Parameters": the catalog and
custom parameters. Behaviour (rows, import, suggestions) lives in Assets/js/mt3s-mp-smartlinks.js. #}
{% block _config_smartlinksconfig_widget %}
{% set utm = form.children.mt3s_smart_links_utm_config %}
{% set links = form.children.mt3s_smart_links_config %}
<div class="text-muted small pb-md">{{ 'mt3s.smart_links.settings.description'|trans }}</div>
{{ form_errors(utm) }}
{{ form_errors(links) }}
<div class="smartlinks-utm-config">
<h4 class="fw-sb mb-xs">{{ 'mt3s.smart_links.config.section.utm_settings'|trans }}</h4>
<div class="panel panel-default mb-md">
<div class="panel-body">
<div class="row">
<div class="col-md-4">{{ form_row(utm.children.enforce_lowercase) }}</div>
<div class="col-md-4">{{ form_row(utm.children.separator_replacement) }}</div>
<div class="col-md-4">{{ form_row(links.children.short_link_domain) }}</div>
</div>
</div>
</div>
<h4 class="fw-sb mt-lg mb-xs">{{ 'mt3s.smart_links.config.section.parameters'|trans }}</h4>
<p class="text-muted small">{{ 'mt3s.smart_links.config.description'|trans }}</p>
{% for group in ['standard', 'platform'] %}
<h5 class="fw-sb mt-md mb-sm">{{ ('mt3s.smart_links.config.group.' ~ group)|trans }}</h5>
<div class="panel-group mb-md">
{% for parameter in utm.children.parameters|filter(p => p.vars.utm_group == group) %}
{{ form_widget(parameter) }}
{% endfor %}
</div>
{% endfor %}
{% set custom = utm.children.custom_parameters %}
<h5 class="fw-sb mt-md mb-sm">{{ 'mt3s.smart_links.config.group.custom'|trans }}</h5>
{{ form_errors(custom) }}
<div class="panel-group mb-sm utm-custom-parameters"
data-prototype="{{ form_widget(custom.vars.prototype)|e('html_attr') }}"
data-index="{{ custom|length > 0 ? max(custom|keys) + 1 : 0 }}">
{% for parameter in custom %}
{{ form_widget(parameter) }}
{% endfor %}
</div>
<p class="text-muted small utm-custom-empty{{ custom|length > 0 ? ' hide' : '' }}">{{ 'mt3s.smart_links.config.custom.empty'|trans }}</p>
<button type="button" class="btn btn-default" data-utm-add-parameter>
<i class="ri-add-line"></i> {{ 'mt3s.smart_links.config.custom.add'|trans }}
</button>
{% do custom.setRendered() %}
</div>
{% endblock %}
{# One parameter: accordion panel. #}
{% block utm_parameter_widget %}
{% set fields = form.children %}
{% set isCustom = form.vars.utm_custom %}
{% set bodyId = form.vars.id ~ '_body' %}
{% set hasErrors = formContainsErrors(form) %}
{% set keyText = isCustom ? fields.key.vars.value : form.vars.utm_key %}
<div class="panel panel-default mb-xs utm-parameter" data-utm-parameter>
<div class="panel-heading">
<a class="panel-title d-flex" role="button" data-toggle="collapse" href="#{{ bodyId }}" aria-controls="{{ bodyId }}">
<code class="utm-parameter-key mr-sm">{{ keyText is not empty ? keyText : 'mt3s.smart_links.config.custom.new'|trans }}</code>
<span class="text-muted">{{ fields.label.vars.value }}</span>
{% if form.vars.utm_auto_generated %}
<span class="label label-default ml-sm" data-toggle="tooltip" title="{{ 'mt3s.smart_links.config.auto_generated.tooltip'|trans }}">{{ 'mt3s.smart_links.config.auto_generated.badge'|trans }}</span>
{% endif %}
{% if hasErrors %}<i class="ri-alert-line text-danger ml-sm"></i>{% endif %}
</a>
</div>
<div id="{{ bodyId }}" class="panel-collapse collapse{{ hasErrors or (isCustom and keyText is empty) ? ' in' : '' }}">
<div class="panel-body">
{% if form.vars.utm_description_key %}
<p class="text-muted small">{{ form.vars.utm_description_key|trans }}</p>
{% endif %}
<div class="row">
{% if isCustom %}
<div class="col-md-3">{{ form_row(fields.key) }}</div>
{% endif %}
<div class="col-md-{{ isCustom ? 3 : 4 }}">{{ form_row(fields.label) }}</div>
<div class="col-md-{{ isCustom ? 3 : 4 }}">{{ form_row(fields.mode) }}</div>
<div class="col-md-{{ isCustom ? 3 : 4 }}">{{ form_row(fields.enabled) }}</div>
</div>
{% if fields.values is defined %}
{% set values = fields.values %}
<div class="row">
{# Hidden unless mode = dropdown, by Mautic's form field state switcher (data-show-on). #}
<div class="col-xs-12 utm-values-editor" id="{{ form.vars.id }}_values_editor"
data-show-on="{{ {(fields.mode.vars.id): 'dropdown'}|json_encode|e('html_attr') }}">
<label class="control-label">{{ 'mt3s.smart_links.config.values'|trans }}</label>
{{ form_errors(values) }}
<div class="row small text-muted mb-xs">
<div class="col-xs-1"></div>
<div class="col-xs-4">{{ 'mt3s.smart_links.config.values.value'|trans }}</div>
<div class="col-xs-4">{{ 'mt3s.smart_links.config.values.label'|trans }}</div>
<div class="col-xs-2">{{ 'mt3s.smart_links.config.values.default'|trans }}</div>
</div>
<div class="utm-values-list" data-prototype="{{ form_widget(values.vars.prototype)|e('html_attr') }}">
{% for row in values %}
{{ form_widget(row) }}
{% endfor %}
</div>
<p class="text-muted small utm-values-empty{{ values|length > 0 ? ' hide' : '' }}">{{ 'mt3s.smart_links.config.values.empty'|trans }}</p>
<div class="mb-sm">
<button type="button" class="btn btn-default btn-sm" data-utm-add-value>
<i class="ri-add-line"></i> {{ 'mt3s.smart_links.config.values.add'|trans }}
</button>
{% if form.vars.utm_suggestions is not empty %}
<button type="button" class="btn btn-default btn-sm{{ values|length > 0 ? ' hide' : '' }}" data-utm-load-suggestions
data-utm-suggestions="{{ form.vars.utm_suggestions|json_encode|e('html_attr') }}">
<i class="ri-magic-line"></i> {{ 'mt3s.smart_links.config.values.suggestions'|trans }}
</button>
{% endif %}
</div>
<label class="control-label small" for="{{ form.vars.id }}_import">{{ 'mt3s.smart_links.config.values.import'|trans }}</label>
<div class="input-group mb-sm">
{# Not a form field: the text is never submitted, the script turns it into value rows. #}
<textarea id="{{ form.vars.id }}_import" class="form-control utm-import-text" rows="3"
placeholder="{{ 'mt3s.smart_links.config.values.import.placeholder'|trans }}"></textarea>
<span class="input-group-btn">
<button type="button" class="btn btn-default" data-utm-import>{{ 'mt3s.smart_links.config.values.import.button'|trans }}</button>
</span>
</div>
</div>
</div>
{% do values.setRendered() %}
{% endif %}
{% if isCustom %}
<button type="button" class="btn btn-danger btn-sm" data-utm-remove-parameter>
<i class="ri-delete-bin-line"></i> {{ 'mt3s.smart_links.config.custom.remove'|trans }}
</button>
{% endif %}
</div>
</div>
</div>
{% endblock %}
{# One allowed value of a dropdown parameter. #}
{% block utm_value_widget %}
{% set fields = form.children %}
<div class="row mb-xs utm-value-row">
<div class="col-xs-1">
<span class="btn btn-default btn-sm utm-value-handle" title="{{ 'mt3s.smart_links.config.values.drag'|trans }}"><i class="ri-draggable"></i></span>
</div>
<div class="col-xs-4">
{{ form_widget(fields.value) }}
{{ form_errors(fields.value) }}
</div>
<div class="col-xs-4">
{{ form_widget(fields.label) }}
{{ form_errors(fields.label) }}
</div>
<div class="col-xs-2">
<label class="checkbox-inline" title="{{ 'mt3s.smart_links.config.values.default'|trans }}">
{{ form_widget(fields.is_default) }}
</label>
</div>
<div class="col-xs-1">
<button type="button" class="btn btn-default btn-sm" data-utm-remove-value title="{{ 'mt3s.smart_links.config.values.remove'|trans }}">
<i class="ri-delete-bin-line"></i>
</button>
</div>
</div>
{% endblock %}
+71
View File
@@ -0,0 +1,71 @@
{% extends '@MauticCore/Default/content.html.twig' %}
{% block mauticContent %}mt3sMpSmartLink{% endblock %}
{% block headerTitle %}
{% if form.vars.data.id %}
{{ 'mt3s.smart_links.smart_links.header.edit'|trans({'%slug%': form.vars.data.slug}) }}
{% else %}
{{ 'mt3s.smart_links.smart_links.header.new'|trans }}
{% endif %}
{% endblock %}
{% block content %}
{{ form_start(form) }}
<div class="box-layout">
<div class="col-md-9 height-auto bdr-r">
<div class="pa-md">
{# Short link preview: the slug the user types, on the domain set in Smart Links Settings. #}
<div class="well well-sm" id="smartLinkDomainReminder"
data-domain="{{ form.vars.smart_link_domain }}"
data-separator="{{ form.vars.smart_link_separator }}"
data-lowercase="{{ form.vars.smart_link_lowercase ? '1' : '0' }}">
<span class="text-muted">{{ 'mt3s.smart_links.smart_links.domain.reminder'|trans }}</span>
<code id="smartLinkPreview">{{ form.vars.smart_link_domain ? form.vars.smart_link_domain ~ '/l/' : '' }}{{ form.vars.smart_link_slug }}</code>
</div>
<div class="input-group smart-link-slug-group">
{{ form_row(form.slug) }}
{% if not form.vars.smart_link_is_saved %}
<span class="input-group-btn">
<button type="button" class="btn btn-default" id="smartLinkGenerateSlug"
data-generated="{{ form.vars.smart_link_generated }}"
title="{{ 'mt3s.smart_links.smart_links.slug.generate.tooltip'|trans }}">
<i class="ri-refresh-line"></i>
{{ 'mt3s.smart_links.smart_links.slug.generate'|trans }}
</button>
</span>
{% endif %}
</div>
{# The UTM taxonomy of the link: its allowed values drive the fields on the right. #}
{{ form_row(form.taxonomy) }}
{{ form_row(form.redirectType) }}
<div id="smartLinkDestinationUrlWrapper"{% if form.vars.data.redirectType.value == 'mautic' %} class="hide"{% endif %}>
{{ form_row(form.destinationUrl) }}
</div>
<div id="smartLinkMauticDestinationWrapper"{% if form.vars.data.redirectType.value != 'mautic' %} class="hide"{% endif %}>
{{ form_row(form.destination) }}
</div>
</div>
</div>
<div class="col-md-3 height-auto">
<div class="pr-lg pl-lg pt-md pb-md">
<h4>{{ 'mt3s.smart_links.smart_links.utm_parameters'|trans }}</h4>
<p class="text-muted small">{{ 'mt3s.smart_links.smart_links.utm_parameters.help'|trans }}</p>
{# One fieldset per taxonomy: Mautic's data-show-on switcher shows the one of the
chosen taxonomy (the container carries the col- class the switcher toggles). #}
{% for taxonomyId, fieldset in form.vars.smart_link_utm_fieldsets %}
<div class="col-xs-12 smart-link-utm-fields" data-show-on="{{ {(form.taxonomy.vars.id): taxonomyId}|json_encode|e('html_attr') }}">
{% for key in fieldset.keys %}
{{ form_row(form.utmParameters[fieldset.prefix ~ key]) }}
{% endfor %}
</div>
{% endfor %}
{% do form.utmParameters.setRendered() %}
</div>
</div>
</div>
{{ form_end(form) }}
{% endblock %}
+149
View File
@@ -0,0 +1,149 @@
{% set isIndex = 'index' == tmpl|default('index') ? true : false %}
{% set tmpl = 'list' %}
{% extends isIndex ? '@MauticCore/Default/content.html.twig' : '@MauticCore/Default/raw_output.html.twig' %}
{% block mauticContent %}mt3sMpSmartLink{% endblock %}
{% block headerTitle %}{{ 'mt3s.smart_links.smart_links.header.index'|trans }}{% endblock %}
{% block content %}
<div id="page-list-wrapper" class="{% if items|length > 0 or searchValue is not empty %}panel {% endif %}panel-default">
{# The toolbar belongs to the full page only: ajax reloads (sort, filter, pagination)
replace the contents of .page-list, so including it here again would duplicate it. #}
{% if isIndex %}
{{- include('@MauticCore/Helper/list_toolbar.html.twig', {
'searchValue': searchValue,
'action': currentRoute,
'page_actions': {
'templateButtons': {
'new': permissions[permissionBase ~ ':create'],
},
'langVar': 'mt3smarketingprogram.smart_links',
'routeBase': 'smart_links',
},
'bulk_actions': {
'langVar': 'mt3smarketingprogram.smart_links',
'templateButtons': {
'delete': permissions[permissionBase ~ ':deleteown'] or permissions[permissionBase ~ ':deleteother'],
},
},
}) -}}
{% endif %}
<div class="page-list">
{% if items is defined and items is not empty %}
<div class="table-responsive">
<table class="table table-hover" id="smartLinkTable">
<thead>
<tr>
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'checkall': 'true',
'target': '#smartLinkTable',
}) }}
{# Columns: Short link, Slug, Redirect, Destination, Date added. #}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': sessionVar,
'orderBy': tablePrefix ~ '.slug',
'text': 'mt3s.smart_links.smart_links.short_link',
'class': 'col-smart-link-slug',
'default': true,
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': sessionVar,
'text': 'mt3s.smart_links.smart_links.taxonomy',
'class': 'visible-md visible-lg col-smart-link-taxonomy',
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': sessionVar,
'orderBy': tablePrefix ~ '.redirectType',
'text': 'mt3s.smart_links.smart_links.redirect_type',
'class': 'visible-md visible-lg col-smart-link-type',
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': sessionVar,
'orderBy': tablePrefix ~ '.destinationUrl',
'text': 'mt3s.smart_links.smart_links.destination_url',
'class': 'visible-md visible-lg col-smart-link-destination',
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': sessionVar,
'orderBy': tablePrefix ~ '.hitCount',
'text': 'mt3s.smart_links.smart_links.hits',
'class': 'col-smart-link-hits',
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': sessionVar,
'orderBy': tablePrefix ~ '.dateAdded',
'text': 'mautic.core.date.added',
'class': 'visible-md visible-lg col-smart-link-date',
}) }}
</tr>
</thead>
<tbody>
{% for item in items %}
{% set canEdit = securityHasEntityAccess(permissions[permissionBase ~ ':editown'], permissions[permissionBase ~ ':editother'], item.createdBy) %}
<tr>
<td>
{{- include('@MauticCore/Helper/list_actions.html.twig', {
'item': item,
'templateButtons': {
'edit': canEdit,
'delete': securityHasEntityAccess(permissions[permissionBase ~ ':deleteown'], permissions[permissionBase ~ ':deleteother'], item.createdBy),
},
'langVar': 'mt3smarketingprogram.smart_links',
'routeBase': 'smart_links',
}) -}}
</td>
<td>
{# Shortened link https://{domain}/l/{slug}; a tooltip shows the UTM parameters it carries. #}
{% set shortLink = shortLinkDomain ? 'https://' ~ shortLinkDomain ~ '/l/' ~ item.slug : item.slug %}
{% if canEdit %}
<a href="{{ path(actionRoute, {'objectAction': 'edit', 'objectId': item.id}) }}" data-toggle="ajax" title="{{ shortLink }}">{{ shortLink }}</a>
{% else %}
<span title="{{ shortLink }}">{{ shortLink }}</span>
{% endif %}
</td>
<td class="visible-md visible-lg">
{{ item.taxonomy.name|default('—') }}
</td>
<td class="visible-md visible-lg">
<span class="label label-{{ item.redirectType.value == 'mautic' ? 'info' : 'warning' }}">
{{ ('mt3s.smart_links.smart_links.redirect_type.' ~ item.redirectType.value)|trans ~ ' · ' ~ item.redirectCode.value }}
</span>
</td>
<td class="visible-md visible-lg text-muted">
{{ item.destinationLabel|default('—') }}
</td>
<td>
<span class="label label-info" title="{{ 'mt3s.smart_links.smart_links.hits.tooltip'|trans }}">
{{ hitCounts[item.id]|default(0) }}
</span>
</td>
<td class="visible-md visible-lg">{{ dateToFull(item.dateAdded) }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="panel-footer">
{{- include('@MauticCore/Helper/pagination.html.twig', {
'totalItems': totalItems,
'page': page,
'limit': limit,
'baseUrl': path(indexRoute),
'sessionVar': sessionVar,
}) -}}
</div>
</div>
{% elseif searchValue is not empty %}
{{ include('@MauticCore/Helper/noresults.html.twig') }}
{% else %}
<div class="mt-80 col-md-offset-2 col-lg-offset-3 col-md-8 col-lg-5 height-auto">
{{ include('@MauticCore/Components/content-block.html.twig', {
'heading': 'mt3s.smart_links.smart_links.onboarding.heading',
'subheading': 'mt3s.smart_links.smart_links.onboarding.subheading',
'copy': 'mt3s.smart_links.smart_links.onboarding.copy',
}) }}
</div>
{% endif %}
</div>
</div>
{% endblock %}
@@ -0,0 +1,43 @@
{% extends '@MauticCore/Default/content.html.twig' %}
{% block mauticContent %}mt3sMpUtmTaxonomy{% endblock %}
{% block headerTitle %}
{% if form.vars.data.id %}
{{ 'mt3s.smart_links.taxonomies.header.edit'|trans({'%name%': form.vars.data.name}) }}
{% else %}
{{ 'mt3s.smart_links.taxonomies.header.new'|trans }}
{% endif %}
{% endblock %}
{% block content %}
{{ form_start(form) }}
<div class="box-layout">
<div class="col-md-9 height-auto bdr-r">
<div class="pa-md">
{{ form_row(form.name) }}
{{ form_row(form.description) }}
<h4 class="fw-sb mt-lg mb-xs">{{ 'mt3s.smart_links.taxonomies.parameters'|trans }}</h4>
<p class="text-muted small">{{ 'mt3s.smart_links.taxonomies.parameters.help'|trans }}</p>
{{ form_errors(form.parameters) }}
<div class="panel panel-default mb-md">
<div class="panel-body">
{# One checkbox list per dropdown parameter: the choices are exactly the
values configured in Smart Links Settings, nothing can be typed. #}
{% for key, child in form.parameters %}
<div class="col-xs-6">{{ form_row(child) }}</div>
{% endfor %}
</div>
</div>
{% do form.parameters.setRendered() %}
</div>
</div>
<div class="col-md-3 height-auto">
<div class="pr-lg pl-lg pt-md pb-md">
{{ form_row(form.buttons) }}
</div>
</div>
</div>
{{ form_end(form) }}
{% endblock %}
+118 -10
View File
@@ -1,19 +1,127 @@
{% set isIndex = 'index' == tmpl ? true : false %} {% set isIndex = 'index' == tmpl|default('index') ? true : false %}
{% set tmpl = 'list' %} {% set tmpl = 'list' %}
{% extends isIndex ? '@MauticCore/Default/content.html.twig' : '@MauticCore/Default/raw_output.html.twig' %} {% extends isIndex ? '@MauticCore/Default/content.html.twig' : '@MauticCore/Default/raw_output.html.twig' %}
{% block mauticContent %}mt3sMpProgramUtmTaxonomy{% endblock %} {% block mauticContent %}mt3sMpUtmTaxonomy{% endblock %}
{% block headerTitle %}{{ 'mt3s.marketing_program.utm_taxonomy.header.index'|trans }}{% endblock %} {% block headerTitle %}{{ 'mt3s.smart_links.taxonomies.header.index'|trans }}{% endblock %}
{% block content %} {% block content %}
<div class="page-list"> <div id="page-list-wrapper" class="{% if items|length > 0 or searchValue is not empty %}panel {% endif %}panel-default">
<div class="mt-80 col-md-offset-2 col-lg-offset-3 col-md-8 col-lg-5 height-auto"> {# The toolbar belongs to the full page only: ajax reloads (sort, filter, pagination)
{{ include('@MauticCore/Components/content-block.html.twig', { replace the contents of .page-list, so including it here again would duplicate it. #}
'heading': 'mt3s.marketing_program.utm_taxonomy.onboarding.heading', {% if isIndex %}
'subheading': 'mt3s.marketing_program.utm_taxonomy.onboarding.subheading', {{- include('@MauticCore/Helper/list_toolbar.html.twig', {
'copy': 'mt3s.marketing_program.utm_taxonomy.onboarding.copy', 'searchValue': searchValue,
}) }} 'action': currentRoute,
'page_actions': {
'templateButtons': {
'new': permissions[permissionBase ~ ':create'],
},
'langVar': 'smartlinks.taxonomies',
'routeBase': 'utm_taxonomies',
},
'bulk_actions': {
'langVar': 'smartlinks.taxonomies',
'templateButtons': {
'delete': permissions[permissionBase ~ ':deleteown'] or permissions[permissionBase ~ ':deleteother'],
},
},
}) -}}
{% endif %}
<div class="page-list">
{% if items is defined and items is not empty %}
<div class="table-responsive">
<table class="table table-hover" id="utmTaxonomyTable">
<thead>
<tr>
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'checkall': 'true',
'target': '#utmTaxonomyTable',
}) }}
{# Columns: Name, Description, Parameters, Date added. #}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': sessionVar,
'orderBy': tablePrefix ~ '.name',
'text': 'mt3s.smart_links.taxonomies.name',
'class': 'col-utm-taxonomy-name',
'default': true,
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': sessionVar,
'orderBy': tablePrefix ~ '.description',
'text': 'mt3s.smart_links.taxonomies.description',
'class': 'visible-md visible-lg col-utm-taxonomy-description',
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': sessionVar,
'text': 'mt3s.smart_links.taxonomies.parameter_count',
'class': 'visible-md visible-lg col-utm-taxonomy-parameters',
}) }}
{{ include('@MauticCore/Helper/tableheader.html.twig', {
'sessionVar': sessionVar,
'orderBy': tablePrefix ~ '.dateAdded',
'text': 'mautic.core.date.added',
'class': 'visible-md visible-lg col-utm-taxonomy-date',
}) }}
</tr>
</thead>
<tbody>
{% for item in items %}
{% set canEdit = securityHasEntityAccess(permissions[permissionBase ~ ':editown'], permissions[permissionBase ~ ':editother'], item.createdBy) %}
<tr>
<td>
{{- include('@MauticCore/Helper/list_actions.html.twig', {
'item': item,
'templateButtons': {
'edit': canEdit,
'delete': securityHasEntityAccess(permissions[permissionBase ~ ':deleteown'], permissions[permissionBase ~ ':deleteother'], item.createdBy),
},
'langVar': 'smartlinks.taxonomies',
'routeBase': 'utm_taxonomies',
}) -}}
</td>
<td>
{% if canEdit %}
<a href="{{ path(actionRoute, {'objectAction': 'edit', 'objectId': item.id}) }}" data-toggle="ajax">{{ item.name }}</a>
{% else %}
<span>{{ item.name }}</span>
{% endif %}
</td>
<td class="visible-md visible-lg text-muted">
{{ item.description|default('—')|slice(0, 120) }}
</td>
<td class="visible-md visible-lg">
<span class="label label-info" title="{{ 'mt3s.smart_links.taxonomies.parameter_count.tooltip'|trans }}">
{{ item.parameters|length }}
</span>
</td>
<td class="visible-md visible-lg">{{ dateToFull(item.dateAdded) }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="panel-footer">
{{- include('@MauticCore/Helper/pagination.html.twig', {
'totalItems': totalItems,
'page': page,
'limit': limit,
'baseUrl': path(indexRoute),
'sessionVar': sessionVar,
}) -}}
</div>
</div>
{% elseif searchValue is not empty %}
{{ include('@MauticCore/Helper/noresults.html.twig') }}
{% else %}
<div class="mt-80 col-md-offset-2 col-lg-offset-3 col-md-8 col-lg-5 height-auto">
{{ include('@MauticCore/Components/content-block.html.twig', {
'heading': 'mt3s.smart_links.taxonomies.onboarding.heading',
'subheading': 'mt3s.smart_links.taxonomies.onboarding.subheading',
'copy': 'mt3s.smart_links.taxonomies.onboarding.copy',
}) }}
</div>
{% endif %}
</div> </div>
</div> </div>
{% endblock %} {% endblock %}
@@ -24,12 +24,14 @@ class MT3SMarketingProgramPermissions extends AbstractPermissions
{ {
parent::__construct($params); parent::__construct($params);
$this->addStandardPermissions('categories'); $this->addStandardPermissions(['categories']);
$this->addExtendedPermissions('programs'); $this->addExtendedPermissions(['programs']);
$this->addExtendedPermissions('tasks'); $this->addExtendedPermissions(['tasks']);
$this->addExtendedPermissions('stakeholders'); $this->addExtendedPermissions(['stakeholders']);
$this->addExtendedPermissions('audiences'); $this->addExtendedPermissions(['audiences']);
$this->addStandardPermissions('itemtypes'); $this->addExtendedPermissions(['smart_links']);
$this->addExtendedPermissions(['taxonomies']);
$this->addStandardPermissions(['itemtypes']);
} }
public function getName(): string public function getName(): string
@@ -48,6 +50,8 @@ class MT3SMarketingProgramPermissions extends AbstractPermissions
$this->addExtendedFormFields('mt3smarketingprogram', 'tasks', $builder, $data); $this->addExtendedFormFields('mt3smarketingprogram', 'tasks', $builder, $data);
$this->addExtendedFormFields('mt3smarketingprogram', 'stakeholders', $builder, $data); $this->addExtendedFormFields('mt3smarketingprogram', 'stakeholders', $builder, $data);
$this->addExtendedFormFields('mt3smarketingprogram', 'audiences', $builder, $data); $this->addExtendedFormFields('mt3smarketingprogram', 'audiences', $builder, $data);
$this->addExtendedFormFields('mt3smarketingprogram', 'smart_links', $builder, $data);
$this->addExtendedFormFields('mt3smarketingprogram', 'taxonomies', $builder, $data);
$this->addStandardFormFields('mt3smarketingprogram', 'itemtypes', $builder, $data); $this->addStandardFormFields('mt3smarketingprogram', 'itemtypes', $builder, $data);
} }
} }
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff. Show more