Skip to content

Fix/autocomplete choice value removal#1

Open
DhirenMhatre wants to merge 2 commits into
2.3from
fix/autocomplete-choice-value-removal
Open

Fix/autocomplete choice value removal#1
DhirenMhatre wants to merge 2 commits into
2.3from
fix/autocomplete-choice-value-removal

Conversation

@DhirenMhatre
Copy link
Copy Markdown

Q A
Branch? 2.2 or 2.3
Bug fix? no/yes
New feature? no/yes
BC breaks? no/yes
Deprecations? no/yes
Related tickets fixes #X, partially #Y, mentioned in #Z
License MIT

…e issue

When choice_value is set to 'code' on Symfony UX Autocomplete types,
DoctrineChoiceLoader cannot use optimized getEntitiesByIds() query,
causing ALL entities to be loaded instead of just the selected ones.

This change removes choice_value from all UX Autocomplete types,
letting Symfony use the default entity ID which enables the optimized
WHERE id IN (...) query.

Refs: Sylius#17953
…complete

After removing choice_value from autocomplete types, the form values
are now entity IDs instead of codes. This commit updates Behat tests to:

- Use selectByName/removeByName instead of selectByValue/removeByValue
- Use getSelectedItems() or option[selected] text for assertions
- Compare with entity names instead of codes
- Add JS/non-JS driver handling for parent taxon selection

Refs: Sylius#17953
@chay2199
Copy link
Copy Markdown

chay2199 commented Jun 6, 2026

@codity review

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

PR Summary

What Changed

  • Switched autocomplete fields from entity codes to names/descriptors for selection and display across admin forms.
  • Fixed taxon parent lookup to use ID instead of code when generating slugs.
  • Updated Behat tests to use name-based selection and assertions.

Key Changes by Area

Autocomplete Forms: Removed choice_value => 'code' from 6 form types (TaxonAutocompleteType, ProductAutocompleteType, ProductVariantAutocompleteType, ProductAttributeAutocompleteType, ChannelPriceHistoryConfigType, ProductImageType) and ProductOptionAutocompleteType to use default identifier resolution.

Taxon Slug Generation: Fixed generateTaxonSlug() in FormComponent.php to use find($id) instead of findOneBy(['code' => ...]) for correct parent resolution.

Test Infrastructure: Updated helpers and assertions to use name-based selection (selectByName, removeByName) instead of code-based methods.

Files Changed

File Changes Summary
src/Sylius/Behat/Context/Ui/Admin/ManagingCatalogPromotionsContext.php Updated assertions to check against entity names instead of codes
src/Sylius/Behat/Context/Ui/Admin/ManagingProductsContext.php Switched to name-based selection for product associations and image variants
src/Sylius/Behat/Context/Ui/Admin/ManagingTaxonsContext.php Updated taxon parent selection to use names
src/Sylius/Behat/Element/Admin/CatalogPromotion/FormElement.php Changed scope assertion to use variant/taxon names
src/Sylius/Behat/Element/Admin/CatalogPromotion/FormElementInterface.php Updated interface for name-based scope checking
src/Sylius/Behat/Element/Admin/Channel/ExcludeTaxonsFromShowingLowestPriceInputElement.php Updated to use removeByName instead of removeByValue
src/Sylius/Behat/Element/Admin/Product/AssociationsFormElement.php Switched to selectByName for product associations
src/Sylius/Behat/Element/Admin/Product/MediaFormElement.php Added getFirstImageSelectedVariantName() method
src/Sylius/Behat/Element/Admin/Product/MediaFormElementInterface.php Added interface method for variant name retrieval
src/Sylius/Behat/Element/Admin/Taxon/FormElement.php Injected AutocompleteHelperInterface for consistent handling
src/Sylius/Bundle/AdminBundle/Form/Type/ChannelPriceHistoryConfigType.php Removed choice_value => 'code' configuration
src/Sylius/Bundle/AdminBundle/Form/Type/ProductAttributeAutocompleteType.php Removed choice_value => 'code' configuration
src/Sylius/Bundle/AdminBundle/Form/Type/ProductAutocompleteType.php Removed choice_value => 'code' configuration
src/Sylius/Bundle/AdminBundle/Form/Type/ProductImageType.php Removed choice_value => 'code' configuration
src/Sylius/Bundle/AdminBundle/Form/Type/ProductVariantAutocompleteType.php Removed choice_value => 'code' configuration
src/Sylius/Bundle/AdminBundle/Form/Type/TaxonAutocompleteType.php Removed choice_value => 'code' configuration
src/Sylius/Bundle/AdminBundle/Twig/Component/Taxon/FormComponent.php Fixed parent lookup to use find($id) instead of findOneBy(['code' => ...])
src/Sylius/Bundle/ProductBundle/Form/Type/ProductOptionAutocompleteType.php Removed choice_value => 'code' configuration

Review Focus Areas

  • Verify taxon slug generation works correctly with ID-based parent lookup in hierarchical structures.
  • Check that autocomplete selections still resolve properly without explicit choice_value configuration.
  • Confirm Behat test coverage handles both single and multi-select autocomplete scenarios with names.

Architecture

Design Decisions: The shift from codes to names/descriptors for autocomplete values improves UX (human-readable selection) but relies on name uniqueness. The choice_value removal delegates identifier resolution to the parent ResourceAutocompleteChoiceType, which is the intended Symfony form behavior.

Risks: Name-based selection assumes unique, stable names. If names change or duplicate, autocomplete behavior may break. This is an intentional tradeoff for usability over code-based stability. The taxon parent lookup fix corrects a bug where codes were incorrectly used as IDs, but verify no other code-paths depend on the old behavior.

Merge Status

MERGEABLE — PR Score 62/100, above threshold (50). All gates passed.

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

Workflow Diagrams

Automatically generated sequence diagrams showing the workflows in this PR

1. Workflow Analysis

Medium complexity • Components: AutocompleteHelper, CatalogPromotion FormElement, Product AssociationsFormElement

sequenceDiagram
    title Autocomplete Selection Refactoring: Code to Name Based Selection

    participant BehatContext as Behat Context
    participant FormElement as Form Element
    participant AutocompleteHelper as Autocomplete Helper
    participant AutocompleteType as Autocomplete Form Type
    participant Browser as Browser/JS
    participant Entity as Entity Repository

    Note over BehatContext,Entity: OLD FLOW: Selection by Code
    Note over BehatContext,Entity: NEW FLOW: Selection by Name

    rect rgb(230, 245, 255)
        Note over BehatContext,Entity: Phase 1: Test Context Preparation
        BehatContext->>BehatContext: Extract entity names instead of codes
        Note right of BehatContext: variant.getName replaces variant.getCode
        BehatContext->>BehatContext: taxon.getName() replaces taxon.getCode()
        BehatContext->>BehatContext: product.getName() replaces product.getCode()
    end

    rect rgb(255, 245, 230)
        Note over BehatContext,Entity: Phase 2: Form Element Interaction
        BehatContext->>FormElement: selectScopeOption(variantNames)
        Note right of BehatContext: Previously passed variantCodes
        
        FormElement->>AutocompleteHelper: selectByName(name)
        Note right of FormElement: Previously called selectByValuecode
        
        alt Removal Operation
            FormElement->>AutocompleteHelper: removeByName(name)
            Note right of FormElement: Previously called removeByValuecode
        end
    end

    rect rgb(230, 255, 230)
        Note over BehatContext,Entity: Phase 3: Form Type Configuration
        AutocompleteHelper->>AutocompleteType: Configure autocomplete field
        Note right of AutocompleteHelper: choice_value set to name property
        
        AutocompleteType->>AutocompleteType: setChoiceValue('name')
        Note right of AutocompleteType: Previously set to 'code'
    end

    rect rgb(255, 230, 245)
        Note over BehatContext,Entity: Phase 4: Browser Execution
        AutocompleteHelper->>Browser: Type entity name in search field
        Browser->>Entity: Search by name pattern
        Entity-->>Browser: Return matching entities
        Browser->>Browser: Display name-based results
        Browser->>AutocompleteHelper: Confirm selection by name
    end

    rect rgb(245, 255, 230)
        Note over BehatContext,Entity: Phase 5: Verification
        BehatContext->>FormElement: getLastScopeNames()
        Note right of BehatContext: Previously getLastScopeCodes
        
        FormElement-->>BehatContext: Return array of selected names
        BehatContext->>BehatContext: Assert expected name in selection
        Note right of BehatContext: Previously asserted codes
    end

    Note over BehatContext,Entity: Affected Components
    Note over BehatContext: ManagingCatalogPromotionsContext
    Note over BehatContext: ManagingProductsContext
    Note over BehatContext: ManagingTaxonsContext
    Note over FormElement: CatalogPromotion FormElement
    Note over FormElement: Product AssociationsFormElement
    Note over FormElement: MediaFormElement
    Note over FormElement: Taxon FormElement
    Note over AutocompleteType: ProductAutocompleteType
    Note over AutocompleteType: ProductVariantAutocompleteType
    Note over AutocompleteType: ProductAttributeAutocompleteType
Loading

Note: Diagrams show detected patterns only. Complex workflows may require manual review.

Comment on lines 108 to +117
public function hasImageWithVariant(ProductVariantInterface $productVariant): bool
{
$selectedVariantName = $this->getFirstImageSelectedVariantName();

if (null === $selectedVariantName) {
return false;
}

return str_contains($selectedVariantName, $productVariant->getName());
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional High

The hasImageWithVariant method only checks the first image's selected variant instead of searching all images in the gallery for a matching variant. This causes the method to incorrectly return false when a variant is attached to any image other than the first one. The original implementation used a CSS selector to search the entire images container, but the refactored version delegates to getFirstImageSelectedVariantName which explicitly retrieves only the first image subform.

Suggested fix
    public function hasImageWithVariant(ProductVariantInterface $productVariant): bool
        {
            $this->changeTab();
        
            $images = $this->getElement('images');
            $variantElements = $images->findAll('css', '[data-test-product-variant*="' . $productVariant->getName() . '"]');
        
            return count($variantElements) > 0;
        }
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: src/Sylius/Behat/Element/Admin/Product/MediaFormElement.php
Lines: 108-117
Issue Type: functional-high
Severity: high

Issue Description:
The `hasImageWithVariant` method only checks the first image's selected variant instead of searching all images in the gallery for a matching variant. This causes the method to incorrectly return `false` when a variant is attached to any image other than the first one. The original implementation used a CSS selector to search the entire images container, but the refactored version delegates to `getFirstImageSelectedVariantName` which explicitly retrieves only the first image subform.

Current Code:
    public function hasImageWithVariant(ProductVariantInterface $productVariant): bool
    {
        $selectedVariantName = $this->getFirstImageSelectedVariantName();

        if (null === $selectedVariantName) {
            return false;
        }

        return str_contains($selectedVariantName, $productVariant->getName());
    }

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue

return false;
}

return str_contains($selectedVariantName, $productVariant->getName());
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional High

The hasImageWithVariant method uses str_contains() to check if a product variant name matches the selected variant, but this performs a substring match rather than an exact match. This causes false positives where checking for variant "Small" incorrectly returns true when "Extra Small" is selected, since "Small" is a substring of "Extra Small". This leads to unreliable test assertions in image-variant validation.

Suggested change
return str_contains($selectedVariantName, $productVariant->getName());
return $selectedVariantName === $productVariant->getName();
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: src/Sylius/Behat/Element/Admin/Product/MediaFormElement.php
Lines: 116-116
Issue Type: functional-high
Severity: high

Issue Description:
The `hasImageWithVariant` method uses `str_contains()` to check if a product variant name matches the selected variant, but this performs a substring match rather than an exact match. This causes false positives where checking for variant "Small" incorrectly returns true when "Extra Small" is selected, since "Small" is a substring of "Extra Small". This leads to unreliable test assertions in image-variant validation.

Current Code:
        return str_contains($selectedVariantName, $productVariant->getName());

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

Security Scan Summary

Metric Value
Vulnerabilities Critical: 0
Overall Risk Clean
Files Scanned 18

No critical security issues detected

Scan completed in 35.9s

Security scan powered by Codity.ai

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

License Compliance Scan

Metric Value
Packages Scanned 188
High Risk (Strong Copyleft) 0
Medium Risk (Weak Copyleft) 0
Low Risk (Permissive) 22
Unknown License 166

Some packages have unknown licenses - manual review required

Unknown Licenses - 166 packages
  • @sylius-ui/shop file:src/Sylius/Bundle/ShopBundle
  • @sylius-ui/admin file:src/Sylius/Bundle/AdminBundle
  • @symfony/ux-live-component file:vendor/symfony/ux-live-component/assets
  • @symfony/ux-autocomplete file:vendor/symfony/ux-autocomplete/assets
  • @sylius/admin-bundle file:Resources/assets/
  • slugify 1.6
  • webpack 5.72
  • stimulus-use 0.52
  • @sylius/shop-bundle file:Resources/assets/
  • api-platform/doctrine-orm 4.1.7
  • doctrine/dbal 3.9
  • doctrine/doctrine-bundle 2.13
  • api-platform/symfony 4.1.7
  • api-platform/state 4.1.7
  • doctrine/collections 2.2
  • babdev/pagerfanta-bundle 4.4
  • behat/transliterator 1.5
  • doctrine/common 3.2
  • doctrine/persistence 3.3
  • doctrine/event-manager 2.0

...and 146 more

Low Risk Licenses - Top licenses from 22 packages

Apache-2.0 (2 packages)
ISC (1 packages)
MIT (19 packages)

Powered by Codity.ai · Docs

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

Code Quality Report — test-org-codity/Sylius · PR #1

Scanned: 2026-06-06 17:29 UTC | Score: 56/100 | Provider: github

Executive Summary

Severity Count
Critical 0
High 1
Medium 5
Low 1
Top Findings

[CQ-LLM-003] src/Sylius/Behat/Context/Ui/Admin/ManagingCatalogPromotionsContext.php:754 (Error_Handling · HIGH)

Issue: The method itShouldHaveVariantBasedScope does not handle potential null values from getLastScopeNames.
Suggestion: Add null checks to ensure that the method behaves correctly when no names are returned.

$selectedVariants = $this->formElement->getLastScopeNames();

[CQ-LLM-001] src/Sylius/Behat/Context/Ui/Admin/ManagingCatalogPromotionsContext.php:225 (Complexity · MEDIUM)

Issue: The method iAddScopeThatAppliesOnVariants has a cyclomatic complexity that could increase with more conditions.
Suggestion: Consider simplifying the method or breaking it into smaller methods.

public function iAddScopeThatAppliesOnVariants(ProductVariantInterface ...$variants): void

[CQ-LLM-002] src/Sylius/Behat/Context/Ui/Admin/ManagingCatalogPromotionsContext.php:235 (Duplication · MEDIUM)

Issue: The code for selecting scope options is duplicated across multiple methods.
Suggestion: Extract the common logic into a private method to adhere to DRY principles.

$this->formElement->selectScopeOption($variantNames);

[CQ-LLM-007] src/Sylius/Behat/Context/Ui/Admin/ManagingTaxonsContext.php:272 (Maintainability · MEDIUM)

Issue: The use of 'getCode' and 'getName' methods may lead to confusion regarding the purpose of these variables.
Suggestion: Consider renaming the variables to be more descriptive of their content.

Assert::same($this->formElement->getParent(), $taxon->getName());

[CQ-LLM-006] src/Sylius/Behat/Element/Admin/CatalogPromotion/FormElement.php:98 (Testability · MEDIUM)

Issue: The method selectScopeOption directly manipulates the form element, making it hard to test in isolation.
Suggestion: Consider using dependency injection for the form element to improve testability.

public function selectScopeOption(array $names): void

[CQ-LLM-004] src/Sylius/Behat/Element/Admin/CatalogPromotion/FormElement.php:128 (Performance · MEDIUM)

Issue: The method getLastScopeNames may lead to performance issues if the number of options is large.
Suggestion: Consider optimizing the way options are retrieved or processed.

return array_map(fn (NodeElement $element) => $element->getText(), $lastScope->findAll('css', 'option[selected="selected"]'));

[CQ-LLM-005] src/Sylius/Behat/Context/Ui/Admin/ManagingProductsContext.php:965 (Documentation · LOW)

Issue: The method itsImageShouldHaveVariantSelected lacks a detailed docstring explaining its purpose.
Suggestion: Add a docstring to describe the method's functionality and parameters.

public function itsImageShouldHaveVariantSelected(ProductVariantInterface $productVariant): void

Per-File Breakdown

File Critical High Medium Low Total
src/Sylius/Behat/Context/Ui/Admin/ManagingCatalogPromotionsContext.php 0 1 2 0 3
src/Sylius/Behat/Context/Ui/Admin/ManagingProductsContext.php 0 0 0 1 1
src/Sylius/Behat/Context/Ui/Admin/ManagingTaxonsContext.php 0 0 1 0 1
src/Sylius/Behat/Element/Admin/CatalogPromotion/FormElement.php 0 0 2 0 2

Recommendations

  1. Resolve High severity issues, especially error handling gaps and performance bottlenecks.
  • Run automated tests after applying fixes to verify no regressions.

@chay2199
Copy link
Copy Markdown

chay2199 commented Jun 6, 2026

@codity review

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

PR Summary

What Changed

  • Fixed autocomplete field value handling by removing choice_value => 'code' from form types, allowing proper item removal using names instead of entity codes.
  • Fixed taxon parent lookup in slug generation to use ID instead of code, matching form value format.
  • Updated Behat tests to select and assert by name rather than code.

Key Changes by Area

Form Types: Removed explicit choice_value option from 6 autocomplete types (TaxonAutocompleteType, ProductAutocompleteType, ProductVariantAutocompleteType, ProductAttributeAutocompleteType, ChannelPriceHistoryConfigType, ProductImageType, ProductOptionAutocompleteType) to use default name-based values.

Taxon Slug Generation: Fixed generateTaxonSlug() in FormComponent.php to use find($id) instead of findOneBy(['code' => ...]) for parent lookup.

Behat Tests: Updated test helpers and contexts to use selectByName/removeByName and name-based assertions; added getFirstImageSelectedVariantName() to MediaFormElementInterface.

Files Changed

File Changes Summary
src/Sylius/Behat/Context/Ui/Admin/ManagingCatalogPromotionsContext.php Updated to use name-based selection and assertions
src/Sylius/Behat/Context/Ui/Admin/ManagingProductsContext.php Updated to use name-based selection and assertions
src/Sylius/Behat/Context/Ui/Admin/ManagingTaxonsContext.php Updated to use name-based selection and assertions
src/Sylius/Behat/Element/Admin/CatalogPromotion/FormElement.php Updated to use autocompleteHelper for name-based selection
src/Sylius/Behat/Element/Admin/CatalogPromotion/FormElementInterface.php Updated interface for name-based methods
src/Sylius/Behat/Element/Admin/Channel/ExcludeTaxonsFromShowingLowestPriceInputElement.php Updated to use name-based selection
src/Sylius/Behat/Element/Admin/Product/AssociationsFormElement.php Updated to use name-based selection
src/Sylius/Behat/Element/Admin/Product/MediaFormElement.php Added getFirstImageSelectedVariantName() implementation
src/Sylius/Behat/Element/Admin/Product/MediaFormElementInterface.php Added getFirstImageSelectedVariantName() method
src/Sylius/Behat/Element/Admin/Taxon/FormElement.php Updated to use autocompleteHelper for name-based selection
src/Sylius/Bundle/AdminBundle/Form/Type/ChannelPriceHistoryConfigType.php Removed choice_value => 'code' option
src/Sylius/Bundle/AdminBundle/Form/Type/ProductAttributeAutocompleteType.php Removed choice_value => 'code' option
src/Sylius/Bundle/AdminBundle/Form/Type/ProductAutocompleteType.php Removed choice_value => 'code' option
src/Sylius/Bundle/AdminBundle/Form/Type/ProductImageType.php Removed choice_value => 'code' option
src/Sylius/Bundle/AdminBundle/Form/Type/ProductVariantAutocompleteType.php Removed choice_value => 'code' option
src/Sylius/Bundle/AdminBundle/Form/Type/TaxonAutocompleteType.php Removed choice_value => 'code' option
src/Sylius/Bundle/AdminBundle/Twig/Component/Taxon/FormComponent.php Fixed generateTaxonSlug() to use find($id) for parent lookup
src/Sylius/Bundle/ProductBundle/Form/Type/ProductOptionAutocompleteType.php Removed choice_value => 'code' option

Review Focus Areas

  • Verify taxon parent lookup correctly handles ID-based form values in edge cases (root taxons, missing parents).
  • Check that name-based autocomplete selection handles duplicate names correctly across all form types.
  • Confirm Behat test coverage for item removal from autocomplete fields.

Architecture

Design Decisions: The switch from code-based to name-based values in autocomplete fields aligns with how the underlying autocomplete component handles selection internally. This fixes item removal bugs but trades code stability (unique, immutable) for name readability. The taxon slug fix corrects a mismatch between form value format (ID) and repository lookup method (code).

Risks: Name-based values may cause issues if entity names are not unique or change over time. This is an intentional tradeoff for UX improvement. The ProductTaxonAutocompleteChoiceType retains choice_value => 'code' (noted in summary but not in file list), suggesting partial migration. Review if this inconsistency is deliberate.

Merge Status

NOT MERGEABLE — PR Score 44/100, below threshold (50)

  • [H4] PR quality score (44) is below merge floor (50)
  • [H5] 1 CRITICAL inline review finding need resolution

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

Workflow Diagrams

Automatically generated sequence diagrams showing the workflows in this PR

1. Analysis

Medium complexity • Components: AutocompleteHelper, CatalogPromotion FormElement, Product AssociationsFormElement

sequenceDiagram
    title Refactoring Autocomplete from Code-Based to Name-Based Selection

    participant BehatContext as Behat Context
    participant FormElement as Form Element
    participant AutocompleteHelper as Autocomplete Helper
    participant FormType as Form Type
    participant EntityRepository as Entity Repository
    participant Database as Database

    Note over BehatContext,Database: NEW FLOW: Name-based autocomplete selection

    BehatContext->>BehatContext: Extract entity names instead of codes
    Note right of BehatContext: variant.getName replaces variant.getCode

    BehatContext->>FormElement: selectScopeOption(variantNames)
    activate FormElement

    FormElement->>AutocompleteHelper: selectByName(field, names)
    Note right of AutocompleteHelper: NEW METHOD replaces selectByValue

    AutocompleteHelper->>FormType: Search by name pattern
    FormType->>EntityRepository: findByNameLike(name)
    EntityRepository->>Database: SELECT * FROM entity WHERE name LIKE
    Database-->>EntityRepository: matching entities
    EntityRepository-->>FormType: entity results
    FormType-->>AutocompleteHelper: name-value pairs

    AutocompleteHelper->>AutocompleteHelper: select matching options by name
    AutocompleteHelper-->>FormElement: selection confirmed

    FormElement-->>BehatContext: scope option selected

    BehatContext->>FormElement: getLastScopeNames()
    Note right of FormElement: NEW METHOD replaces getLastScopeCodes

    FormElement->>AutocompleteHelper: getSelectedItems(field)
    Note right of AutocompleteHelper: NEW METHOD for verification

    AutocompleteHelper-->>FormElement: selected names array
    FormElement-->>BehatContext: names for assertion

    BehatContext->>BehatContext: Assert entity name in selected names

    deactivate FormElement

    Note over BehatContext,Database: REMOVAL FLOW: Name-based option removal

    BehatContext->>FormElement: removeScopeOption(variantNames)
    FormElement->>AutocompleteHelper: removeByName(field, names)
    Note right of AutocompleteHelper: NEW METHOD replaces removeByValue
    AutocompleteHelper->>FormType: Remove matching name entries
    AutocompleteHelper-->>FormElement: removal confirmed
    FormElement-->>BehatContext: scope option removed
Loading

Note: Diagrams show detected patterns only. Complex workflows may require manual review.

@@ -33,7 +33,6 @@ public function configureOptions(OptionsResolver $resolver): void
$resolver->setDefaults([
'class' => $this->productAttributeClass,
'choice_name' => 'name',
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional Critical

The ProductAttributeAutocompleteType is missing the 'choice_value' => 'code' configuration option. Without it, the autocomplete API endpoint returns entity IDs instead of attribute codes as option values. This causes the product form to send numeric IDs to Product/FormComponent::addAttributes(), which then fails to find attributes by code and throws a TypeError when calling isTranslatable() on a null object.

Suggested fix
            $resolver->setDefaults([
                'class' => $this->productAttributeClass,
                'choice_name' => 'name',
                'choice_value' => 'code',
            ]);
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: src/Sylius/Bundle/AdminBundle/Form/Type/ProductAttributeAutocompleteType.php
Lines: 35-35
Issue Type: functional-critical
Severity: critical

Issue Description:
The `ProductAttributeAutocompleteType` is missing the `'choice_value' => 'code'` configuration option. Without it, the autocomplete API endpoint returns entity IDs instead of attribute codes as option values. This causes the product form to send numeric IDs to `Product/FormComponent::addAttributes()`, which then fails to find attributes by code and throws a TypeError when calling `isTranslatable()` on a null object.

Current Code:
            'choice_name' => 'name',

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue

Comment on lines +110 to +116
$selectedVariantName = $this->getFirstImageSelectedVariantName();

if (null === $selectedVariantName) {
return false;
}

return str_contains($selectedVariantName, $productVariant->getName());
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional High

The hasImageWithVariant() method has two bugs: (1) it only checks the first image subform via getFirstImageSelectedVariantName(), missing variants assigned to other images, and (2) it uses str_contains() for substring matching instead of exact comparison, causing false positives (e.g., 'Red' matches 'Red Large'). The fix must iterate through all image subforms and use exact string comparison.

Suggested fix
        public function hasImageWithVariant(ProductVariantInterface $productVariant): bool
            {
                $this->changeTab();

                $images = $this->getElement('images');
                $imageSubforms = $images->findAll('css', '[data-test-image-subform]');

                foreach ($imageSubforms as $imageSubform) {
                    $variantField = $imageSubform->find('css', '[data-test-product-variant]');
                    if (null === $variantField) {
                        continue;
                    }

                    $selectedOption = $variantField->find('css', 'option[selected]');
                    if (null === $selectedOption) {
                        continue;
                    }

                    if ($selectedOption->getText() === $productVariant->getName()) {
                        return true;
                    }
                }

                return false;
            }
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: src/Sylius/Behat/Element/Admin/Product/MediaFormElement.php
Lines: 110-116
Issue Type: functional-high
Severity: high

Issue Description:
The `hasImageWithVariant()` method has two bugs: (1) it only checks the first image subform via `getFirstImageSelectedVariantName()`, missing variants assigned to other images, and (2) it uses `str_contains()` for substring matching instead of exact comparison, causing false positives (e.g., 'Red' matches 'Red Large'). The fix must iterate through all image subforms and use exact string comparison.

Current Code:
        $selectedVariantName = $this->getFirstImageSelectedVariantName();

        if (null === $selectedVariantName) {
            return false;
        }

        return str_contains($selectedVariantName, $productVariant->getName());

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

Security Scan Summary

Metric Value
Vulnerabilities Critical: 0
Overall Risk Clean
Files Scanned 18

No critical security issues detected

Scan completed in 36.2s

Security scan powered by Codity.ai

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

License Compliance Scan

Metric Value
Packages Scanned 188
High Risk (Strong Copyleft) 0
Medium Risk (Weak Copyleft) 0
Low Risk (Permissive) 22
Unknown License 166

Some packages have unknown licenses - manual review required

Unknown Licenses - 166 packages
  • @symfony/ux-autocomplete file:vendor/symfony/ux-autocomplete/assets
  • @sylius-ui/admin file:src/Sylius/Bundle/AdminBundle
  • @sylius-ui/shop file:src/Sylius/Bundle/ShopBundle
  • @symfony/ux-live-component file:vendor/symfony/ux-live-component/assets
  • @sylius/admin-bundle file:Resources/assets/
  • slugify 1.6
  • stimulus-use 0.52
  • webpack 5.72
  • @sylius/shop-bundle file:Resources/assets/
  • babdev/pagerfanta-bundle 4.4
  • doctrine/collections 2.2
  • api-platform/symfony 4.1.7
  • api-platform/doctrine-orm 4.1.7
  • behat/transliterator 1.5
  • doctrine/common 3.2
  • api-platform/state 4.1.7
  • doctrine/dbal 3.9
  • doctrine/doctrine-bundle 2.13
  • doctrine/doctrine-migrations-bundle 3.3
  • doctrine/event-manager 2.0

...and 146 more

Low Risk Licenses - Top licenses from 22 packages

Apache-2.0 (2 packages)
ISC (1 packages)
MIT (19 packages)

Powered by Codity.ai · Docs

@codity-chait
Copy link
Copy Markdown

codity-chait Bot commented Jun 6, 2026

Code Quality Report — test-org-codity/Sylius · PR #1

Scanned: 2026-06-06 18:17 UTC | Score: 56/100 | Provider: github

Executive Summary

Severity Count
Critical 0
High 1
Medium 5
Low 1
Top Findings

[CQ-LLM-003] src/Sylius/Behat/Context/Ui/Admin/ManagingCatalogPromotionsContext.php:225 (Error_Handling · HIGH)

Issue: The code does not handle potential null values returned from 'getName()'.
Suggestion: Add null checks to ensure that the code does not break if 'getName()' returns null.

array_map(fn (ProductVariantInterface $variant) => $variant->getName(), $variants);

[CQ-LLM-001] src/Sylius/Behat/Context/Ui/Admin/ManagingCatalogPromotionsContext.php:225 (Complexity · MEDIUM)

Issue: The method 'iAddScopeThatAppliesOnVariants' has a cyclomatic complexity that could increase with additional conditions.
Suggestion: Consider simplifying the method or breaking it into smaller methods.

public function iAddScopeThatAppliesOnVariants(ProductVariantInterface ...$variants): void

[CQ-LLM-002] src/Sylius/Behat/Context/Ui/Admin/ManagingCatalogPromotionsContext.php:225 (Duplication · MEDIUM)

Issue: The pattern of mapping variant/taxon codes to names is repeated across multiple methods.
Suggestion: Extract the mapping logic into a separate method to adhere to DRY principles.

array_map(fn (ProductVariantInterface $variant) => $variant->getName(), $variants);

[CQ-LLM-007] src/Sylius/Behat/Context/Ui/Admin/ManagingCatalogPromotionsContext.php:225 (Maintainability · MEDIUM)

Issue: The variable names 'variantCodes' and 'taxonsCodes' are misleading as they now hold names instead of codes.
Suggestion: Rename variables to reflect their actual content, e.g., 'variantNames' and 'taxonNames'.

$variantCodes = array_map(...);

[CQ-LLM-006] src/Sylius/Behat/Context/Ui/Admin/ManagingCatalogPromotionsContext.php:754 (Testability · MEDIUM)

Issue: The method 'itShouldHaveVariantBasedScope' relies on global state through 'sharedStorage'.
Suggestion: Refactor to use dependency injection to improve testability.

$this->sharedStorage->set('catalog_promotion', $catalogPromotion);

[CQ-LLM-004] src/Sylius/Behat/Element/Admin/CatalogPromotion/FormElement.php:99 (Performance · MEDIUM)

Issue: The method 'selectScopeOption' may lead to performance issues if the number of options is large due to multiple DOM queries.
Suggestion: Consider optimizing the selection process to minimize DOM interactions.

foreach ($names as $name) { $this->autocompleteHelper->selectByName(...); }

[CQ-LLM-005] src/Sylius/Behat/Element/Admin/CatalogPromotion/FormElement.php:98 (Documentation · LOW)

Issue: The method 'selectScopeOption' lacks a docstring explaining its parameters and purpose.
Suggestion: Add a docstring to describe the method's functionality and parameters.

public function selectScopeOption(array $names): void

Per-File Breakdown

File Critical High Medium Low Total
src/Sylius/Behat/Context/Ui/Admin/ManagingCatalogPromotionsContext.php 0 1 4 0 5
src/Sylius/Behat/Element/Admin/CatalogPromotion/FormElement.php 0 0 1 1 2

Recommendations

  1. Resolve High severity issues, especially error handling gaps and performance bottlenecks.
  • Run automated tests after applying fixes to verify no regressions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants