# Bss/CustomerAttributes — Module Audit

Scan of `app/code/Bss/CustomerAttributes` (version `1.5.2.2`, vendor `bsscommerce/customer-attributes`) as a Magento 2 module. Findings are grouped by severity and file.

---

## 1. Packaging / Autoload

### 1.1 PSR-4 root-mapped autoload (critical)
`composer.json`:
```json
"autoload": {
    "files": ["registration.php"],
    "psr-4": { "Bss\\CustomerAttributes\\": "" }
}
```
The namespace is mapped to the module **root** (empty string) instead of the conventional `""` → nothing, or more precisely there is no `src/` layout. This causes the autoloader to attempt PSR-4 resolution for **every** file in the module (including `etc/`, `view/`, `i18n/`, `Test/`), producing many spurious `class_exists` misses and slowing class loading. The Magento convention is to keep PSR-4 pointing at a subfolder or to ensure no non-PHP top-level folders exist; here the root contains `etc/`, `view/`, `i18n/`, `Setup/`, etc., which is tolerated but not ideal.

### 1.2 Overly-loose Composer requirement
```json
"require": { "bsscommerce/core": "*" }
```
Wildcard version constraint — no minimum version pinned. This can silently break on `composer update`. It also **doesn’t declare any dependency on `magento/framework` or `magento/module-customer`**, even though the module hard-depends on them.

### 1.3 Missing Magento core requirements in `composer.json`
Module PHP code uses `Magento_Customer`, `Magento_Eav`, `Magento_Sales`, `Magento_Checkout`, `Magento_Multishipping`, `Magento_Email`, etc. None of these are listed under `require`. Only `module.xml/<sequence>` declares them, which is *not* the same as a composer dependency and will fail Marketplace/EQP validation.

---

## 2. `etc/module.xml`

### 2.1 Deprecated `setup_version` attribute
```xml
<module name="Bss_CustomerAttributes" setup_version="1.5.2.2">
```
`setup_version` has been deprecated since Magento 2.3 in favor of declarative schema (`db_schema.xml` is already present in the module). It should be removed; keeping it forces legacy `InstallSchema`/`UpgradeSchema` semantics to be considered by the setup framework.

### 2.2 Hard sequence dependencies on optional / 3rd-party modules
```xml
<sequence>
    <module name="Magento_Customer"/>
    <module name="Magento_Sales"/>
    <module name="Magento_Eav"/>
    <module name="Amazon_Payment"/>
    <module name="Magento_Multishipping"/>
    <module name="Bss_OneStepCheckout"/>
</sequence>
```
- `Amazon_Payment` was **removed from Magento core** in 2.4.x — declaring it in `<sequence>` will cause `bin/magento setup:upgrade` to fail on stores that don’t have it.
- `Bss_OneStepCheckout` is a paid 3rd-party BSS module — a hard sequence dependency here forces every store to either install it or manually patch this file.
- Sequence entries should be optional integration points, not hard requirements. If integration is needed, use conditional plugins via `di.xml` guarded by `module_exists`-style logic (or provide a separate integration submodule).

---

## 3. `etc/di.xml`

### 3.1 Duplicate `<type>` declarations (dead XML)
The same `<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">` block appears twice (lines 45–51 and 135–141) with the **same** item. The second is dead code. Same duplication for `Bss\CustomerAttributes\Model\ResourceModel\Attribute\Grid\Collection` (lines 52–57 and 142–147).

### 3.2 Duplicate `<type name="Magento\Customer\Model\Customer\Attribute\Validator\File">` plugin
Lines 228–230 and 231–233 register the **exact same plugin twice**. Magento will process both; the effect depends on ordering but at best it’s wasteful, at worst it double-runs validation.

### 3.3 Duplicate plugin name across different types
Both DI entries above use `name="bss_ca_validator_file"` — Magento requires plugin names to be unique **per target type**. They are, technically, but the second `<type>` block collides with itself, effectively overriding the first.

### 3.4 Plugin registered on both interface **and** implementation of the same target
- `Magento\Eav\Model\Attribute\Data\Text` (line 111) and again for `bss_b2b_customer_attributes_plugin_eav_validate_form_text` (line 179).
- Same duplication for `Date`, `Textarea`, `Boolean`, `Multiselect`, `Select`, `File`.

Two different plugin classes (`Bss\...\Plugin\Model\Metadata\Form\ValidateValue` and `Bss\...\Plugin\Integration\Model\Metadata\Form\ValidateValue`) intercept the **same methods** of the **same target**. The order between them is unspecified (both `sortOrder` are 10 or default), and the second one hides the first’s modifications from Around plugins.

### 3.5 `<preference>` used as a plugin substitute (anti-pattern)
```xml
<preference for="Magento\Customer\Model\Metadata\Form\File"
            type="Bss\CustomerAttributes\Plugin\Model\Metadata\Form\File" />
```
- A class named `Plugin\...\File` is registered as a **preference**, not a plugin. This is misleading and, more importantly, **breaks module compatibility**: any other extension using a preference on the same class silently wins/loses.
- Same issue for `Magento\Sales\Block\Adminhtml\Order\Address\Form` and `Magento\Sales\Block\Adminhtml\Order\Create\Billing\Address` (lines 240–241) — preferences on core Sales admin blocks will collide with any other module doing the same and are strongly discouraged by Magento best practices.

### 3.6 Plugin on `Magento\Email\Model\BackendTemplate`
Line 94–96 registers `bss_email_new_account`. `BackendTemplate` is not part of the public API surface for extension and is prone to breakage between Magento minor versions.

### 3.7 `<argument name="shared" xsi:type="object">` misuse
`filterPool` is declared with `shared="false"` at the argument level. `shared` is a **type-level** attribute in `<type>` / `<virtualType>`, not an argument attribute for `<object>`. The XSD tolerates it but Magento silently ignores it here.

### 3.8 Global `di.xml` used for frontend-only plugins
`Bss\CustomerAttributes\Plugin\Model\ShippingInformationManagement`, `PaymentInformationManagement`, and `GuestPaymentInformationManagement` intercept checkout webapi/frontend flows. They belong in `etc/frontend/di.xml` (or `etc/webapi_rest/di.xml`) to avoid being instantiated for admin and CLI areas.

---

## 4. Plugin Code Quality (e.g., `Plugin/Model/ShippingInformationManagement.php`)

### 4.1 Missing property types + PHPDoc-only typing
Fields are declared as `protected $quoteRepository;` with no type hint (Magento 2 code guideline for PHP 7.4+/8.x is typed properties). Constructor uses no promoted properties and no readonly (unlike the modernised `Gti\Overrides\Plugin\AddressRegionTransformer` reference file supplied with this issue).

### 4.2 `@SuppressWarnings(PHPMD.UnusedFormalParameter)` on public plugin methods
Used liberally in the module to suppress warnings rather than fixing the signature. Acceptable for `before*` plugins where the subject is unused, but here it is added even where parameters *are* used, hiding real MD/PMD signal.

### 4.3 Direct dependency on the concrete `\Magento\Quote\Model\QuoteRepository`
Should depend on `\Magento\Quote\Api\CartRepositoryInterface`. Using the concrete model breaks DI substitution and is against the Service Contract policy.

### 4.4 Helper class as dependency
`\Bss\CustomerAttributes\Helper\Customerattribute` is injected almost everywhere. `Helper` classes extending `AbstractHelper` are deprecated as a general-purpose dependency container in Magento; behaviour should be split into dedicated services.

### 4.5 Class-name casing: `Customerattribute`
The helper class is named `Customerattribute` (not `CustomerAttribute`). This violates PSR-1/PSR-12 StudlyCaps and Magento code standards. Case-sensitive filesystems (Linux prod) will surface autoload issues if any consumer types the name correctly.

---

## 5. Class Naming / Namespace layout

- `Bss\CustomerAttributes\Model\Metadata\Form\CheckBoxs` — typo (should be `Checkboxes` / `CheckBoxes`). Referenced explicitly in `di.xml` line 152.
- `Plugin\Model\Metadata\Form\File` is registered as a **preference target**, not a plugin, though it lives under the `Plugin\` namespace.
- Mixed use of `Plugin\Model\...` and `Plugin\Integration\Model\...` intercepting the same core classes, with no README describing the split.

---

## 6. Setup / Schema

- `db_schema.xml` is present alongside `setup_version="1.5.2.2"` — the module mixes declarative schema with legacy setup versioning; `db_schema_whitelist.json` should be reviewed for accuracy (verify presence).
- `Setup/` folder (if it contains `Install`/`Upgrade*Schema.php`) becomes dead code under declarative schema.

---

## 7. Console Command Wiring

```xml
<type name="Bss\CustomerAttributes\Console\Customer\SetRequiredAttributeValue">
    <arguments>
        <argument name="helper" xsi:type="object">Bss\CustomerAttributes\Helper\Customerattribute\Proxy</argument>
    </arguments>
</type>
```
Explicit `\Proxy` suffix is used to lazy-load the helper. This is fine, but injecting a helper into a console command reinforces the anti-pattern noted in 4.4. Also, a CLI-only wiring should live in a dedicated area (`etc/di.xml` is fine, but the helper should be a service, not a `Helper`).

---

## 8. Security / Data Handling (spot-check)

Files under `Model/Metadata/Form/File` and `Plugin/Model/Customer/Attribute/Validator/File` handle uploaded files. They should be audited for:
- MIME/extension validation against `\Magento\Framework\File\Uploader`.
- Path traversal in stored `value` when read back into the customer address grid.
- CSV export path (`Plugin/Ui/Component/DataProvider/Document`) — verify escaping when custom attribute values contain `=`, `+`, `-`, `@` (CSV injection).

(These are candidates for follow-up rather than confirmed bugs from this scan.)

---

## 9. Compatibility Notes

- Sequence references `Amazon_Payment` — **breaks under Magento 2.4.4+** where that module was removed.
- Plugin on `Magento\Customer\Model\EmailNotification` — API is not marked `@api` in newer Magento releases; verify against target Magento version.
- Preference on `Magento\Sales\Block\Adminhtml\Order\Create\Billing\Address` — this block’s constructor changed signature in recent 2.4 releases; forced preference means the module must be re-released for each Magento minor bump.

---

## 10. Summary of Top Fixes

| # | Priority | Fix |
|---|----------|-----|
| 1 | High     | Remove `Amazon_Payment` and `Bss_OneStepCheckout` from `<sequence>` in `module.xml`, or make them conditional. |
| 2 | High     | De-duplicate the `di.xml` entries (sections 3.1, 3.2, 3.4). |
| 3 | High     | Replace `<preference>` on `Magento\Sales\Block\Adminhtml\Order\...` with plugins or layout overrides. |
| 4 | High     | Declare real `require` entries in `composer.json` for Magento modules; pin `bsscommerce/core` to a version range. |
| 5 | Medium   | Move frontend/webapi plugins from global `etc/di.xml` to `etc/frontend/di.xml` / `etc/webapi_rest/di.xml`. |
| 6 | Medium   | Drop `setup_version` from `module.xml`; rely on declarative schema. |
| 7 | Medium   | Rename `Customerattribute` → `CustomerAttribute` and `CheckBoxs` → `CheckBoxes` (with BC aliases). |
| 8 | Low      | Modernise plugin classes (typed properties, constructor promotion, `readonly`) — see `Gti\Overrides\Plugin\AddressRegionTransformer` as a reference style. |
| 9 | Low      | Fix PSR-4 mapping in `composer.json` to point at a src folder, or ensure no unintended files pollute the namespace root. |

---

## 11. Deep-dive: Structure of Specific Plugin Files

Two files were called out for review. Both are compared against the modern reference style in `app/code/Gti/Overrides/Plugin/AddressRegionTransformer.php` (typed, constructor-promoted, `readonly`, PHP 8.x).

### 11.1 `Plugin/Model/Customer/Address/CustomerAddressDataProvider.php`

**Location vs. purpose mismatch**
- Namespace is `Bss\CustomerAttributes\Plugin\Model\Customer\Address` but the target is `Magento\Customer\Model\Address\CustomerAddressDataProvider` — the folder path should mirror the target: `Plugin\Customer\Model\Address\...`. The `Plugin\Model\...` prefix used here is the module’s own convention and it is inconsistent with the sibling file `Plugin/Customer/Controller/Adminhtml/Address/Save.php` which *does* mirror the target namespace.

**Misleading class docblock**
- Line 31: `@package Bss\CustomerAttributes\Plugin\Model\Entity` — wrong package tag (copy-pasted from another file). This is a classic sign the file was cloned from `Plugin\Model\Entity\Type` and never cleaned up.

**Blanket PMD suppression**
- Lines 29–30 suppress `CyclomaticComplexity` and `UnusedFormalParameter` at class level. The class *does* have unused parameters (`$subject` in `afterGetAddressDataByCustomer`) — that suppression is fine — but suppressing `CyclomaticComplexity` hides the fact that `afterGetAddressDataByCustomer` nests 4 levels of `if/foreach` and should be decomposed.

**Non-modern style (all fixable in one pass)**
- Lines 38–48: untyped `protected` fields with PHPDoc-only types. Compare to the `readonly` promoted properties in `AddressRegionTransformer` (lines 19–26 of the attached file).
- Line 63–73: no constructor promotion, no return types on methods.
- No `declare(strict_types=1);` (unlike the sibling `Save.php` at line 2).

**Method naming**
- Line 82: `public function getLable(...)` — spelling: `getLable` → `getLabel`. This method is `public`, so renaming is a BC break; use a `@deprecated` alias.

**Broken/dead branch in `getLable()`**
- Lines 91–97 return `false` for `frontendInput === 'file'` (among others).
- Lines 98–100 then check `if ($frontendInput == "file" && ...)` — **this branch is unreachable** because the earlier block already returned `false` for `file`. Either the early-return list should exclude `'file'`, or the second `if` is dead code.

**Loose comparisons + repeated equality chain**
- Lines 91–95 use `==` and a repeated `$frontendInput == 'x' || ...`. Prefer `in_array($frontendInput, ['text','textarea','file','date'], true)` with strict comparison.

**Silent `catch (Exception $e)` on public plugin methods**
- Lines 107–110 and 144–146 log critical then return the original data. That means bugs never surface to admins; a mistyped attribute lookup will just quietly leave labels unformatted. At minimum, downgrade to `warning` for expected paths (attribute not found) and rethrow / mark the outer request in error for truly unexpected exceptions.

**`@param` docblock lies about the signature**
- Lines 117 and 120: the docblock advertises `array $result`, but the actual parameter is `$addresses` and it is later re-checked with `is_array($addresses)` (line 123) — the doc says "array" but the code defends against non-arrays. Pick one.

**Business-logic issue**
- Lines 129–134: `formatDate` is applied whenever `frontend_input === 'date'`, but only when `$addressAttr->getData()` returns a non-empty array indexed at `[0]`. Depending on `NotDisplay::getAddressAttributeByCode()`’s contract, this can silently skip formatting when the attribute exists but is loaded differently. Add a guard/log for the missing case.

**Filename extraction**
- Lines 156–163: `getFileName()` uses `strpos($filename, "/")` — Windows-uploaded backslashes are not handled. Use `basename()` (which handles both separators when `DIRECTORY_SEPARATOR` differs, but for URL-style paths `basename(str_replace('\\','/',$filename))` is safer).

---

### 11.2 `Plugin/Customer/Controller/Adminhtml/Address/Save.php`

**This is not a plugin at all**
- Line 32: `class Save extends \Magento\Customer\Controller\Adminhtml\Address\Save` — the class **extends the target controller**. It is intended to be used as a plugin (method `aroundExecute($subject, $proceed)`, lines 130), but simultaneously inherits from the very class it is trying to intercept. That is a serious architectural bug:
  - If wired as a plugin: the inheritance is dead weight, and the `parent::__construct(...)` call still forces the parent’s dependencies to be resolved on every plugin instantiation.
  - If wired as a preference / `<preference>` (which the folder name and inheritance suggest): then `aroundExecute` is *never* invoked, because plugins only fire on the target’s configured type. Whoever wrote this could not decide between plugin and preference, and the file works only under one of the two wirings.
- Verify `etc/di.xml` (or `etc/adminhtml/di.xml`) to see which mode is actually wired. Neither is a good pattern; a `plugin` on `execute` without inheritance is the correct Magento 2 approach.

**Duplicated dependencies**
- Constructor (lines 90–121) injects `AddressRepositoryInterface`, `FormFactory`, `CustomerRepositoryInterface`, `DataObjectHelper`, `AddressInterfaceFactory`, `LoggerInterface`, `JsonFactory` — then passes all of them to `parent::__construct(...)` (lines 110–119). Since the parent already stores them as private, this class re-stores each as a private property (lines 58–88) and uses `$this->...` locally. That is fine only if the plugin path is used; under preference, every future Magento update that changes the parent’s ctor signature will break this file.

**Full copy of core logic**
- `aroundExecute()` (lines 130–208) is a nearly line-for-line copy of `Magento\Customer\Controller\Adminhtml\Address\Save::execute()`. Any bugfix or CVE fix in the Magento core `Save::execute` will NOT reach admins on this store until BSS re-releases. The correct pattern is:
  - `beforeExecute` to normalise/inject data on the request, or
  - `afterExecute` to enrich the JSON response (the *only* thing this class actually adds is `custom_attributes_address` in the JSON at lines 194–206).
- The whole flow of building `$addressToSave`, saving it, and building the JSON should be delegated to `$proceed()`, and only the extra key added afterwards.

**ACL constant that has no effect in a plugin**
- Line 53: `public const ADMIN_RESOURCE = 'Magento_Customer::manage';` — ACL is read from the *controller* class Magento is dispatching, not from a plugin/inherited copy. If this class is wired as a plugin only, this constant is decorative.

**Untyped properties + inconsistent visibility**
- Line 36: `protected $customerAddress;` has no PHPDoc and no type. The rest of the fields are `private` with PHPDoc but not typed (lines 58–88). Should be typed `readonly` promoted properties.

**Missing return type**
- Line 130: `public function aroundExecute($subject, $proceed)` — no return type; docblock says `Json` but the method can also propagate exceptions. Declare `: \Magento\Framework\Controller\ResultInterface|Json` and stop suppressing the parameter list.

**`__($e->getMessage())` anti-pattern**
- Line 183: `$message = __($e->getMessage());` — translating dynamic strings is a well-known Magento anti-pattern (i18n scanners cannot extract them, translations never apply). Log the raw message and show a static translated string.

**Silent generic catch**
- Lines 185–189: catching `\Exception` and setting a generic message. OK for UX, but the response then hides *which* attribute failed — combine with the logger context (`$this->logger->critical($e, ['address_id' => $addressId, 'customer_id' => $customerId])`).

**Bug: `$message` may be undefined**
- If `$this->customerRepository->getById($customerId)` throws before line 170/173, `$message` is set in the catch (NoSuchEntityException). Good.
- But if `$addressForm->extractData(...)` (line 148) throws a non-LocalizedException/non-NoSuchEntity error before either `$message = __('...updated');` or `$message = __('...added');` is set, the code proceeds past the try/catch. The generic catch at line 185 sets `$message`, so this is currently safe — but only because of the generic catch. Any future narrowing of exception types will reintroduce an undefined-variable warning.
- Similarly, `$addressData` is only defined if the try-block progressed past line 148; the `if (isset($addressData))` at line 194 papers over this — meaning **on total failure the JSON response has no body**, and the front-end will see an empty admin response instead of the error message. Move the error branch into its own `setData([...])` call.

**Helper injection**
- Lines 92 and 120: `Customerattribute $helper` — same helper-as-service anti-pattern flagged in section 4.4, plus the class-name casing issue from section 4.5.

**Comparison to the modern reference (`AddressRegionTransformer`)**
| Aspect | `AddressRegionTransformer` (reference) | `CustomerAddressDataProvider` | `Save` |
|---|---|---|---|
| `declare(strict_types=1)` | absent (should add) | absent | present |
| Constructor promotion | yes | no | no |
| `readonly` fields | yes | no | no |
| Typed properties | yes | no | partially (untyped `protected $customerAddress`) |
| Return types on all methods | yes | no | no |
| Extends target of plugin | no | no | **yes (bug)** |
| Copies core logic | no | no | **yes (fragile)** |
| Silent catch of `\Exception` | scoped (email sending) | class-wide | class-wide |
| PMD suppressions | none | class-level | class-level |

### 11.3 Recommended concrete fixes

1. Rewrite `Save.php` as a small `afterExecute` plugin that only appends `custom_attributes_address` to the JSON result; drop the inheritance from the core controller and the copy of `execute()`.
2. In `CustomerAddressDataProvider`, remove the unreachable `file` branch (line 98), rename `getLable` → `getLabel` with a `@deprecated` alias, and replace loose `==` chains with a strict `in_array()`.
3. Modernise both classes: `declare(strict_types=1)`, typed promoted `readonly` constructor properties, return types on every method (use `AddressRegionTransformer` as the template).
4. Fix the class-level docblock `@package` tag in `CustomerAddressDataProvider` and move it to the correct `Plugin\Customer\Model\Address` folder (or normalise the whole module to one convention).
5. Replace catch-`\Exception`-and-swallow with narrow exception types and structured logger context so real errors surface in the admin UI.
6. Ensure the `di.xml` wiring for these two classes matches their design: `CustomerAddressDataProvider` should be `<type name="Magento\Customer\Model\Address\CustomerAddressDataProvider">` (verify), and `Save` should be `<type name="Magento\Customer\Controller\Adminhtml\Address\Save">` with a plain plugin — no `<preference>`.
