Conversation
WalkthroughThe pull request introduces significant changes across multiple classes in the Changes
Possibly related PRs
Suggested labels
Suggested reviewers
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
setIndianStateOptions Hook for Dynamic State Options in CollectionBaseService
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Outside diff range and nitpick comments (6)
wp-content/civi-extensions/goonjcustom/Civi/InductionService.php (4)
Line range hint
826-840: Add error handling for database operationsThe Contact API query could fail, but there's no try-catch block to handle potential exceptions. This could lead to unhandled errors in production.
Consider wrapping the database operation in a try-catch block:
+ try { $officeContact = Contact::get(FALSE) ->addWhere('contact_sub_type', 'CONTAINS', 'Goonj_Office') ->addClause('OR', ['Goonj_Office_Details.Other_Induction_Cities', 'CONTAINS', $contactCityFormatted], ['address_primary.city', 'CONTAINS', $contactCityFormatted] ) ->execute(); + } catch (\Exception $e) { + \Civi::log()->error('Failed to fetch office contact', [ + 'error' => $e->getMessage(), + 'city' => $contactCityFormatted + ]); + return 'Online'; + }
Line range hint
841-845: Remove redundant else blockThe else block is unnecessary as it returns the same value that would be returned if the if-condition is false. This makes the code harder to read without adding any value.
Simplify the logic by removing the else block:
if (!empty($officeDetails)) { return $inductionType; } - else { - $inductionType = 'Online'; - return $inductionType; - } + $inductionType = 'Online'; + return $inductionType;
Line range hint
826-840: Consider case-insensitive city comparisonThe current implementation uses case-sensitive CONTAINS for city matching, which might miss valid matches if the case doesn't match exactly.
Consider using a case-insensitive comparison or normalizing the city names before comparison:
$officeContact = Contact::get(FALSE) ->addWhere('contact_sub_type', 'CONTAINS', 'Goonj_Office') ->addClause('OR', - ['Goonj_Office_Details.Other_Induction_Cities', 'CONTAINS', $contactCityFormatted], - ['address_primary.city', 'CONTAINS', $contactCityFormatted] + ['LOWER(Goonj_Office_Details.Other_Induction_Cities)', 'CONTAINS', strtolower($contactCityFormatted)], + ['LOWER(address_primary.city)', 'CONTAINS', strtolower($contactCityFormatted)] )
Line range hint
826-845: Refactor method for better maintainabilityThe
fetchTypeOfInductionmethod is quite long and handles multiple responsibilities. Consider breaking it down into smaller, more focused methods.Consider extracting the office lookup logic into a separate method:
private static function findGoonjOfficeForCity($cityName) { try { return Contact::get(FALSE) ->addWhere('contact_sub_type', 'CONTAINS', 'Goonj_Office') ->addClause('OR', ['LOWER(Goonj_Office_Details.Other_Induction_Cities)', 'CONTAINS', strtolower($cityName)], ['LOWER(address_primary.city)', 'CONTAINS', strtolower($cityName)] ) ->execute(); } catch (\Exception $e) { \Civi::log()->error('Failed to fetch office contact', [ 'error' => $e->getMessage(), 'city' => $cityName ]); return NULL; } }This would make the main method cleaner and more maintainable.
wp-content/civi-extensions/goonjcustom/Civi/CollectionBaseService.php (2)
521-533: Improve documentation and readability of getStateFieldNamesThe method would benefit from:
- PHPDoc explaining the purpose of the state group mapping
- More readable array transformation
Here's a suggested improvement:
/** + * Returns an array of field names for state fields across different entity types. + * + * Maps entity types to their corresponding custom group names and constructs + * the full field path in the format: {CustomGroupName}.State + * + * @return array Array of field names for state fields */ public static function getStateFieldNames() { $stateGroupNameMapper = [ 'Collection_Camp' => 'Collection_Camp_Intent_Details', 'Dropping_Center' => 'Dropping_Centre', 'Institution_Collection_Camp' => 'Institution_Collection_Camp_Intent', 'Goonj_Activities' => 'Goonj_Activities', 'Institution_Dropping_Center' => 'Institution_Dropping_Center_Intent', ]; - $statefieldNames = array_map(fn ($field) => "{$field}.State", $stateGroupNameMapper); + $stateFieldNames = array_map( + function ($customGroupName) { + return "{$customGroupName}.State"; + }, + $stateGroupNameMapper + ); - return $statefieldNames; + return $stateFieldNames; }
488-533: Consider future extensibility for location-based optionsThe current implementation successfully centralizes state options management, but consider:
- Creating a more generic location options service that could handle:
- Different countries
- Cities and districts
- Custom geographical hierarchies
- Implementing a caching mechanism for frequently accessed location data
- Adding support for location validation rules
This would make the system more maintainable and scalable for future requirements.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (7)
wp-content/civi-extensions/goonjcustom/Civi/CollectionBaseService.php(3 hunks)wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php(0 hunks)wp-content/civi-extensions/goonjcustom/Civi/DroppingCenterService.php(0 hunks)wp-content/civi-extensions/goonjcustom/Civi/GoonjActivitiesService.php(0 hunks)wp-content/civi-extensions/goonjcustom/Civi/InductionService.php(2 hunks)wp-content/civi-extensions/goonjcustom/Civi/InstitutionCollectionCampService.php(0 hunks)wp-content/civi-extensions/goonjcustom/Civi/InstitutionDroppingCenterService.php(0 hunks)
💤 Files with no reviewable changes (5)
- wp-content/civi-extensions/goonjcustom/Civi/InstitutionCollectionCampService.php
- wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php
- wp-content/civi-extensions/goonjcustom/Civi/DroppingCenterService.php
- wp-content/civi-extensions/goonjcustom/Civi/GoonjActivitiesService.php
- wp-content/civi-extensions/goonjcustom/Civi/InstitutionDroppingCenterService.php
🔇 Additional comments (2)
wp-content/civi-extensions/goonjcustom/Civi/CollectionBaseService.php (2)
16-16: LGTM: StateProvince API import follows existing patterns
The import is correctly placed with other API imports and follows the established naming conventions.
47-47: LGTM: Hook registration is properly implemented
The hook registration follows the established pattern in getSubscribedEvents.
| public static function setIndianStateOptions(string $entity, string $field, ?array &$options, array $params) { | ||
| if ($entity !== 'Eck_Collection_Camp') { | ||
| return; | ||
| } | ||
|
|
||
| $stateFieldNames = self::getStateFieldNames(); | ||
|
|
||
| if (!in_array($field, $stateFieldNames)) { | ||
| return; | ||
| } | ||
|
|
||
| $indianStates = StateProvince::get(FALSE) | ||
| ->addWhere('country_id.iso_code', '=', 'IN') | ||
| ->addOrderBy('name', 'ASC') | ||
| ->execute(); | ||
|
|
||
| $stateOptions = []; | ||
| foreach ($indianStates as $state) { | ||
| if ($state['is_active']) { | ||
| $stateOptions[$state['id']] = $state['name']; | ||
| } | ||
| } | ||
|
|
||
| $options = $stateOptions; | ||
|
|
||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Enhance error handling and reduce nesting in setIndianStateOptions
Consider the following improvements:
- Use early returns to reduce nesting
- Add error handling for the StateProvince API call
- Consider making the country code configurable for better reusability
Here's a suggested refactor:
public static function setIndianStateOptions(string $entity, string $field, ?array &$options, array $params) {
- if ($entity !== 'Eck_Collection_Camp') {
- return;
- }
+ if ($entity !== 'Eck_Collection_Camp' || !in_array($field, self::getStateFieldNames())) {
+ return;
+ }
- $stateFieldNames = self::getStateFieldNames();
+ try {
+ $indianStates = StateProvince::get(FALSE)
+ ->addWhere('country_id.iso_code', '=', 'IN')
+ ->addOrderBy('name', 'ASC')
+ ->execute();
- if (!in_array($field, $stateFieldNames)) {
- return;
- }
-
- $indianStates = StateProvince::get(FALSE)
- ->addWhere('country_id.iso_code', '=', 'IN')
- ->addOrderBy('name', 'ASC')
- ->execute();
-
- $stateOptions = [];
- foreach ($indianStates as $state) {
- if ($state['is_active']) {
- $stateOptions[$state['id']] = $state['name'];
- }
- }
+ $options = array_reduce($indianStates, function ($carry, $state) {
+ if ($state['is_active']) {
+ $carry[$state['id']] = $state['name'];
+ }
+ return $carry;
+ }, []);
- $options = $stateOptions;
+ } catch (\Exception $e) {
+ \Civi::log()->error('Failed to fetch state options', [
+ 'error' => $e->getMessage(),
+ 'entity' => $entity,
+ 'field' => $field
+ ]);
+ $options = [];
+ }
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| public static function setIndianStateOptions(string $entity, string $field, ?array &$options, array $params) { | |
| if ($entity !== 'Eck_Collection_Camp') { | |
| return; | |
| } | |
| $stateFieldNames = self::getStateFieldNames(); | |
| if (!in_array($field, $stateFieldNames)) { | |
| return; | |
| } | |
| $indianStates = StateProvince::get(FALSE) | |
| ->addWhere('country_id.iso_code', '=', 'IN') | |
| ->addOrderBy('name', 'ASC') | |
| ->execute(); | |
| $stateOptions = []; | |
| foreach ($indianStates as $state) { | |
| if ($state['is_active']) { | |
| $stateOptions[$state['id']] = $state['name']; | |
| } | |
| } | |
| $options = $stateOptions; | |
| } | |
| public static function setIndianStateOptions(string $entity, string $field, ?array &$options, array $params) { | |
| if ($entity !== 'Eck_Collection_Camp' || !in_array($field, self::getStateFieldNames())) { | |
| return; | |
| } | |
| try { | |
| $indianStates = StateProvince::get(FALSE) | |
| ->addWhere('country_id.iso_code', '=', 'IN') | |
| ->addOrderBy('name', 'ASC') | |
| ->execute(); | |
| $options = array_reduce($indianStates, function ($carry, $state) { | |
| if ($state['is_active']) { | |
| $carry[$state['id']] = $state['name']; | |
| } | |
| return $carry; | |
| }, []); | |
| } catch (\Exception $e) { | |
| \Civi::log()->error('Failed to fetch state options', [ | |
| 'error' => $e->getMessage(), | |
| 'entity' => $entity, | |
| 'field' => $field | |
| ]); | |
| $options = []; | |
| } | |
| } |
This pull request introduces a new
hook_civicrm_fieldOptionsin theCollectionBaseServiceclass to dynamically populate Indian state options for specific fields. The refactoring adds extensibility and scalability to the handling of state-related options, making future development more modular and maintainable.Why Refactored?
How to Extend in the Future
getStateFieldNames()utility to include more fields requiring dynamic options.Summary by CodeRabbit
Release Notes
New Features
Eck_Collection_Campentity.Bug Fixes
Refactor
fetchTypeOfInductionmethod for better readability.Chores